【问题标题】:How to query for a specific document by _id using the elasticsearch Nest client如何使用 elasticsearch Nest 客户端通过 _id 查询特定文档
【发布时间】:2020-09-16 21:23:08
【问题描述】:

我有一个要检索的特定文档。 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;

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

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

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

【问题讨论】:

标签: c# elasticsearch nest


【解决方案1】:

在将文档索引到 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 的子集进行过滤,可以使用 Ids 查询

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 API 可以在文档被编入索引后立即检索它们。相比之下,索引文档只有在索引刷新后才会显示在搜索结果中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-22
    • 2015-02-19
    • 2019-09-07
    • 2011-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    相关资源
    最近更新 更多