我尝试使用NEST ElasticClient执行搜索,仅获取匹配的_id。
这是我的代码:
var client = new ElasticClient();
var searchResponse = client.Search<ElasticResult>(new SearchRequest {
From = this.query.Page * 100,
Size = 100,
Source = new SourceFilter {
Includes = "_id"
},
Query = new QueryStringQuery {
Query = this.query.Querystring
}
});
public class ElasticResult {
public string _id;
}
但是,文档(ElasticResult-Objects)的_id始终为null。我究竟做错了什么?
最佳答案
_id
不是_source
文档的一部分,而是hits数组中每个匹配项的匹配项元数据的一部分。
仅返回_id
字段的最紧凑方法是使用using response filtering,该方法在NEST中作为FilterPath
公开
private static void Main()
{
var defaultIndex = "documents";
var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
var settings = new ConnectionSettings(pool)
.DefaultIndex(defaultIndex)
.DefaultTypeName("_doc");
var client = new ElasticClient(settings);
if (client.IndexExists(defaultIndex).Exists)
client.DeleteIndex(defaultIndex);
client.Bulk(b => b
.IndexMany<object>(new[] {
new { Message = "hello" },
new { Message = "world" }
})
.Refresh(Refresh.WaitFor)
);
var searchResponse = client.Search<object>(new SearchRequest<object>
{
From = 0 * 100,
Size = 100,
FilterPath = new [] { "hits.hits._id" },
Query = new QueryStringQuery
{
Query = ""
}
});
foreach(var id in searchResponse.Hits.Select(h => h.Id))
{
// do something with the ids
Console.WriteLine(id);
}
}
从Elasticsearch对搜索请求的JSON响应如下所示
{
"hits" : {
"hits" : [
{
"_id" : "6gs8lmQB_8sm1yFaJDlq"
},
{
"_id" : "6Qs8lmQB_8sm1yFaJDlq"
}
]
}
}
关于c# - 使用NEST ElasticClient仅检索内部_id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51327364/