ElasticSearch and Nest: Why amd I missing the id field on a query?

左心房为你撑大大i 提交于 2019-12-05 13:31:16

There is a way to get the internal id, as described in this issue requesting this very feature.

Rather than using response.Documents, do this instead:

var results = response.Hits.Select(hit =>
    {
        var result = hit.Source;
        result.Id = hit.Id;
        return result;
    });

Elasticsearch sets an "_id" meta-data parameter (for which it chooses a value if you don't specify one), but it doesn't set that value in your document source.

To illustrate, if I create a trivial index:

PUT /test_index

then give it a couple of documents, without specifying "_id":

POST /test_index/doc/_bulk
{"index":{}}
{"id":null,"name":"doc1"}
{"index":{}}
{"id":null,"name":"doc2"}

and then search:

POST /test_index/_search

this is what I get back:

{
   "took": 2,
   "timed_out": false,
   "_shards": {
      "total": 5,
      "successful": 5,
      "failed": 0
   },
   "hits": {
      "total": 2,
      "max_score": 1,
      "hits": [
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "AVEmuVlmj_RE0PsHCpza",
            "_score": 1,
            "_source": {
               "id": null,
               "name": "doc2"
            }
         },
         {
            "_index": "test_index",
            "_type": "doc",
            "_id": "AVEmuVlmj_RE0PsHCpzZ",
            "_score": 1,
            "_source": {
               "id": null,
               "name": "doc1"
            }
         }
      ]
   }
}

Notice that the "_id" meta-data parameter was set for both documents, but the "id" field I passed is unchanged. That's because, as far as Elasticsearch is concerned, "id" is just another document field.

(here is the code I used: http://sense.qbox.io/gist/777dafae88311c4105453482050c64d69ccd09db)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!