Skip to content

Instantly share code, notes, and snippets.

@thdotnet
Forked from Mark-Broadhurst/Program.cs
Created March 9, 2020 21:37
Show Gist options
  • Select an option

  • Save thdotnet/2ed970cf7ac3725bb52ea445a30f7984 to your computer and use it in GitHub Desktop.

Select an option

Save thdotnet/2ed970cf7ac3725bb52ea445a30f7984 to your computer and use it in GitHub Desktop.
Lucence Spatial Search 3.0.3
namespace LuceneExample
{
#region Namespaces
using System;
using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Spatial.Queries;
using Lucene.Net.Spatial.Vector;
using Lucene.Net.Store;
using Spatial4n.Core.Context;
using Spatial4n.Core.Shapes;
#endregion
public static class Program
{
private static readonly SpatialContext context = new SpatialContext(true);
private static PointVectorStrategy strategy;
private static void AddPoint(IndexWriter writer, string name, double lng, double lat)
{
Point shape = context.MakePoint(lng, lat);
var doc = new Document();
foreach (var fld in strategy.CreateIndexableFields(shape))
{
doc.Add(fld);
}
doc.Add(new Field("Name", name, Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
writer.AddDocument(doc);
}
private static void Main()
{
strategy = new PointVectorStrategy(context, "Location");
using (var dir = new RAMDirectory())
{
using (var writer = new IndexWriter(dir, new SimpleAnalyzer(), true, IndexWriter.MaxFieldLength.UNLIMITED))
{
AddPoint(writer, "London", -81.233040, 42.983390);
AddPoint(writer, "East New York", -73.882360, 40.666770);
AddPoint(writer, "Manhattan", -73.966250, 40.783430);
AddPoint(writer, "New York City", -74.005970, 40.714270);
AddPoint(writer, "Oslo", 10.746090, 59.912730);
AddPoint(writer, "Bergen", 5.324150, 60.392990);
AddPoint(writer, "Washington, D. C.", -77.036370, 38.895110);
}
// Origin point - Oslo Spektrum
const double lat = 59.9138688;
const double lng = 10.752245399999993;
const double radius = 180;
var query = strategy.MakeQuery(new SpatialArgs(SpatialOperation.IsWithin, context.MakeCircle(lng, lat, radius)));
using (var searcher = new IndexSearcher(dir))
{
var results = searcher.Search(query, null, 100);
foreach (var topDoc in results.ScoreDocs)
{
var name = searcher.Doc(topDoc.Doc).Get("Name");
Console.WriteLine(name);
}
}
}
Console.ReadLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment