Search code examples
elasticsearchnestelasticsearch.net

How to read distance from Elasticsearch response


I am using Elasticsearch V6, NEST V6.

I am searching ES as below and I am using ScriptFields to calculate the distance and include it the result.

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

Now, I am trying to read the search result and I am not sure how to read the distance from the response, this is what I have tried:

// 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
}                                  

While debugging I can see the distance value, I am just not sure how to read the value?

enter image description here


Solution

  • I found the answer here

    To read search document and distance:

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

    And if you are only interested in distance:

    foreach (var fieldValues in searchResponse.Fields)
    {
        var distance = fieldValues.Value<double>("distance");
    }