如何使用elasticsearch nest客户端按id查询特定文档

4jb9z9bj  于 2021-06-14  发布在  ElasticSearch
关注(0)|答案(1)|浏览(832)

我要检索一个特定的文档。id值是由ElasticSearch分配的,因此不会出现在 _source 文件的第节。
我认为应该有一个 Ids 函数,但在嵌套文档中找不到它。结果如下: 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客户机没有对应的示例
ma8fv8wu

ma8fv8wu1#

如果在将文档索引到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,就可以使用getapi检索文档

var getResponse = client.Get<MyDocument>(id, g => g.Index("my_documents"));

var fetchedDocument = getResponse.Source;
``` `getResponse` 包含文档元数据,如索引、序列号、路由等。
还可以使用源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可以跨不同索引将文档作为目标,这些索引可能Map到应用程序中的不同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可以在索引文档之后立即检索它们。相反,索引文档只有在索引刷新后才会显示在搜索结果中。

相关问题