簡體   English   中英

如何使用 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;

Rest 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 的子集進行過濾,可以使用 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 可以在索引后立即檢索文檔。 相比之下,索引文檔只有在索引刷新后才會出現在搜索結果中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM