Exemple #1
0
		public static Query MakeQuery(SpatialStrategy spatialStrategy, string shapeWKT, SpatialRelation relation,
		                              double distanceErrorPct = 0.025)
		{
			SpatialOperation spatialOperation;
			Shape shape = ShapeReadWriter.ReadShape(shapeWKT);
			switch (relation)
			{
				case SpatialRelation.Within:
					spatialOperation = SpatialOperation.IsWithin;
					break;
				case SpatialRelation.Contains:
					spatialOperation = SpatialOperation.Contains;
					break;
				case SpatialRelation.Disjoint:
					spatialOperation = SpatialOperation.IsDisjointTo;
					break;
				case SpatialRelation.Intersects:
					spatialOperation = SpatialOperation.Intersects;
					break;
				case SpatialRelation.Nearby:
					var nearbyArgs = new SpatialArgs(SpatialOperation.IsWithin, shape);
					nearbyArgs.SetDistPrecision(distanceErrorPct);
					// only sort by this, do not filter
					return new FunctionQuery(spatialStrategy.MakeValueSource(nearbyArgs));
				default:
					throw new ArgumentOutOfRangeException("relation");
			}
			var args = new SpatialArgs(spatialOperation, shape);
			args.SetDistPrecision(distanceErrorPct);

			return spatialStrategy.MakeQuery(args);
		}
        public override Filter MakeFilter(SpatialArgs args)
        {
            SpatialOperation op = args.Operation;
            if (op == SpatialOperation.IsDisjointTo)
            {
                return new DisjointSpatialFilter(this, args, FieldName);
            }
            IShape shape = args.Shape;
            int detailLevel = grid.GetLevelForDistance(args.ResolveDistErr(ctx, distErrPct));

        
            if (pointsOnly || op == SpatialOperation.Intersects)
            {
                return new IntersectsPrefixTreeFilter(
                    shape, FieldName, grid, detailLevel, prefixGridScanLevel, !pointsOnly);
            }
            else if (op == SpatialOperation.IsWithin)
            {
                return new WithinPrefixTreeFilter(
                    shape, FieldName, grid, detailLevel, prefixGridScanLevel, 
                    -1); //-1 flag is slower but ensures correct results
            }
            else if (op == SpatialOperation.Contains)
            {
                return new ContainsPrefixTreeFilter(shape, FieldName, grid, detailLevel, 
                    multiOverlappingIndexedShapes);
            }
            throw new UnsupportedSpatialOperation(op);
        }
        protected virtual Lucene.Net.Search.Query VisitWithinRadius(WithinRadiusNode node, LuceneQueryMapperState mappingState)
        {
            SpatialContext ctx = SpatialContext.GEO;
           
            var strategy = new PointVectorStrategy(ctx, Sitecore.ContentSearch.Spatial.Common.Constants.LocationFieldName);

            if (node.Latitude is double && node.Longitude is double && node.Radius is double)
            {
                var distance = DistanceUtils.Dist2Degrees((double)node.Radius, DistanceUtils.EARTH_MEAN_RADIUS_MI);
                Circle circle = ctx.MakeCircle((double)node.Longitude,(double)node.Latitude, distance);

                var spatialArgs = new SpatialArgs(SpatialOperation.IsWithin, circle);
                var dq = strategy.MakeQuery(spatialArgs);

                DistanceReverseValueSource valueSource = new DistanceReverseValueSource(strategy, circle.GetCenter(), distance);
                ValueSourceFilter vsf = new ValueSourceFilter(new QueryWrapperFilter(dq), valueSource, 0, distance);
                var filteredSpatial = new FilteredQuery(new MatchAllDocsQuery(), vsf);
                mappingState.FilterQuery = filteredSpatial;
                Lucene.Net.Search.Query spatialRankingQuery = new FunctionQuery(valueSource);
                Random r = new Random(DateTime.Now.Millisecond);
                var randomNumber = r.Next(10000101,11000101);
                Lucene.Net.Search.Query dummyQuery = Lucene.Net.Search.NumericRangeQuery.NewIntRange("__smallcreateddate", randomNumber, Int32.Parse(DateTime.Now.ToString("yyyyMMdd")), true, true);
                BooleanQuery bq = new BooleanQuery();

                bq.Add(filteredSpatial, Occur.MUST);
                bq.Add(spatialRankingQuery, Occur.MUST);
                bq.Add(dummyQuery, Occur.SHOULD);
                return bq;
            }
            throw new NotSupportedException("Wrong parameters type, Radius, latitude and longitude must be of type double");
        }
Exemple #4
0
 private SpatialArgs q(String shapeStr, double distErrPct)
 {
     IShape shape = ctx.ReadShapeFromWkt(shapeStr);
     SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, shape);
     args.DistErrPct = (distErrPct);
     return args;
 }
		public void testCircleShapeSupport()
		{
            Circle circle = ctx.MakeCircle(ctx.MakePoint(0, 0), 10);
			SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);
			Query query = this.strategy.MakeQuery(args);

			Assert.NotNull(query);
		}
Exemple #6
0
 protected virtual void ReadNameValuePairs(SpatialArgs args, IDictionary <string, string> nameValPairs)
 {
     nameValPairs.TryGetValue(DIST_ERR_PCT, out string distErrPctStr);
     nameValPairs.TryGetValue(DIST_ERR, out string distErrStr);
     args.DistErrPct = ReadDouble(distErrPctStr);
     nameValPairs.Remove(DIST_ERR_PCT);
     args.DistErr = ReadDouble(distErrStr);
     nameValPairs.Remove(DIST_ERR);
 }
        /// <param name="strategy">Needed to compute intersects</param>
        /// <param name="args">Used in spatial intersection</param>
        /// <param name="field">
        /// This field is used to determine which docs have spatial data via
        /// <see cref="FieldCache.GetDocsWithField(AtomicReader, string)"/>.
        /// Passing null will assume all docs have spatial data.
        /// </param>
        public DisjointSpatialFilter(SpatialStrategy strategy, SpatialArgs args, string field)
        {
            this.field = field;

            // TODO consider making SpatialArgs cloneable
            SpatialOperation origOp = args.Operation; //copy so we can restore
            args.Operation = SpatialOperation.Intersects; //temporarily set to intersects
            intersectsFilter = strategy.MakeFilter(args);
            args.Operation = origOp;
        }
		public override Filter MakeFilter(SpatialArgs args)
		{
			var op = args.Operation;
			if (!SpatialOperation.Is(op, SpatialOperation.IsWithin, SpatialOperation.Intersects, SpatialOperation.BBoxWithin, SpatialOperation.BBoxIntersects))
				throw new UnsupportedSpatialOperation(op);

			Shape shape = args.Shape;

			int detailLevel = grid.GetLevelForDistance(args.ResolveDistErr(ctx, distErrPct));

			return new RecursivePrefixTreeFilter(GetFieldName(), grid, shape, prefixGridScanLevel, detailLevel);
		}
		public override Filter MakeFilter(SpatialArgs args)
		{
			var op = args.Operation;
			if (!SpatialOperation.Is(op, SpatialOperation.IsWithin, SpatialOperation.Intersects, SpatialOperation.BBoxWithin, SpatialOperation.BBoxIntersects))
				throw new UnsupportedSpatialOperation(op);

			Shape shape = args.GetShape();

			int detailLevel = grid.GetMaxLevelForPrecision(shape, args.GetDistPrecision());

			return new RecursivePrefixTreeFilter(GetFieldName(), grid, shape, prefixGridScanLevel, detailLevel);
		}
 /// <summary>
 /// Writes a close approximation to the parsed input format.
 /// </summary>
 /// <param name="args"></param>
 /// <returns></returns>
 public static String WriteSpatialArgs(SpatialArgs args)
 {
     var str = new StringBuilder();
     str.Append(args.Operation.GetName());
     str.Append('(');
     str.Append(args.Shape);
     if (args.DistErrPct != null)
         str.Append(" distErrPct=").Append(String.Format("{0:0.00}%", args.DistErrPct*100d));
     if (args.DistErr != null)
         str.Append(" distErr=").Append(args.DistErr);
     str.Append(')');
     return str.ToString();
 }
        public override Filter MakeFilter(SpatialArgs args)
        {
            SpatialOperation op = args.Operation;
            if (op != SpatialOperation.Intersects)
                throw new UnsupportedSpatialOperation(op);

            Shape shape = args.Shape;
            int detailLevel = grid.GetLevelForDistance(args.ResolveDistErr(ctx, distErrPct));
            var cells = grid.GetNodes(shape, detailLevel, false);
            var filter = new TermsFilter();
            foreach (Node cell in cells)
            {
                filter.AddTerm(new Term(GetFieldName(), cell.GetTokenString()));
            }
            return filter;
        }
		public override Filter MakeFilter(SpatialArgs args)
		{
			SpatialOperation op = args.Operation;
			if (
				!SpatialOperation.Is(op, SpatialOperation.IsWithin, SpatialOperation.Intersects, SpatialOperation.BBoxWithin,
				                     SpatialOperation.BBoxIntersects))
				throw new UnsupportedSpatialOperation(op);

			Shape shape = args.GetShape();
			int detailLevel = grid.GetMaxLevelForPrecision(shape, args.GetDistPrecision());
			var cells = grid.GetNodes(shape, detailLevel, false);
			var filter = new TermsFilter();
			foreach (Node cell in cells)
			{
				filter.AddTerm(new Term(GetFieldName(), cell.GetTokenString()));
			}
			return filter;
		}
Exemple #13
0
        /// <summary>
        /// Writes a close approximation to the parsed input format.
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public static String WriteSpatialArgs(SpatialArgs args)
        {
            var str = new StringBuilder();

            str.Append(args.Operation.GetName());
            str.Append('(');
            str.Append(args.Shape);
            if (args.DistErrPct != null)
            {
                str.Append(" distErrPct=").Append(String.Format("{0:0.00}%", args.DistErrPct * 100d));
            }
            if (args.DistErr != null)
            {
                str.Append(" distErr=").Append(args.DistErr);
            }
            str.Append(')');
            return(str.ToString());
        }
Exemple #14
0
        public void testLineStrings()
        {
            var sdIterator = new List<SampleData>
                                              {
                                                  new SampleData("LineB\tLineB\tLINESTRING (0 1, 1 1, 2 1)"),
                                                  new SampleData("LineC\tLineC\tLINESTRING (0 1, 0.8 0.8, 2 1)"),
                                                  new SampleData("LineD\tLineD\tLINESTRING (0 1, 0.5 1, 2 1)")
                                              };

            ctx = NtsSpatialContext.GEO;
            List<Document> testDocuments = getDocuments(sdIterator.GetEnumerator());
            addDocumentsAndCommit(testDocuments);
            verifyDocumentsIndexed(testDocuments.Count);

            var lineA = ctx.ReadShape("LINESTRING (0 0, 1 1, 1 2)");
            var args = new SpatialArgs(SpatialOperation.Intersects, lineA);
            var got = executeQuery(strategy.MakeQuery(args), 100);
            assertEquals(3, got.numFound); //found all 3
        }
Exemple #15
0
        /// <exception cref="ArgumentNullException"><paramref name="args"/> or <paramref name="nameValPairs"/> is <c>null</c>.</exception>
        protected virtual void ReadNameValuePairs(SpatialArgs args, IDictionary <string, string> nameValPairs)
        {
            // LUCENENET specific - added guard clause
            if (args is null)
            {
                throw new ArgumentNullException(nameof(args));
            }
            if (nameValPairs is null)
            {
                throw new ArgumentNullException(nameof(nameValPairs));
            }

            nameValPairs.TryGetValue(DIST_ERR_PCT, out string?distErrPctStr);
            nameValPairs.TryGetValue(DIST_ERR, out string?distErrStr);
            args.DistErrPct = ReadDouble(distErrPctStr);
            nameValPairs.Remove(DIST_ERR_PCT);
            args.DistErr = ReadDouble(distErrStr);
            nameValPairs.Remove(DIST_ERR);
        }
 //do not simplify indexed cells
 public override Filter MakeFilter(SpatialArgs args)
 {
     SpatialOperation op = args.Operation;
     if (op != SpatialOperation.Intersects)
     {
         throw new UnsupportedSpatialOperation(op);
     }
     Shape shape = args.Shape;
     int detailLevel = grid.GetLevelForDistance(args.ResolveDistErr(ctx, distErrPct));
     IList<Cell> cells = grid.GetCells(shape, detailLevel, false, true);
     //no parents
     //simplify
     var terms = new BytesRef[cells.Count];
     int i = 0;
     foreach (Cell cell in cells)
     {
         terms[i++] = new BytesRef(cell.TokenString);
     }
     return new TermsFilter(FieldName, terms);
 }
Exemple #17
0
        /// <summary>
        /// Parses a string such as "Intersects(-10,20,-8,22) distErrPct=0.025".
        /// </summary>
        /// <param name="v"></param>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public SpatialArgs Parse(String v, SpatialContext ctx)
        {
            int idx = v.IndexOf('(');
            int edx = v.LastIndexOf(')');

            if (idx < 0 || idx > edx)
            {
                throw new ArgumentException("missing parens: " + v);
            }

            SpatialOperation op = SpatialOperation.Get(v.Substring(0, idx).Trim());

            //Substring in .NET is (startPosn, length), But in Java it's (startPosn, endPosn)
            //see http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#substring(int, int)
            String body = v.Substring(idx + 1, edx - (idx + 1)).Trim();

            if (body.Length < 1)
            {
                throw new ArgumentException("missing body : " + v);
            }

            var shape = ctx.ReadShape(body);
            var args  = new SpatialArgs(op, shape);

            if (v.Length > (edx + 1))
            {
                body = v.Substring(edx + 1).Trim();
                if (body.Length > 0)
                {
                    Dictionary <String, String> aa = ParseMap(body);
                    args.DistErrPct = ReadDouble(aa["distErrPct"]); aa.Remove(DIST_ERR_PCT);
                    args.DistErr    = ReadDouble(aa["distErr"]); aa.Remove(DIST_ERR);
                    if (aa.Count != 0)
                    {
                        throw new ArgumentException("unused parameters: " + aa);
                    }
                }
            }
            args.Validate();
            return(args);
        }
        /// <summary>
        /// Parses a string such as "Intersects(-10,20,-8,22) distErrPct=0.025".
        /// </summary>
        /// <param name="v"></param>
        /// <param name="ctx"></param>
        /// <returns></returns>
        public SpatialArgs Parse(String v, SpatialContext ctx)
        {
            int idx = v.IndexOf('(');
            int edx = v.LastIndexOf(')');

            if (idx < 0 || idx > edx)
            {
                throw new ArgumentException("missing parens: " + v);
            }

            SpatialOperation op = SpatialOperation.Get(v.Substring(0, idx).Trim());

            //Substring in .NET is (startPosn, length), But in Java it's (startPosn, endPosn)
            //see http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#substring(int, int)
            String body = v.Substring(idx + 1, edx - (idx + 1)).Trim();
            if (body.Length < 1)
            {
                throw new ArgumentException("missing body : " + v);
            }

            var shape = ctx.ReadShape(body);
            var args = new SpatialArgs(op, shape);

            if (v.Length > (edx + 1))
            {
                body = v.Substring(edx + 1).Trim();
                if (body.Length > 0)
                {
                    Dictionary<String, String> aa = ParseMap(body);
                    args.DistErrPct = ReadDouble(aa["distErrPct"]); aa.Remove(DIST_ERR_PCT);
                    args.DistErr = ReadDouble(aa["distErr"]); aa.Remove(DIST_ERR);
                    if (aa.Count != 0)
                    {
                        throw new ArgumentException("unused parameters: " + aa);
                    }
                }
            }
            args.Validate();
            return args;
        }
        public virtual void TestArgsParser()
        {
            SpatialArgsParser parser = new SpatialArgsParser();

            String      arg  = SpatialOperation.IsWithin + "(Envelope(-10, 10, 20, -20))";
            SpatialArgs @out = parser.Parse(arg, ctx);

            assertEquals(SpatialOperation.IsWithin, @out.Operation);
            IRectangle bounds = (IRectangle)@out.Shape;

            assertEquals(-10.0, bounds.MinX, 0D);
            assertEquals(10.0, bounds.MaxX, 0D);

            // Disjoint should not be scored
            arg  = SpatialOperation.IsDisjointTo + " (Envelope(-10,-20,20,10))";
            @out = parser.Parse(arg, ctx);
            assertEquals(SpatialOperation.IsDisjointTo, @out.Operation);

            try
            {
                parser.Parse(SpatialOperation.IsDisjointTo + "[ ]", ctx);
                fail("spatial operations need args");
            }
#pragma warning disable 168
            catch (Exception ex)
#pragma warning restore 168
            {//expected
            }

            try
            {
                parser.Parse("XXXX(Envelope(-10, 10, 20, -20))", ctx);
                fail("unknown operation!");
            }
#pragma warning disable 168
            catch (Exception ex)
#pragma warning restore 168
            {//expected
            }
        }
		public SpatialArgs Parse(String v, SpatialContext ctx)
		{
			int idx = v.IndexOf('(');
			int edx = v.LastIndexOf(')');

			if (idx < 0 || idx > edx)
			{
				throw new InvalidSpatialArgument("missing parens: " + v);
			}

			SpatialOperation op = SpatialOperation.Get(v.Substring(0, idx).Trim());

			//Substring in .NET is (startPosn, length), But in Java it's (startPosn, endPosn)
			//see http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#substring(int, int)
			String body = v.Substring(idx + 1, edx - (idx + 1)).Trim();
			if (body.Length < 1)
			{
				throw new InvalidSpatialArgument("missing body : " + v);
			}

			var shape = ctx.ReadShape(body);
			var args = new SpatialArgs(op, shape);

			if (v.Length > (edx + 1))
			{
				body = v.Substring(edx + 1).Trim();
				if (body.Length > 0)
				{
					Dictionary<String, String> aa = ParseMap(body);
					args.Min = ReadDouble(aa["min"]);
					args.Max = ReadDouble(aa["max"]);
					args.SetDistPrecision(ReadDouble(aa["distPrec"]));
					if (aa.Count > 3)
					{
						throw new InvalidSpatialArgument("unused parameters: " + aa);
					}
				}
			}
			return args;
		}
        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);
        }
Exemple #22
0
        /// <summary>
        /// Writes a close approximation to the parsed input format.
        /// </summary>
        public static string WriteSpatialArgs(SpatialArgs args)
        {
            // LUCENENET specific - added guard clause
            if (args is null)
            {
                throw new ArgumentNullException(nameof(args));
            }

            var str = new StringBuilder();

            str.Append(args.Operation.Name);
            str.Append('(');
            str.Append(args.Shape);
            if (args.DistErrPct != null)
            {
                str.Append(" distErrPct=").Append(string.Format("{0:0.00}%", args.DistErrPct * 100d, CultureInfo.InvariantCulture));
            }
            if (args.DistErr != null)
            {
                str.Append(" distErr=").Append(args.DistErr);
            }
            str.Append(')');
            return(str.ToString());
        }
Exemple #23
0
        private void _checkHits(bool bbox, String ptStr, double distKM, int assertNumFound, params int[] assertIds)
        {
            SpatialOperation op = SpatialOperation.Intersects;
            var pt = (Point) ctx.ReadShape(ptStr);
            double distDEG = DistanceUtils.Dist2Degrees(distKM, DistanceUtils.EARTH_MEAN_RADIUS_KM);
            Shape shape = ctx.MakeCircle(pt, distDEG);
            if (bbox)
                shape = shape.GetBoundingBox();

            SpatialArgs args = new SpatialArgs(op, shape);
            //args.setDistPrecision(0.025);
            Query query;
            if (random.NextDouble() > 0.5)
            {
                query = strategy.MakeQuery(args);
            }
            else
            {
                query = new FilteredQuery(new MatchAllDocsQuery(), strategy.MakeFilter(args));
            }
            SearchResults results = executeQuery(query, 100);
            assertEquals("" + shape, assertNumFound, results.numFound);
            if (assertIds != null)
            {
                var resultIds = new HashSet<int>();
                foreach (var result in results.results)
                {
                    resultIds.Add(int.Parse(result.document.Get("id")));
                }
                foreach (int assertId in assertIds)
                {
                    assertTrue("has " + assertId, resultIds.Contains(assertId));
                }
            }
        }
Exemple #24
0
		public static Query MakeQuery(SpatialStrategy spatialStrategy, string shapeWKT, SpatialRelation relation,
									  double distanceErrorPct = 0.025)
		{
			SpatialOperation spatialOperation;
			var shape = ReadShape(shapeWKT);

			switch (relation)
			{
				case SpatialRelation.Within:
					spatialOperation = SpatialOperation.IsWithin;
					break;
				case SpatialRelation.Contains:
					spatialOperation = SpatialOperation.Contains;
					break;
				case SpatialRelation.Disjoint:
					spatialOperation = SpatialOperation.IsDisjointTo;
					break;
				case SpatialRelation.Intersects:
					spatialOperation = SpatialOperation.Intersects;
					break;
				case SpatialRelation.Nearby:
					// only sort by this, do not filter
					return new FunctionQuery(spatialStrategy.MakeDistanceValueSource(shape.GetCenter()));
				default:
					throw new ArgumentOutOfRangeException("relation");
			}
			var args = new SpatialArgs(spatialOperation, shape) { DistErrPct = distanceErrorPct };

			return spatialStrategy.MakeQuery(args);
		}
		public override Filter MakeFilter(SpatialArgs args)
		{
			var circle = args.GetShape() as Circle;
			if (circle != null)
			{
				if (SpatialOperation.Is(args.Operation,
					SpatialOperation.Intersects,
					SpatialOperation.IsWithin))
				{
					Query bbox = MakeWithin(circle.GetBoundingBox());

					// Make the ValueSource
					ValueSource valueSource = MakeValueSource(args);

					return new ValueSourceFilter(
						new QueryWrapperFilter(bbox), valueSource, 0, circle.GetRadius());
				}
			}
			return new QueryWrapperFilter(MakeQuery(args));
		}
Exemple #26
0
        private Query MakeSpatialQuery(SpatialArgs args)
        {
            var bbox = args.Shape as Rectangle;
            if (bbox == null)
                throw new InvalidOperationException("Can only query by Rectangle, not " + args.Shape);

            Query spatial = null;

            // Useful for understanding Relations:
            // http://edndoc.esri.com/arcsde/9.1/general_topics/understand_spatial_relations.htm
            SpatialOperation op = args.Operation;
            if (op == SpatialOperation.BBoxIntersects) spatial = MakeIntersects(bbox);
            else if (op == SpatialOperation.BBoxWithin) spatial = MakeWithin(bbox);
            else if (op == SpatialOperation.Contains) spatial = MakeContains(bbox);
            else if (op == SpatialOperation.Intersects) spatial = MakeIntersects(bbox);
            else if (op == SpatialOperation.IsEqualTo) spatial = MakeEquals(bbox);
            else if (op == SpatialOperation.IsDisjointTo) spatial = MakeDisjoint(bbox);
            else if (op == SpatialOperation.IsWithin) spatial = MakeWithin(bbox);
            else if (op == SpatialOperation.Overlaps) spatial = MakeIntersects(bbox);
            else
            {
                throw new UnsupportedSpatialOperation(op);
            }
            return spatial;
        }
Exemple #27
0
		public static Filter MakeFilter(SpatialStrategy spatialStrategy, IndexQuery indexQuery)
		{
			var spatialQry = indexQuery as SpatialIndexQuery;
			if (spatialQry == null) return null;

			var args = new SpatialArgs(SpatialOperation.IsWithin, shapeReadWriter.ReadShape(spatialQry.QueryShape));
			return spatialStrategy.MakeFilter(args);
		}
Exemple #28
0
 public override ConstantScoreQuery MakeQuery(SpatialArgs args)
 {
     return new ConstantScoreQuery(new QueryWrapperFilter(MakeSpatialQuery(args)));
 }
Exemple #29
0
        public Query MakeQueryWithValueSource(SpatialArgs args, ValueSource valueSource)
        {
            var bq = new BooleanQuery();
            var spatial = MakeFilter(args);
            bq.Add(new ConstantScoreQuery(spatial), Occur.MUST);

            // This part does the scoring
            Query spatialRankingQuery = new FunctionQuery(valueSource);
            bq.Add(spatialRankingQuery, Occur.MUST);
            return bq;
        }
Exemple #30
0
 public override Filter MakeFilter(SpatialArgs args)
 {
     return new QueryWrapperFilter(MakeSpatialQuery(args));
 }
Exemple #31
0
		/// <summary>
		/// Make a Filter based principally on {@link org.apache.lucene.spatial.query.SpatialOperation}
		/// and {@link Shape} from the supplied {@code args}.
		/// <p />
		/// If a subclasses implements
		/// {@link #makeQuery(org.apache.lucene.spatial.query.SpatialArgs)}
		/// then this method could be simply:
		/// <pre>return new QueryWrapperFilter(makeQuery(args).getQuery());</pre>
		/// </summary>
		/// <param name="args"></param>
		/// <returns></returns>
		public abstract Filter MakeFilter(SpatialArgs args);
 public override Filter MakeFilter(SpatialArgs args)
 {
     args.Shape = GetRectangle(args.Shape);
     return base.MakeFilter(args);
 }
		public override ValueSource MakeValueSource(SpatialArgs args)
		{
			Point p = args.GetShape().GetCenter();
			return new DistanceValueSource(this, p, ctx.GetDistCalc());
		}
		public override Query MakeQuery(SpatialArgs args)
		{
			// For starters, just limit the bbox
			var shape = args.GetShape();
			if (!(shape is Rectangle || shape is Circle))
				throw new InvalidShapeException("Only Rectangles and Circles are currently supported, found ["
					+ shape.GetType().Name + "]");//TODO

			Rectangle bbox = shape.GetBoundingBox();
			if (bbox.GetCrossesDateLine())
			{
				throw new InvalidOperationException("Crossing dateline not yet supported");
			}

			ValueSource valueSource = null;

			Query spatial = null;
			SpatialOperation op = args.Operation;

			if (SpatialOperation.Is(op,
				SpatialOperation.BBoxWithin,
				SpatialOperation.BBoxIntersects))
			{
				spatial = MakeWithin(bbox);
			}
			else if (SpatialOperation.Is(op,
			  SpatialOperation.Intersects,
			  SpatialOperation.IsWithin))
			{
				spatial = MakeWithin(bbox);
				var circle = args.GetShape() as Circle;
				if (circle != null)
				{
					// Make the ValueSource
					valueSource = MakeValueSource(args);

					var vsf = new ValueSourceFilter(
						new QueryWrapperFilter(spatial), valueSource, 0, circle.GetRadius());

					spatial = new FilteredQuery(new MatchAllDocsQuery(), vsf);
				}
			}
			else if (op == SpatialOperation.IsDisjointTo)
			{
				spatial = MakeDisjoint(bbox);
			}

			if (spatial == null)
			{
				throw new UnsupportedSpatialOperation(args.Operation);
			}

			if (valueSource != null)
			{
				valueSource = new CachingDoubleValueSource(valueSource);
			}
			else
			{
				valueSource = MakeValueSource(args);
			}
			Query spatialRankingQuery = new FunctionQuery(valueSource);
			var bq = new BooleanQuery();
			bq.Add(spatial, Occur.MUST);
			bq.Add(spatialRankingQuery, Occur.MUST);
			return bq;

		}
Exemple #35
0
	    /// <summary>
	    /// Make a (ConstantScore) Query based principally on {@link org.apache.lucene.spatial.query.SpatialOperation}
	    /// and {@link Shape} from the supplied {@code args}.
	    /// The default implementation is
	    /// <pre>return new ConstantScoreQuery(makeFilter(args));</pre>
	    /// </summary>
	    /// <param name="args"></param>
	    /// <returns></returns>
	    public virtual ConstantScoreQuery MakeQuery(SpatialArgs args)
		{
            return new ConstantScoreQuery(MakeFilter(args));
		}
 public override ConstantScoreQuery MakeQuery(SpatialArgs args)
 {
     args.Shape = GetRectangle(args.Shape);
     return base.MakeQuery(args);
 }