如何从 Elasticsearch 响应中读取距离

How to read distance from Elasticsearch response

我正在使用 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
}                                  

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

我找到了答案here

阅读搜索文档和距离:

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");
}