如何使用elasticsearch Nest客户端通过_id查询特定文档

How to query for a specific document by _id using the elasticsearch Nest client

我有一份要检索的特定文档。 id 值由弹性搜索分配,因此不会出现在文档的 _source 部分。

我相信应该有一个 Ids 函数,但我在 NEST 文档中找不到它。 结果如下: Cannot convert lambda expression to type 'Id' because it is not a delegate type

var queryResponse = 
  client.Search<Dictionary<string, object>>(
    s => s.Query(
      q => q.Ids( 
        i => i.Values(v => "_id_assigned_by_elastic")
      )
    )
  ).Hits.FirstOrDefault();

Dictionary<string,object> doc = h.Source;

其余 API 文档显示此示例:

{
  "query": {
    "ids" : {
      "values" : ["1", "4", "100"]
    }
  }
}

C#和NEST客户端没有对应的例子

如果在将文档索引到 Elasticsearch 时没有指定 id,Elasticsearch 将自动为该文档生成一个 id。此 ID 将在索引响应中返回,并且是文档元数据的一部分。相比之下,发送到 Elasticsearch 的 JSON 文档将被持久化为文档的 _source.

假设 JSON 文档使用以下 POCO 建模

public class MyDocument
{
    public string Property1 { get; set; }
}

使用 Nest 索引到 Elasticsearch 时获取文档的 ID

var client = new ElasticClient();

var document = new MyDocument
{
    Property1 = "foo"
};

var indexResponse = client.Index(document, i => i.Index("my_documents"));

var id = indexResponse.Id;

有了id,可以用Get API

检索文档
var getResponse = client.Get<MyDocument>(id, g => g.Index("my_documents"));
    
var fetchedDocument = getResponse.Source;

getResponse除来源外还包含文档元数据,如索引、序号、路由等。

还有 Source API 可用于检索 只是 文档 _source

var sourceResponse = client.Source<MyDocument>(id, g => g.Index("my_documents"));
    
var fetchedDocument = sourceResponse.Body;

如果想通过id检索多个文档,可以使用MultiGet API

var ids = new long[] { 1, 2, 3 };

var multiGetResponse = client.MultiGet(m => m
    .Index("my_documents")
    .GetMany<MyDocument>(ids, (g, id) => g.Index(null))
);


var fetchedDocuments = multiGetResponse.GetMany<MyDocument>(ids).Select(h => h.Source);

Multi Get API 可以跨不同索引定位文档,这些索引可能映射到您应用程序中的不同 POCO。

最后,如果您想在搜索时按文档 ID 的子集进行过滤,您可以使用 ID 查询

var ids = new long[] { 1, 2, 3 };

var multiGetResponse = client.Search<MyDocument>(s => s
    .Index("my_documents")
    .Query(q => q
        .Ids(i => i
            .Values(ids)
        )
    )
);

请注意,Get、Source 和 MultiGet APIs 可以在索引后立即检索文档。相比之下,索引文档只有在刷新索引后才会显示在搜索结果中。