【问题标题】:Automatic id generation and mapping _id NEST自动 id 生成和映射 _id NEST
【发布时间】:2015-03-12 20:07:12
【问题描述】:

我希望在将文档索引到弹性搜索时自动生成 id。当我没有在我的 poco 中指定 Id 属性时,这可以正常工作。

我想做的是在获取时将底层 _id 字段映射到我的 poco 类上,并在索引时使用自动生成的 id。看起来我可以指定 id 或根本不指定。我缺少他们的任何嵌套 api 选项吗?

编辑

示例要点 https://gist.github.com/antonydenyer/9074159

【问题讨论】:

  • 如果您使用 POST 而不是 PUT 发出 http 请求,elasticsearch 将自动创建 id。

标签: elasticsearch nest


【解决方案1】:

正如@Duc.Duong 在 cmets 中所说,您可以使用 DocumentWithMeta 访问 Id。 在当前版本的 NEST 中,DocumentsWithMetaDataHits 替换,您还应该将 IHit<DataForGet>.Idstring 转换为 int

这是我的代码:

public class DataForIndex
{
    public string Name { get; set; }
    // some other fields...
}

public class DataForGet : DataForIndex
{
    public int Id { get; set; }
}

var result = client.Search<DataForGet>(x => x.Index("index").MatchAll());
var list = results.Hits.Select(h =>
                                   {
                                       h.Source.Id = Convert.ToInt32(h.Id);
                                       return h.Source;
                                   }).ToList();

【讨论】:

    【解决方案2】:

    Automatic ID Generation

    可以在不指定id的情况下执行索引操作。在这种情况下,将自动生成一个 id。另外,op_type 会自动设置为create。这是一个示例(注意使用 POST 而不是 PUT):

    $ curl -XPOST 'http://localhost:9200/twitter/tweet/' -d '{
      "user" : "kimchy",
      "post_date" : "2009-11-15T14:12:12",
      "message" : "trying out Elasticsearch"
    }'
    

    结果:

    {
      "_index" : "twitter",
      "_type" : "tweet",
      "_id" : "6a8ca01c-7896-48e9-81cc-9f70661fcb32",
      "_version" : 1,
      "created" : true
    }
    

    【讨论】:

    • 是的,注意使用 POST 而不是 PUT
    【解决方案3】:

    似乎 NEST 会自动检测类中的“Id”字段并将其映射到 ES 中的“_id”。您的要求看起来很奇怪,但为什么不为其创建 2 个类呢?一种用于索引(无Id字段),一种用于获取(从索引类继承并声明新字段“Id”)?

    例如:

    public class DataForIndex
    {
        public string Name { get; set; }
        // some other fields...
    }
    
    public class DataForGet : DataForIndex
    {
        public int Id { get; set; }
    }
    

    【讨论】:

    • 感谢您的回复,很遗憾这不起作用。目前我只是通过其他方式来丰富课堂。它不是很优雅,只是想知道是否有更好的方法。
    • @antonydenyer 您能否更新您的问题,说明为什么 Duc.Duong 建议的答案不起作用?这是解决此问题的最佳方法,但您还必须考虑嵌套尝试猜测您使用的类的索引和类型名称。您可以通过在 ConnectionSettings 上指定类如何映射到索引/类型名来修复它们。
    • @MartijnLaarman 我会尝试花一些时间来举例说明我的意思,并在我这样做时在此处发布要点。 Duc-duong 的建议是有道理的,但不幸的是它对我来说开箱即用。我似乎记得在装饰班级并指定类型时,但我不能确定。可能就是这样。
    • 为此花费了多长时间向所有人道歉。这就是我要说的gist.github.com/antonydenyer/9074159
    • 是的,我明白了,NEST 中似乎有一个错误,Id 字段在继承的类中无法正确序列化,您可以在 github NEST 项目上报告错误。现在你可以使用 DocumentWithMeta 来获取 ID:var item = client.Search&lt;DataForGet&gt;(x =&gt; x.Index("index").MatchAll()); var list = item.DocumentsWithMetaData.Select(x =&gt; { x.Source.Id = x.Id; return x.Source; }).ToList();
    猜你喜欢
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    相关资源
    最近更新 更多