How to read ScriptField from search response using NEST


(Hooman Bahreini) #1

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
    },
    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 the type
}                                  

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

Distance


(system) #2

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.