I have a POCO that has a coordinate field, and the mapping and geodistance search with NEST all works as expected. However, what I'm trying to do with NEST is to also return the distance from the point specified in the GeoDistance query as part of the search results. My research thus far indicates that there are two ways to do this:
I decided to run with option 2, and here's what some of the code looks like:
public class User
{
public int ID { get; set; }
[GeoPoint]
public Coordinate Location { get; set; }
}
And the query itself:
var results = elasticClient.Search<User>(s => s
.Index("user")
.Query(q => q
.GeoDistance(gd => gd
.Field(f => f.Location)
.Distance(Distance.Miles(distance))
.Location(GeoLocation.TryCreate(data.Latitude, data.Longitude))
) && q
.Exists(e => e
.Field("location")
)
)
.ScriptFields(sf => sf
.ScriptField("distance", sf2 => sf2
.Inline(String.Format("doc['location'].arcDistance({0},{1})", data.Latitude, data.Longitude))
.Lang("painless")
)
)
);
While running this query directly against elasticsearch seems fine, when I do it NEST I have a few issues:
My question is: what is the recommended way to access script fields in NEST? Do I have to forego auto-mapping entirely? Or should I just go for the sort option even though I don't particularly want to sort the results?
I eventually managed to get close to what I wanted by:
[ElasticsearchType(Name = "User")]
attribute to my Search Result subclasswhen enumerating through the Hits
in the result, accessing my script field:
((JArray)item.Fields["distance"]).Value<double>(0) / 1609.344
If anyone has a cleaner way of doing this, please do let me know!