Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vnisor/5ba4bcc59dd5455ac826172a8aab42f2 to your computer and use it in GitHub Desktop.
Save vnisor/5ba4bcc59dd5455ac826172a8aab42f2 to your computer and use it in GitHub Desktop.
Easy example of indexing geo-based domain objects to ElasticSearch via #nest
using Nest;
using System;
using System.Globalization;
namespace elasticsearch_nest_geoindex_demo
{
public class Location
{
public string Name { get; set; }
public Coordinate CoordinateObject { get; set; }
public Coordinate CoordinateString { get; set; }
}
public class Coordinate
{
public double Lat { get; set; }
public double Lon { get; set; }
}
internal class Program
{
private static void Main(string[] args)
{
var client = new ElasticClient(new ConnectionSettings(new Uri("http://localhost:9200"))
.SetDefaultIndex("geopoint-tests")
.SetTimeout(30 * 1000));
var rootNodeInfo = client.RootNodeInfo();
if (!rootNodeInfo.ConnectionStatus.Success)
throw new ApplicationException("Could not connect to ElasticSearch!",
rootNodeInfo.ConnectionStatus.OriginalException);
if (client.IndexExists(i => i.Index("geopoint-tests")).Exists)
client.DeleteIndex(i => i.Index("geopoint-tests")); //scrub the index
client.CreateIndex("geopoint-tests", s => s
.AddMapping<Location>(f => f
.MapFromAttributes()
.Properties(p => p
.GeoPoint(g => g.Name(n => n.CoordinateObject).IndexLatLon())
.GeoPoint(g => g.Name(n => n.CoordinateString).IndexLatLon())
)
)
);
//index a few points
client.IndexMany(new[]
{
createLocation("Amsterdam", 52.3740300, 4.8896900),
createLocation("Rotterdam", 51.9225000, 4.4791700),
createLocation("Utrecht", 52.0908300, 5.1222200),
createLocation("Den Haag", 52.0908300, 5.1222200)
});
//find locations within 10km of schiphol airport
var results = client.Search<Location>(s => s
.Filter(f => f
.GeoDistance(
n => n.CoordinateObject,
d => d.Distance(20.0, GeoUnit.km).Location(52.310551, 4.76974)
)
)
);
foreach (var doc in results.Documents)
Console.WriteLine("Found: " + doc.Name);
Console.WriteLine("Done.");
Console.ReadLine();
}
private static Location createLocation(string name, double latitude, double longitude)
{
return new Location
{
Name = name,
CoordinateObject = new Coordinate { Lat = latitude, Lon = longitude },
CoordinateString =
string.Format("{0},{1}", latitude.ToString(CultureInfo.InvariantCulture),
longitude.ToString(CultureInfo.InvariantCulture))
};
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment