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

sch*_*lop 4 c# elasticsearch nest

我有一个要检索的特定文档。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;
Run Code Online (Sandbox Code Playgroud)

Rest API 文档展示了这个例子:

{
  "query": {
    "ids" : {
      "values" : ["1", "4", "100"]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Rus*_*Cam 9

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

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

public class MyDocument
{
    public string Property1 { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

使用 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;
Run Code Online (Sandbox Code Playgroud)

通过 id,可以使用Get API检索文档

var client = new ElasticClient();

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

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

var id = indexResponse.Id;
Run Code Online (Sandbox Code Playgroud)

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

还有可用于检索文档的Source API_source

var getResponse = client.Get<MyDocument>(id, g => g.Index("my_documents"));
    
var fetchedDocument = getResponse.Source;
Run Code Online (Sandbox Code Playgroud)

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

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

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

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

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);
Run Code Online (Sandbox Code Playgroud)

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