Example #1
0
        static void Main(string[] args)
        {
            const Version version = Lucene.Net.Util.Version.LUCENE_30;

            Directory dir      = new RAMDirectory();
            Analyzer  analyzer = new StandardAnalyzer(version);

            var indexWriter = new IndexWriter(dir, analyzer, IndexWriter.MaxFieldLength.UNLIMITED);

            SpatialContext ctx = SpatialContext.GEO;

            // BBoxStrategy
            //var strategy = new BBoxStrategy(ctx, "spartial"); // Can only index and search by retangle

            // TermQueryPrefixTreeStrategy
            //SpatialPrefixTree grid = new GeohashPrefixTree(ctx, 8);
            //var strategy = new TermQueryPrefixTreeStrategy(grid, "spartial"); // Only supports SpatialOperation.Intersects

            // RecursivePrefixTreeStrategy
            SpatialPrefixTree grid = new GeohashPrefixTree(ctx, 8);
            var strategy           = new RecursivePrefixTreeStrategy(grid, "spartial");



            // PointVectorStrategy
            //var strategy = new PointVectorStrategy(ctx, "pointvector");

            foreach (var doc in CreateDocuments(strategy))
            {
                indexWriter.AddDocument(doc);
            }
            indexWriter.Commit();
            indexWriter.Dispose();


            var searcher = new IndexSearcher(dir, true);

            Point littleMermaid = ctx.MakePoint(12.599239, 55.692848);



            // PointVectorStrategy
            //TopDocs hits = DistanceQueryAndSort_PointVectorStrategy(searcher, strategy, littleMermaid);
            //TopDocs hits = DistanceFilter_PointVectorStrategy(searcher, strategy, littleMermaid);
            //TopDocs hits = DistranceScore_PointVectorStrategy(searcher, strategy, littleMermaid);

            // TermQueryPrefixTreeStrategy
            //TopDocs hits = DistanceFilter_TermQueryPrefixTreeStrategy(searcher, strategy, littleMermaid);

            // RecursivePrefixTreeStrategy
            TopDocs hits = DistanceFilter_RecursivePrefixTreeStrategy(searcher, strategy, littleMermaid);

            Console.WriteLine("Found {0} document(s) that matched query:", hits.TotalHits);
            foreach (ScoreDoc match in hits.ScoreDocs)
            {
                Document doc = searcher.Doc(match.Doc);
                Console.WriteLine("Matched {0} (score: {1})", doc.Get("id"), match.Score);
            }
            searcher.Dispose();
        }
Example #2
0
        //@ParametersFactory
        public static IList <Object[]> Parameters()
        {
            List <Object[]> ctorArgs = new List <object[]>();

            SpatialContext    ctx = SpatialContext.GEO;
            SpatialPrefixTree grid;
            SpatialStrategy   strategy;

            grid     = new GeohashPrefixTree(ctx, 12);
            strategy = new RecursivePrefixTreeStrategy(grid, "recursive_geohash");
            ctorArgs.Add(new Object[] { new Param(strategy) });

            grid     = new QuadPrefixTree(ctx, 25);
            strategy = new RecursivePrefixTreeStrategy(grid, "recursive_quad");
            ctorArgs.Add(new Object[] { new Param(strategy) });

            grid     = new GeohashPrefixTree(ctx, 12);
            strategy = new TermQueryPrefixTreeStrategy(grid, "termquery_geohash");
            ctorArgs.Add(new Object[] { new Param(strategy) });

            strategy = new PointVectorStrategy(ctx, "pointvector");
            ctorArgs.Add(new Object[] { new Param(strategy) });

            return(ctorArgs);
        }
        public void testPrecision()
        {
            init(GeohashPrefixTree.GetMaxLevelsPossible());

            Point iPt = ctx.MakePoint(2.8028712999999925, 48.3708044); //lon, lat

            addDocument(newDoc("iPt", iPt));
            commit();

            Point qPt = ctx.MakePoint(2.4632387000000335, 48.6003516);

            double KM2DEG = DistanceUtils.Dist2Degrees(1, DistanceUtils.EARTH_MEAN_RADIUS_KM);
            double DEG2KM = 1 / KM2DEG;

            const double DIST = 35.75; //35.7499...

            assertEquals(DIST, ctx.GetDistCalc().Distance(iPt, qPt) * DEG2KM, 0.001);

            //distErrPct will affect the query shape precision. The indexed precision
            // was set to nearly zilch via init(GeohashPrefixTree.getMaxLevelsPossible());
            const double distErrPct = 0.025; //the suggested default, by the way
            const double distMult   = 1 + distErrPct;

            assertTrue(35.74 * distMult >= DIST);
            checkHits(q(qPt, 35.74 * KM2DEG, distErrPct), 1, null);

            assertTrue(30 * distMult < DIST);
            checkHits(q(qPt, 30 * KM2DEG, distErrPct), 0, null);

            assertTrue(33 * distMult < DIST);
            checkHits(q(qPt, 33 * KM2DEG, distErrPct), 0, null);

            assertTrue(34 * distMult < DIST);
            checkHits(q(qPt, 34 * KM2DEG, distErrPct), 0, null);
        }
        public LuceneIndexManager(
            IClock clock,
            IOptions <ShellOptions> shellOptions,
            ShellSettings shellSettings,
            ILogger <LuceneIndexManager> logger,
            LuceneAnalyzerManager luceneAnalyzerManager,
            LuceneIndexSettingsService luceneIndexSettingsService
            )
        {
            _clock    = clock;
            _logger   = logger;
            _rootPath = PathExtensions.Combine(
                shellOptions.Value.ShellsApplicationDataPath,
                shellOptions.Value.ShellsContainerName,
                shellSettings.Name, "Lucene");
            Directory.CreateDirectory(_rootPath);
            _luceneAnalyzerManager      = luceneAnalyzerManager;
            _luceneIndexSettingsService = luceneIndexSettingsService;

            // Typical geospatial context
            // These can also be constructed from SpatialContextFactory
            _ctx = SpatialContext.Geo;

            var maxLevels = 11; // Results in sub-meter precision for geohash

            // TODO demo lookup by detail distance
            // This can also be constructed from SpatialPrefixTreeFactory
            _grid = new GeohashPrefixTree(_ctx, maxLevels);
        }
        //Tests should call this first.
        private void init(int maxLength)
        {
            this.maxLength = maxLength;
            this.ctx       = SpatialContext.GEO;
            GeohashPrefixTree grid = new GeohashPrefixTree(ctx, maxLength);

            this.strategy = new RecursivePrefixTreeStrategy(grid, GetType().Name);
        }
        public SearchProvider(string luceneDir)
        {
            _luceneDir      = luceneDir;
            _spatialContext = SpatialContext.GEO;
            int maxLevels          = 11; // Results in sub-metre precision for geohash.
            SpatialPrefixTree grid = new GeohashPrefixTree(_spatialContext, maxLevels);

            _strategy = new RecursivePrefixTreeStrategy(grid, Location);
        }
        public virtual void TestOneMeterPrecision()
        {
            init(GeohashPrefixTree.MaxLevelsPossible);
            GeohashPrefixTree grid = (GeohashPrefixTree)((RecursivePrefixTreeStrategy)strategy).Grid;
            //DWS: I know this to be true.  11 is needed for one meter
            double degrees = DistanceUtils.Dist2Degrees(0.001, DistanceUtils.EARTH_MEAN_RADIUS_KM);

            assertEquals(11, grid.GetLevelForDistance(degrees));
        }
Example #8
0
        private static readonly double LUCENE_4464_distErrPct = SpatialArgs.DEFAULT_DISTERRPCT;        //DEFAULT 2.5%

        public NtsPolygonTest()
        {
            //var args = new HashMap<String, String> {{"spatialContextFactory", "com.spatial4j.core.context.jts.JtsSpatialContextFactory"}};
            //SpatialContextFactory.MakeSpatialContext(args, getClass().getClassLoader());
            ctx = new NtsSpatialContext(true);

            var grid = new GeohashPrefixTree(ctx, 11);            //< 1 meter == 11 maxLevels

            this.strategy = new RecursivePrefixTreeStrategy(grid, GetType().Name);
            ((RecursivePrefixTreeStrategy)this.strategy).DistErrPct = LUCENE_4464_distErrPct;            //1% radius (small!)
        }
        public void testFilterWithVariableScanLevel()
        {
            init(GeohashPrefixTree.GetMaxLevelsPossible());
            getAddAndVerifyIndexedDocuments(DATA_WORLD_CITIES_POINTS);

            //execute queries for each prefix grid scan level
            for (int i = 0; i <= maxLength; i++)
            {
                ((RecursivePrefixTreeStrategy)strategy).SetPrefixGridScanLevel(i);
                executeQueries(SpatialMatchConcern.FILTER, QTEST_Cities_Intersects_BBox);
            }
        }
        public FilteredQuery CreateFilteredQuery(ILuceneQueryService builder, LuceneQueryContext context, string type, JToken filter, Query toFilter)
        {
            if (type != "geo_bounding_box")
            {
                return(null);
            }

            if (!(toFilter is BooleanQuery booleanQuery))
            {
                return(null);
            }

            var queryObj = filter as JObject;
            var first    = queryObj.Properties().First();

            var ctx = SpatialContext.Geo;

            var maxLevels = 11; //results in sub-meter precision for geohash

            //  This can also be constructed from SpatialPrefixTreeFactory
            SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);

            var geoPropertyName = first.Name;
            var strategy        = new RecursivePrefixTreeStrategy(grid, geoPropertyName);

            var boundingBox = (JObject)first.Value;

            var topLeftProperty     = boundingBox["top_left"] as JObject;
            var bottomRightProperty = boundingBox["bottom_right"] as JObject;

            if (topLeftProperty == null || bottomRightProperty == null)
            {
                return(null);
            }

            var left   = topLeftProperty["lon"];
            var top    = topLeftProperty["lat"];
            var bottom = bottomRightProperty["lat"];
            var right  = bottomRightProperty["lon"];

            var rectangle = ctx.MakeRectangle((double)left, (double)right, (double)bottom, (double)top);

            var args = new SpatialArgs(SpatialOperation.Intersects, rectangle);

            var spatialQuery      = strategy.MakeQuery(args);
            var valueSource       = strategy.MakeRecipDistanceValueSource(rectangle);
            var valueSourceFilter = new ValueSourceFilter(new QueryWrapperFilter(spatialQuery), valueSource, 0, 1);

            booleanQuery.Add(new FunctionQuery(valueSource), Occur.MUST);

            return(new FilteredQuery(booleanQuery, valueSourceFilter));
        }
Example #11
0
        protected void Init()
        {
            //Typical geospatial context
            //  These can also be constructed from SpatialContextFactory
            this.ctx = SpatialContext.GEO;

            int maxLevels = 11; //results in sub-meter precision for geohash
                                //TODO demo lookup by detail distance
                                //  This can also be constructed from SpatialPrefixTreeFactory
            SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);

            this.strategy = new RecursivePrefixTreeStrategy(grid, "myGeoField");

            this.directory = new RAMDirectory();
        }
Example #12
0
        public IEnumerable <IFieldable> SpatialGenerate(string fieldName, string shapeWKT,
                                                        SpatialSearchStrategy spatialSearchStrategy = SpatialSearchStrategy.GeohashPrefixTree,
                                                        int maxTreeLevel = 0, double distanceErrorPct = 0.025)
        {
            if (maxTreeLevel == 0)
            {
                maxTreeLevel = GeohashPrefixTree.GetMaxLevelsPossible();
            }
            var strategy = SpatialStrategies.GetOrAdd(fieldName, s => SpatialIndex.CreateStrategy(fieldName, spatialSearchStrategy, maxTreeLevel));

            var shape = SpatialIndex.ShapeReadWriter.ReadShape(shapeWKT);

            return(strategy.CreateIndexableFields(shape)
                   .Concat(new[] { new Field(Constants.SpatialShapeFieldName, SpatialIndex.ShapeReadWriter.WriteShape(shape), Field.Store.YES, Field.Index.NO), }));
        }
        private static List <IFieldable> AddBounds(SpatialContext ctx, double lng, double lat)
        {
            SpatialPrefixTree grid        = new GeohashPrefixTree(ctx, 11);
            var strategy                  = new RecursivePrefixTreeStrategy(grid, Sitecore.ContentSearch.Spatial.Common.Constants.LocationFieldName);
            List <IFieldable> pointFields = new List <IFieldable>();
            Point             shape       = ctx.MakePoint(lng, lat);

            foreach (var f in strategy.CreateIndexableFields(shape))
            {
                if (f != null)
                {
                    pointFields.Add(f);
                }
            }
            return(pointFields);
        }
        public virtual void TestEqualsHashCode()
        {
            SpatialPrefixTree gridQuad    = new QuadPrefixTree(ctx, 10);
            SpatialPrefixTree gridGeohash = new GeohashPrefixTree(ctx, 10);

            List <SpatialStrategy> strategies = new List <SpatialStrategy>();

            strategies.Add(new RecursivePrefixTreeStrategy(gridGeohash, "recursive_geohash"));
            strategies.Add(new TermQueryPrefixTreeStrategy(gridQuad, "termquery_quad"));
            strategies.Add(new PointVectorStrategy(ctx, "pointvector"));
            //strategies.Add(new BBoxStrategy(ctx, "bbox"));
            strategies.Add(new SerializedDVStrategy(ctx, "serialized"));
            foreach (SpatialStrategy strategy in strategies)
            {
                TestEqualsHashcode(strategy);
            }
        }
Example #15
0
        private QueryHelper <TModel> GeoFilter(Expression <Func <TModel, object> > exp, double longitude, double latitude, double distDEG)
        {
            string name = getName(exp.Body.ToString());
            //name = name.IndexOf('.') > -1 ? name.Substring(0, name.LastIndexOf('.')) : name;
            SpatialOperation op = SpatialOperation.Intersects;
            //SpatialStrategy strat = new PointVectorStrategy(ctx, name);
            int maxLevels          = 11;
            SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
            var strat = new RecursivePrefixTreeStrategy(grid, name);

            var point = ctx.MakePoint(longitude, latitude);
            var shape = ctx.MakeCircle(point, distDEG);
            var args  = new SpatialArgs(op, shape);

            filter = strat.MakeFilter(args);
            return(this);
        }
Example #16
0
        public void Document_Writing_To_Index_Spatial_Data_And_Search_On_100km_Radius_RecursivePrefixTreeStrategy()
        {
            // NOTE: It is advised to use RecursivePrefixTreeStrategy, see:
            // https://stackoverflow.com/a/13631289/694494
            // Here's the Java sample code
            // https://github.com/apache/lucene-solr/blob/branch_4x/lucene/spatial/src/test/org/apache/lucene/spatial/SpatialExample.java

            SpatialContext              ctx       = SpatialContext.GEO;
            int                         maxLevels = 11; //results in sub-meter precision for geohash
            SpatialPrefixTree           grid      = new GeohashPrefixTree(ctx, maxLevels);
            RecursivePrefixTreeStrategy strategy  = new RecursivePrefixTreeStrategy(grid, GeoLocationFieldName);

            // NOTE: The SpatialExample uses MatchAllDocsQuery however the strategy can create a query too, the source is here:
            // https://github.com/apache/lucenenet/blob/master/src/Lucene.Net.Spatial/SpatialStrategy.cs#L124
            // all that really does it take the filter created and creates a ConstantScoreQuery with it
            // which probably makes sense because a 'Score' for a geo coord doesn't make a lot of sense.
            RunTest(ctx, strategy, a => strategy.MakeQuery(a));
        }
Example #17
0
        private static readonly double LUCENE_4464_distErrPct = SpatialArgs.DEFAULT_DISTERRPCT;//DEFAULT 2.5%

        public NtsPolygonTest()
        {
            try
            {
                IDictionary <string, string> args = new Dictionary <string, string>();
                args.Put("spatialContextFactory",
                         typeof(Spatial4n.Core.Context.Nts.NtsSpatialContextFactory).AssemblyQualifiedName);
                ctx = SpatialContextFactory.MakeSpatialContext(args /*, getClass().getClassLoader()*/);
            }
            catch (TypeLoadException e) //LUCENENET TODO: Does this match NoClassDefFoundError ??
            {
                AssumeTrue("This test requires Spatial4n.Core.NTS: " + e, false);
            }

            GeohashPrefixTree grid = new GeohashPrefixTree(ctx, 11);//< 1 meter == 11 maxLevels

            this.strategy = new RecursivePrefixTreeStrategy(grid, GetType().Name);
            ((RecursivePrefixTreeStrategy)this.strategy).DistErrPct = (LUCENE_4464_distErrPct);//1% radius (small!)
        }
Example #18
0
        public void CreateSpatialFilterAndWeight(PointRadiusCriterion geoFilter, Filter currentFilter, Weight currentWeight)
        {
            var spatialContext = SpatialContext.GEO;
            var geohashTree    = new GeohashPrefixTree(spatialContext, 10);
            var strategy       = new RecursivePrefixTreeStrategy(geohashTree, geoFilter.FieldName);
            var point          = spatialContext.MakePoint(geoFilter.Longitude, geoFilter.Latitude);

            var spatialArgs = new SpatialArgs(SpatialOperation.Intersects, spatialContext.MakeCircle(point,
                                                                                                     DistanceUtils.Dist2Degrees(geoFilter.RadiusKm, DistanceUtils.EARTH_MEAN_RADIUS_KM)));

            var circle = spatialContext.MakeCircle(point,
                                                   DistanceUtils.Dist2Degrees(geoFilter.RadiusKm, DistanceUtils.EARTH_MEAN_RADIUS_KM));
            var circleCells = strategy.GetGrid().GetWorldNode().GetSubCells(circle);

            var luceneFilters = new List <Filter>();

            if (currentFilter != null)
            {
                luceneFilters.Add(currentFilter);
            }

            var tempSpatial = strategy.MakeFilter(spatialArgs);

            luceneFilters.Add(tempSpatial);

            if (geoFilter.Sort != PointRadiusCriterion.SortOption.None)
            {
                var valueSource = strategy.MakeDistanceValueSource(point);
                var funcQ       = new FunctionQuery(valueSource);
                // this is a bit odd... but boosting the score negatively orders results
                if (geoFilter.Sort == PointRadiusCriterion.SortOption.Ascending)
                {
                    funcQ.Boost = -1;
                }
                spatialWeight = funcQ.CreateWeight(this);
                spatialWeight.GetSumOfSquaredWeights();

                luceneFilters.Add(new QueryWrapperFilter(currentWeight.Query));
            }

            spatialFilter = new ChainedFilter(luceneFilters.ToArray(), 1);
        }
Example #19
0
        private static readonly double LUCENE_4464_distErrPct = SpatialArgs.DEFAULT_DISTERRPCT;//DEFAULT 2.5%

        public NtsPolygonTest()
        {
            try
            {
                IDictionary <string, string> args = new Dictionary <string, string>
                {
                    ["SpatialContextFactory"] = typeof(NtsSpatialContextFactory).FullName
                };
                ctx = SpatialContextFactory.MakeSpatialContext(args, GetType().Assembly);
            }
            catch (Exception e) when(e.IsNoClassDefFoundError())
            {
                AssumeTrue("This test requires Spatial4n: " + e, false);
            }

            GeohashPrefixTree grid = new GeohashPrefixTree(ctx, 11);//< 1 meter == 11 maxLevels

            this.strategy = new RecursivePrefixTreeStrategy(grid, GetType().Name);
            ((RecursivePrefixTreeStrategy)this.strategy).DistErrPct = (LUCENE_4464_distErrPct);//1% radius (small!)
        }
Example #20
0
        static void Main(string[] args)
        {
            int maxLength = GeohashPrefixTree.GetMaxLevelsPossible();

            strategy = new RecursivePrefixTreeStrategy(
                new GeohashPrefixTree(context, maxLength));

            var dir    = new RAMDirectory();
            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);

            writer.Close();

            // Origin point - Oslo Spektrum
            const double lat    = 59.9138688;
            const double lng    = 10.752245399999993;
            const double radius = 600;
            var          query  = strategy.MakeQuery(new SpatialArgs(SpatialOperation.IsWithin,
                                                                     context.MakeCircle(lng, lat, radius)), fieldInfo);

            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);
            }
            searcher.Close();
            dir.Close();
        }
Example #21
0
        private List <IFieldable> AddPoint(Item item)
        {
            List <IFieldable> pointFields = new List <IFieldable>();
            var setting = spatialConfigurations.LocationSettings.Where(i => i.TemplateId.Equals(item.TemplateID)).FirstOrDefault();

            if (setting == null)
            {
                return(pointFields);
            }

            SpatialContext ctx = SpatialContext.GEO;

            SpatialPrefixTree grid = new GeohashPrefixTree(ctx, 11);
            var strategy           = new PointVectorStrategy(ctx, Sitecore.ContentSearch.Spatial.Common.Constants.LocationFieldName);

            double lng        = 0;
            double lat        = 0;
            bool   parsedLat  = false;
            bool   parsedLong = false;

            if (!string.IsNullOrEmpty(item[setting.LatitudeField]))
            {
                parsedLat = Double.TryParse(item[setting.LatitudeField], out lat);
            }

            if (!string.IsNullOrEmpty(item[setting.LongitudeField]))
            {
                parsedLong = Double.TryParse(item[setting.LongitudeField], out lng);
            }
            if (!parsedLat && !parsedLong)
            {
                return(pointFields);
            }

            pointFields = AddPoint(lng, lat);

            return(pointFields);
        }
        public object ComputeFieldValue(Sitecore.ContentSearch.IIndexable indexable)
        {
            var indexableItem = indexable as SitecoreIndexableItem;

            if (indexableItem == null)
            {
                return(null);
            }

            var item = (Sitecore.Data.Items.Item)indexableItem;

            if (item == null)
            {
                return(null);
            }

            var latLon = item[SourceFieldName];

            if (latLon == "" || latLon == "NULL")
            {
                return(null);
            }

            // Convert from georss point to normal X, Y format
            latLon = latLon.Replace(" ", ", ");

            var spatialContext = SpatialContext.GEO;
            var geohashTree    = new GeohashPrefixTree(spatialContext, 10);
            var strategy       = new RecursivePrefixTreeStrategy(geohashTree, FieldName);

            var          shape            = spatialContext.ReadShape(latLon);
            var          grid             = strategy.GetGrid();
            int          levelForDistance = grid.GetLevelForDistance(strategy.DistErrPct);
            IList <Node> list             = grid.GetNodes(shape, levelForDistance, true);

            return(list.Select(node => node.GetTokenString()));
        }
            public IEnumerable <Param> ParamsProvider()
            {
                var ctorArgs = new List <Param>();

                SpatialContext    ctx = SpatialContext.GEO;
                SpatialPrefixTree grid;
                SpatialStrategy   strategy;

                grid     = new QuadPrefixTree(ctx, 25);
                strategy = new RecursivePrefixTreeStrategy(grid, "recursive_quad");
                ctorArgs.Add(new Param(strategy));

                grid     = new GeohashPrefixTree(ctx, 12);
                strategy = new TermQueryPrefixTreeStrategy(grid, "termquery_geohash");
                ctorArgs.Add(new Param(strategy));

                strategy = new PointVectorStrategy(ctx, "pointvector");
                ctorArgs.Add(new Param(strategy));

                strategy = new BBoxStrategy(ctx, "bbox");
                ctorArgs.Add(new Param(strategy));

                return(ctorArgs);
            }
Example #24
0
        public FilteredQuery CreateFilteredQuery(ILuceneQueryService builder, LuceneQueryContext context, string type, JToken filter, Query toFilter)
        {
            if (type != "geo_distance")
            {
                return(null);
            }

            if (!(toFilter is BooleanQuery booleanQuery))
            {
                return(null);
            }

            var queryObj = filter as JObject;

            if (queryObj.Properties().Count() != 2)
            {
                return(null);
            }

            var ctx = SpatialContext.Geo;

            var maxLevels = 11; //results in sub-meter precision for geohash

            //  This can also be constructed from SpatialPrefixTreeFactory
            SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);

            JProperty distanceProperty = null;
            JProperty geoProperty      = null;

            foreach (var jProperty in queryObj.Properties())
            {
                if (jProperty.Name.Equals("distance", StringComparison.Ordinal))
                {
                    distanceProperty = jProperty;
                }
                else
                {
                    geoProperty = jProperty;
                }
            }

            if (distanceProperty == null || geoProperty == null)
            {
                return(null);
            }

            var strategy = new RecursivePrefixTreeStrategy(grid, geoProperty.Name);

            if (!TryParseDistance((string)distanceProperty.Value, out var distanceDegrees))
            {
                return(null);
            }

            if (!TryGetPointFromJToken(geoProperty.Value, out var point))
            {
                return(null);
            }

            var circle = ctx.MakeCircle(point.X, point.Y, distanceDegrees);

            var args = new SpatialArgs(SpatialOperation.Intersects, circle);

            var spatialQuery      = strategy.MakeQuery(args);
            var valueSource       = strategy.MakeRecipDistanceValueSource(circle);
            var valueSourceFilter = new ValueSourceFilter(new QueryWrapperFilter(spatialQuery), valueSource, 0, 1);

            booleanQuery.Add(new FunctionQuery(valueSource), Occur.MUST);

            return(new FilteredQuery(booleanQuery, valueSourceFilter));
        }
Example #25
0
        public void PureLucene()
        {
            using (var dir = new RAMDirectory())
            {
                using (var keywordAnalyzer = new KeywordAnalyzer())
                    using (var writer = new IndexWriter(dir, keywordAnalyzer, true, IndexWriter.MaxFieldLength.UNLIMITED))
                    {
                        var doc = new Lucene.Net.Documents.Document();

                        var writeShape    = NtsSpatialContext.GEO.ReadShape("LINESTRING (0 0, 1 1, 2 1)");
                        var writeStrategy = SpatialIndex.CreateStrategy("WKT", SpatialSearchStrategy.GeohashPrefixTree, GeohashPrefixTree.GetMaxLevelsPossible());
                        foreach (var f in writeStrategy.CreateIndexableFields(writeShape))
                        {
                            doc.Add(f);
                        }
                        writer.AddDocument(doc);
                        writer.Commit();
                    }


                var         shape     = NtsSpatialContext.GEO.ReadShape("LINESTRING (1 0, 1 1, 1 2)");
                SpatialArgs args      = new SpatialArgs(SpatialOperation.Intersects, shape);
                var         strategy  = SpatialIndex.CreateStrategy("WKT", SpatialSearchStrategy.GeohashPrefixTree, GeohashPrefixTree.GetMaxLevelsPossible());
                var         makeQuery = strategy.MakeQuery(args);
                using (var search = new IndexSearcher(dir))
                {
                    var topDocs = search.Search(makeQuery, 5);
                    Assert.Equal(1, topDocs.TotalHits);
                }
            }
        }
Example #26
0
 static SpatialIndex()
 {
     maxLength = GeohashPrefixTree.GetMaxLevelsPossible();
     fieldInfo = new SimpleSpatialFieldInfo(Constants.SpatialFieldName);
     strategy  = new RecursivePrefixTreeStrategy(new GeohashPrefixTree(RavenSpatialContext, maxLength));
 }
Example #27
0
        public void GetFieldSettings(List <FlattenedObject> props, Document doc, List <KeyValuePair <string, Analyzer> > analyzers)
        {
            foreach (var p in props)
            {
                if (p == null)
                {
                    continue;
                }
                if (analyzers != null)
                {
                    if (p.Analyzer != null)
                    {
                        analyzers.Add(new KeyValuePair <string, Analyzer>(p.Key, p.Analyzer));
                    }
                }
                if (doc != null)
                {
                    if (p.Value is int || p.Value is int?)
                    {
                        var nf = new Int32Field(p.Key, int.Parse(p.Value.ToString()), p.FieldStoreSetting);
                        doc.Add(nf);
                    }
                    else if (p.Value is long || p.Value is long?)
                    {
                        var nf = new Int64Field(p.Key, long.Parse(p.Value.ToString()), p.FieldStoreSetting);
                        doc.Add(nf);
                    }
                    else if (p.Value is float || p.Value is float?)
                    {
                        var nf = new SingleField(p.Key, float.Parse(p.Value.ToString()), p.FieldStoreSetting);
                        doc.Add(nf);
                    }
                    else if (p.Value is double || p.Value is double?)
                    {
                        var nf = new DoubleField(p.Key, double.Parse(p.Value.ToString()), p.FieldStoreSetting);
                        doc.Add(nf);
                    }
                    else if (p.Spatial)
                    {
                        if (p.Value == null || string.IsNullOrEmpty(p.Value.ToString()))
                        {
                            continue;
                        }
                        var name               = p.Key;// p.Key.IndexOf('.')>-1?p.Key.Substring(0,p.Key.LastIndexOf('.')):p.Key;
                        int maxLevels          = 11;
                        SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
                        var strat              = new RecursivePrefixTreeStrategy(grid, name);

                        //var strat = new PointVectorStrategy(ctx,name);
                        var xyArr = p.Value.ToString().Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        if (xyArr.Length != 2)
                        {
                            continue;
                        }
                        double x;
                        double y;
                        if (!double.TryParse(xyArr[0], out x) || !double.TryParse(xyArr[1], out y))
                        {
                            continue;
                        }
                        var point = ctx.MakePoint(x, y);
                        //var point = ctx.ReadShape(p.Value.ToString());
                        var fields = strat.CreateIndexableFields(point);
                        fields.ToList().ForEach(x => doc.Add(x));

                        IPoint pt = (IPoint)point;
                        //doc.Add(new StoredField(strat.FieldName, pt.X.ToString(CultureInfo.InvariantCulture) + " " + pt.Y.ToString(CultureInfo.InvariantCulture)));
                    }
                    else
                    {
                        string value = p.Value == null ? null : (p.KeepValueCasing ? p.Value.ToString() : p.Value.ToString().ToLower());
                        Field  f     = null;
                        if (p.FieldIndexSetting == Field.Index.ANALYZED || p.FieldIndexSetting == Field.Index.ANALYZED_NO_NORMS)
                        {
                            f = new TextField(p.Key, value ?? string.Empty, p.FieldStoreSetting);
                        }
                        else
                        {
                            f = new StringField(p.Key, value ?? string.Empty, p.FieldStoreSetting);
                        }
                        doc.Add(f);
                    }
                }
            }
        }
 public SpatialStrategy GetStrategyForField(string fieldName)
 {
     return(SpatialStrategies.GetOrAdd(fieldName, s =>
     {
         if (SpatialStrategies.Count > 1024)
         {
             throw new InvalidOperationException("The number of spatial fields in an index is limited ot 1,024");
         }
         return SpatialIndex.CreateStrategy(fieldName, SpatialSearchStrategy.GeohashPrefixTree, GeohashPrefixTree.GetMaxLevelsPossible());
     }));
 }
Example #29
0
        public IEnumerable <IFieldable> SpatialGenerate(string fieldName, double?lat, double?lng)
        {
            var strategy = SpatialStrategies.GetOrAdd(fieldName, s => SpatialIndex.CreateStrategy(fieldName, SpatialSearchStrategy.GeohashPrefixTree,
                                                                                                  GeohashPrefixTree.GetMaxLevelsPossible()));

// ReSharper disable CSharpWarnings::CS0612
            Shape shape = SpatialIndex.Context.MakePoint(lng ?? 0, lat ?? 0);

            return(strategy.CreateIndexableFields(shape)
                   .Concat(new[] { new Field(Constants.SpatialShapeFieldName, SpatialIndex.ShapeReadWriter.WriteShape(shape), Field.Store.YES, Field.Index.NO), }));
// ReSharper restore CSharpWarnings::CS0612
        }