0

我正在使用Elasticsearch V6NEST V6

我正在搜索 ES,如下所示,我正在使用 ScriptFields 来计算距离并将其包含在结果中。

var searchResponse = _elasticClient.Search<MyDocument>(new SearchRequest<MyDocument>
{
    Query = new BoolQuery
    {
        Must = new QueryContainer[] { matchQuery },
        Filter = new QueryContainer[] { filterQuery },
    },
    Source = new SourceFilter
    {
        Includes = resultFields    // fields to be included in the result
    },
    ScriptFields = new ScriptField
    {
        Script = new InlineScript("doc['geoLocation'].planeDistance(params.lat, params.lng) * 0.001")   // divide by 1000 to convert to km
        {
            Lang = "painless",
            Params = new FluentDictionary<string, object>
            {
                { "lat", _center.Latitude },
                { "lng", _center.Longitude }
            }
        }
    }
});

现在,我正在尝试读取搜索结果,但我不确定如何读取与响应的距离,这就是我尝试过的:

// this is how I read the Document, all OK here
var docs = searchResponse.Documents.ToList<MyDocument>();

// this is my attempt to read the distance from the result
var hits = searchResponse.Hits;
foreach (var h in hits)
{
    var d = h.Fields["distance"];
    // d is of type Nest.LazyDocument 
    // I am not sure how to get the distance value from object of type LazyDocument
}                                  

在调试时我可以看到距离值,我只是不确定如何读取该值?

在此处输入图像描述

4

1 回答 1

2

我在这里找到了答案

阅读搜索文档和距离:

foreach (var hit in searchResponse.Hits)
{
    MyDocument doc = hit.Source;    
    double distance = hit.Fields.Value<double>("distance");  
}

如果您只对距离感兴趣:

foreach (var fieldValues in searchResponse.Fields)
{
    var distance = fieldValues.Value<double>("distance");
}
于 2018-07-03T23:51:18.427 回答