org.apache.lucene.spatial.query.SpatialArgs Java Examples

The following examples show how to use org.apache.lucene.spatial.query.SpatialArgs. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PortedSolr3Test.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void _checkHits(boolean bbox, Point pt, double distKM, int assertNumFound, int... assertIds) {
  SpatialOperation op = SpatialOperation.Intersects;
  double distDEG = DistanceUtils.dist2Degrees(distKM, DistanceUtils.EARTH_MEAN_RADIUS_KM);
  Shape shape = shapeFactory.circle(pt, distDEG);
  if (bbox)
    shape = shape.getBoundingBox();

  SpatialArgs args = new SpatialArgs(op,shape);
  //args.setDistPrecision(0.025);
  Query query = strategy.makeQuery(args);
  SearchResults results = executeQuery(query, 100);
  assertEquals(""+shape,assertNumFound,results.numFound);
  if (assertIds != null) {
    Set<Integer> resultIds = new HashSet<>();
    for (SearchResult result : results.results) {
      resultIds.add(Integer.valueOf(result.document.get("id")));
    }
    for (int assertId : assertIds) {
      assertTrue("has " + assertId, resultIds.contains(assertId));
    }
  }
}
 
Example #2
Source File: RandomSpatialOpFuzzyPrefixTreeTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test /** LUCENE-4916 */
public void testWithinLeafApproxRule() throws IOException {
  setupQuadGrid(2, randomBoolean());//4x4 grid
  //indexed shape will simplify to entire right half (2 top cells)
  adoc("0", ctx.makeRectangle(192, 204, -128, 128));
  commit();

  ((RecursivePrefixTreeStrategy) strategy).setPrefixGridScanLevel(randomInt(2));

  //query does NOT contain it; both indexed cells are leaves to the query, and
  // when expanded to the full grid cells, the top one's top row is disjoint
  // from the query and thus not a match.
  assertTrue(executeQuery(strategy.makeQuery(
      new SpatialArgs(SpatialOperation.IsWithin, ctx.makeRectangle(38, 192, -72, 56))
  ), 1).numFound==0);//no-match

  //this time the rect is a little bigger and is considered a match. It's
  // an acceptable false-positive because of the grid approximation.
  assertTrue(executeQuery(strategy.makeQuery(
      new SpatialArgs(SpatialOperation.IsWithin, ctx.makeRectangle(38, 192, -72, 80))
  ), 1).numFound==1);//match
}
 
Example #3
Source File: GeoNameResolver.java    From lucene-geo-gazetteer with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of location near a certain coordinate. 
 * @param latitude, @param longitude - Center of search area 
 * @param distanceInMiles - Search Radius in miles
 * @param indexerPath - Path to Lucene index
 * @param count - Upper bound to number of results
 * @return - List of locations sorted by population
 * @throws IOException
 */
public List<Location> searchNearby(Double latitude, Double longitude, Double distanceInMiles, String indexerPath, int count) throws IOException {
	
	double distanceInDeg = DistanceUtils.dist2Degrees(distanceInMiles,DistanceUtils.EARTH_EQUATORIAL_RADIUS_MI);
	SpatialArgs spatialArgs = new SpatialArgs(SpatialOperation.IsWithin,
			ctx.makeCircle(longitude,latitude, distanceInDeg));
	
	String key = latitude+"-"+longitude;
	Filter filter = strategy.makeFilter(spatialArgs);
	
	IndexSearcher searcher = new IndexSearcher(createIndexReader(indexerPath));
	Sort sort = new Sort(populationSort);
	TopDocs topDocs = searcher.search(new MatchAllDocsQuery(), filter, count, sort);

	ScoreDoc[] scoreDocs = topDocs.scoreDocs;
	HashMap<String, List<Location>> allCandidates = new HashMap<String, List<Location>>();

	getMatchingCandidates(searcher, allCandidates, key, scoreDocs);
	List<Location> results = allCandidates.get(key);
	
	return results;
}
 
Example #4
Source File: OLuceneSpatialIndexManager.java    From orientdb-lucene with Apache License 2.0 6 votes vote down vote up
public Object searchIntersect(OCompositeKey key, double distance, OCommandContext context) throws IOException {

    double lat = ((Double) OType.convert(((OCompositeKey) key).getKeys().get(0), Double.class)).doubleValue();
    double lng = ((Double) OType.convert(((OCompositeKey) key).getKeys().get(1), Double.class)).doubleValue();
    SpatialOperation operation = SpatialOperation.Intersects;

    Point p = ctx.makePoint(lng, lat);
    SpatialArgs args = new SpatialArgs(operation, ctx.makeCircle(lng, lat,
        DistanceUtils.dist2Degrees(distance, DistanceUtils.EARTH_MEAN_RADIUS_KM)));
    Filter filter = strategy.makeFilter(args);
    IndexSearcher searcher = getSearcher();
    ValueSource valueSource = strategy.makeDistanceValueSource(p);
    Sort distSort = new Sort(valueSource.getSortField(false)).rewrite(searcher);

    return new LuceneResultSet(this,
        new SpatialQueryContext(context, searcher, new MatchAllDocsQuery(), filter, distSort).setSpatialArgs(args));
  }
 
Example #5
Source File: RandomSpatialOpFuzzyPrefixTreeTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
protected Shape gridSnap(Shape snapMe) {
  if (snapMe == null)
    return null;
  if (snapMe instanceof ShapePair) {
    ShapePair me = (ShapePair) snapMe;
    return new ShapePair(gridSnap(me.shape1), gridSnap(me.shape2), me.biasContainsThenWithin);
  }
  if (snapMe instanceof Point) {
    snapMe = snapMe.getBoundingBox();
  }
  //The next 4 lines mimic PrefixTreeStrategy.createIndexableFields()
  double distErrPct = ((PrefixTreeStrategy) strategy).getDistErrPct();
  double distErr = SpatialArgs.calcDistanceFromErrPct(snapMe, distErrPct, ctx);
  int detailLevel = grid.getLevelForDistance(distErr);
  CellIterator cells = grid.getTreeCellIterator(snapMe, detailLevel);

  //calc bounding box of cells.
  List<Shape> cellShapes = new ArrayList<>(1024);
  while (cells.hasNext()) {
    Cell cell = cells.next();
    if (!cell.isLeaf())
      continue;
    cellShapes.add(cell.getShape());
  }
  return new ShapeCollection<>(cellShapes, ctx).getBoundingBox();
}
 
Example #6
Source File: AbstractSpatialFieldType.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
protected Query getQueryFromSpatialArgs(QParser parser, SchemaField field, SpatialArgs spatialArgs) {
  T strategy = getStrategy(field.getName());

  SolrParams localParams = parser.getLocalParams();
  //See SOLR-2883 needScore
  String scoreParam = (localParams == null ? null : localParams.get(SCORE_PARAM));

  //We get the valueSource for the score then the filter and combine them.
  DoubleValuesSource valueSource = getValueSourceFromSpatialArgs(parser, field, spatialArgs, scoreParam, strategy);
  if (valueSource == null) {
    return strategy.makeQuery(spatialArgs); //assumed constant scoring
  }

  FunctionScoreQuery functionQuery = new FunctionScoreQuery(new MatchAllDocsQuery(), valueSource);

  if (localParams != null && !localParams.getBool(FILTER_PARAM, true))
    return functionQuery;

  Query filterQuery = strategy.makeQuery(spatialArgs);
  return new BooleanQuery.Builder()
      .add(functionQuery, Occur.MUST)//matches everything and provides score
      .add(filterQuery, Occur.FILTER)//filters (score isn't used)
      .build();
}
 
Example #7
Source File: TermQueryPrefixTreeStrategy.java    From incubator-retired-blur with Apache License 2.0 6 votes vote down vote up
@Override
public Filter makeFilter(SpatialArgs args) {
  final SpatialOperation op = args.getOperation();
  if (op != SpatialOperation.Intersects)
    throw new UnsupportedSpatialOperation(op);

  Shape shape = args.getShape();
  int detailLevel = grid.getLevelForDistance(args.resolveDistErr(ctx, distErrPct));
  List<Cell> cells = grid.getCells(shape, detailLevel, false,// no parents
      true);// simplify
  BytesRef[] terms = new BytesRef[cells.size()];
  int i = 0;
  for (Cell cell : cells) {
    terms[i++] = new BytesRef(cell.getTokenString());
  }
  return new TermsFilter(getFieldName(), terms);
}
 
Example #8
Source File: QueryEqualsHashCodeTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
private void testEqualsHashcode(SpatialArgs args1, SpatialArgs args2, ObjGenerator generator) {
  Object first;
  try {
    first = generator.gen(args1);
  } catch (UnsupportedOperationException e) {
    return;
  }
  if (first == null)
    return;//unsupported op?
  Object second = generator.gen(args1);//should be the same
  assertEquals(first, second);
  assertEquals(first.hashCode(), second.hashCode());
  assertTrue(args1.equals(args2) == false);
  second = generator.gen(args2);//now should be different
  assertTrue(first.equals(second) == false);
  assertTrue(first.hashCode() != second.hashCode());
}
 
Example #9
Source File: BBoxStrategy.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Query makeQuery(SpatialArgs args) {
  Shape shape = args.getShape();
  if (!(shape instanceof Rectangle))
    throw new UnsupportedOperationException("Can only query by Rectangle, not " + shape);

  Rectangle bbox = (Rectangle) shape;
  Query spatial;

  // Useful for understanding Relations:
  // http://edndoc.esri.com/arcsde/9.1/general_topics/understand_spatial_relations.htm
  SpatialOperation op = args.getOperation();
       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 { //no Overlaps support yet
      throw new UnsupportedSpatialOperation(op);
  }
  return new ConstantScoreQuery(spatial);
}
 
Example #10
Source File: SuperParserTest.java    From incubator-retired-blur with Apache License 2.0 6 votes vote down vote up
@Test
public void test28() throws ParseException {
  SpatialContext ctx = SpatialContext.GEO;
  ShapeReadWriter<SpatialContext> shapeReadWriter = new ShapeReadWriter<SpatialContext>(ctx);
  int maxLevels = 11;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
  RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, "a.id_gis", false);
  Circle circle = ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_KM));
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);

  String writeSpatialArgs = SpatialArgsParser.writeSpatialArgs(args, shapeReadWriter);

  // This has to be done because of rounding.
  SpatialArgs spatialArgs = SpatialArgsParser.parse(writeSpatialArgs, shapeReadWriter);
  Query q1 = sq(strategy.makeQuery(spatialArgs));
  Query q = parseSq("a.id_gis:\"" + writeSpatialArgs + "\"");
  boolean equals = q1.equals(q);
  assertTrue(equals);
}
 
Example #11
Source File: RecursivePrefixTreeStrategy.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Query makeQuery(SpatialArgs args) {
  final SpatialOperation op = args.getOperation();

  Shape shape = args.getShape();
  int detailLevel = grid.getLevelForDistance(args.resolveDistErr(ctx, distErrPct));

  if (op == SpatialOperation.Intersects) {
    if (isGridAlignedShape(args.getShape())) {
      return makeGridShapeIntersectsQuery(args.getShape());
    }
    return new IntersectsPrefixTreeQuery(
        shape, getFieldName(), grid, detailLevel, prefixGridScanLevel);
  } else if (op == SpatialOperation.IsWithin) {
    return new WithinPrefixTreeQuery(
        shape, getFieldName(), grid, detailLevel, prefixGridScanLevel,
        -1);//-1 flag is slower but ensures correct results
  } else if (op == SpatialOperation.Contains) {
    return new ContainsPrefixTreeQuery(shape, getFieldName(), grid, detailLevel,
        multiOverlappingIndexedShapes);
  }
  throw new UnsupportedSpatialOperation(op);
}
 
Example #12
Source File: LatLonPointSpatialField.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Query makeQuery(SpatialArgs args) {
  if (args.getOperation() != SpatialOperation.Intersects) {
    throw new UnsupportedSpatialOperation(args.getOperation());
  }
  Shape shape = args.getShape();
  if (indexed && docValues) {
    return new IndexOrDocValuesQuery(makeQueryFromIndex(shape), makeQueryFromDocValues(shape));
  } else if (indexed) {
    return makeQueryFromIndex(shape);
  } else if (docValues) {
    return makeQueryFromDocValues(shape);
  } else {
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
        getFieldName() + " needs indexed (preferred) or docValues to support search");
  }
}
 
Example #13
Source File: LuceneIndex.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
protected Iterable<? extends DocumentDistance> geoQuery(final IRI geoProperty, Point p, final IRI units,
		double distance, String distanceVar, Var contextVar) throws MalformedQueryException, IOException {
	double degs = GeoUnits.toDegrees(distance, units);
	final String geoField = SearchFields.getPropertyField(geoProperty);
	SpatialStrategy strategy = getSpatialStrategyMapper().apply(geoField);
	final Shape boundingCircle = strategy.getSpatialContext().getShapeFactory().circle(p, degs);
	Query q = strategy.makeQuery(new SpatialArgs(SpatialOperation.Intersects, boundingCircle));
	if (contextVar != null) {
		q = addContextTerm(q, (Resource) contextVar.getValue());
	}

	TopDocs docs = search(new FunctionScoreQuery(q, strategy.makeRecipDistanceValueSource(boundingCircle)));
	final boolean requireContext = (contextVar != null && !contextVar.hasValue());
	return Iterables.transform(Arrays.asList(docs.scoreDocs), new Function<ScoreDoc, DocumentDistance>() {

		@Override
		public DocumentDistance apply(ScoreDoc doc) {
			return new LuceneDocumentDistance(doc, geoField, units, boundingCircle.getCenter(), requireContext,
					LuceneIndex.this);
		}
	});
}
 
Example #14
Source File: BBoxStrategy.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
public Query makeQuery(SpatialArgs args) {
  Shape shape = args.getShape();
  if (!(shape instanceof Rectangle))
    throw new UnsupportedOperationException("Can only query by Rectangle, not " + shape);

  Rectangle bbox = (Rectangle) shape;
  Query spatial;

  // Useful for understanding Relations:
  // http://edndoc.esri.com/arcsde/9.1/general_topics/understand_spatial_relations.htm
  SpatialOperation op = args.getOperation();
       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 { //no Overlaps support yet
      throw new UnsupportedSpatialOperation(op);
  }
  return new ConstantScoreQuery(spatial);
}
 
Example #15
Source File: SpatialArgsTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void calcDistanceFromErrPct() {
  final SpatialContext ctx = usually() ? SpatialContext.GEO : new Geo3dSpatialContextFactory().newSpatialContext();
  final double DEP = 0.5;//distErrPct

  //the result is the diagonal distance from the center to the closest corner,
  // times distErrPct

  Shape superwide = ctx.makeRectangle(-180, 180, 0, 0);
  //0 distErrPct means 0 distance always
  assertEquals(0, SpatialArgs.calcDistanceFromErrPct(superwide, 0, ctx), 0);
  assertEquals(180 * DEP, SpatialArgs.calcDistanceFromErrPct(superwide, DEP, ctx), 0);

  Shape supertall = ctx.makeRectangle(0, 0, -90, 90);
  assertEquals(90 * DEP, SpatialArgs.calcDistanceFromErrPct(supertall, DEP, ctx), 0);

  Shape upperhalf = ctx.makeRectangle(-180, 180, 0, 90);
  assertEquals(45 * DEP, SpatialArgs.calcDistanceFromErrPct(upperhalf, DEP, ctx), 0.0001);

  Shape midCircle = ctx.makeCircle(0, 0, 45);
  assertEquals(60 * DEP, SpatialArgs.calcDistanceFromErrPct(midCircle, DEP, ctx), 0.0001);
}
 
Example #16
Source File: SuperParserTest.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
@Test
public void test29() throws ParseException {
  SpatialContext ctx = SpatialContext.GEO;
  int maxLevels = 11;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
  RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, "a.id_gis", false);
  Circle circle = ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_KM));
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);

  Query q1 = sq(strategy.makeQuery(args));
  Query q = parseSq("a.id_gis:\"Intersects(Circle(33.000000,-80.000000 d=10.0km))\"");
  boolean equals = q1.equals(q);
  assertTrue(equals);
}
 
Example #17
Source File: SpatialArgsParser.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
/**
 * Parses a string such as "Intersects(-10,20,-8,22) distErrPct=0.025".
 * 
 * @param v
 *          The string to parse. Mandatory.
 * @param shapeReadWriter
 *          The spatial shapeReadWriter. Mandatory.
 * @return Not null.
 * @throws IllegalArgumentException
 *           If there is a problem parsing the string.
 * @throws InvalidShapeException
 *           Thrown from {@link ShapeReadWriter#readShape(String)}
 */
public static SpatialArgs parse(String v, ShapeReadWriter<SpatialContext> shapeReadWriter) throws IllegalArgumentException, InvalidShapeException {
  int idx = v.indexOf('(');
  int edx = v.lastIndexOf(')');

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

  SpatialOperation op = SpatialOperation.get(v.substring(0, idx).trim());

  String body = v.substring(idx + 1, edx).trim();
  if (body.length() < 1) {
    throw new IllegalArgumentException("missing body : " + v, null);
  }

  Shape shape = shapeReadWriter.readShape(body);
  SpatialArgs args = new SpatialArgs(op, shape);

  if (v.length() > (edx + 1)) {
    body = v.substring(edx + 1).trim();
    if (body.length() > 0) {
      Map<String, String> aa = parseMap(body);
      args.setDistErrPct(readDouble(aa.remove(DIST_ERR_PCT)));
      args.setDistErr(readDouble(aa.remove(DIST_ERR)));
      if (!aa.isEmpty()) {
        throw new IllegalArgumentException("unused parameters: " + aa, null);
      }
    }
  }
  args.validate();
  return args;
}
 
Example #18
Source File: OLuceneSpatialIndexManager.java    From orientdb-lucene with Apache License 2.0 5 votes vote down vote up
public Object searchWithin(OSpatialCompositeKey key, OCommandContext context) throws IOException {

    Set<OIdentifiable> result = new HashSet<OIdentifiable>();

    Shape shape = factory.makeShape(key, ctx);
    if (shape == null)
      return null;
    SpatialArgs args = new SpatialArgs(SpatialOperation.IsWithin, shape);
    IndexSearcher searcher = getSearcher();

    Filter filter = strategy.makeFilter(args);

    return new LuceneResultSet(this, new SpatialQueryContext(context, searcher, new MatchAllDocsQuery(), filter));
  }
 
Example #19
Source File: SuperParserTest.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
@Test
public void test30() throws ParseException {
  SpatialContext ctx = SpatialContext.GEO;
  int maxLevels = 11;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
  RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, "a.id_gis", false);
  Circle circle = ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_MI));
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);

  Query q1 = sq(strategy.makeQuery(args));
  Query q = parseSq("a.id_gis:\"Intersects(Circle(33.000000,-80.000000 d=10.0m))\"");
  boolean equals = q1.equals(q);
  assertTrue(equals);
}
 
Example #20
Source File: SuperParserTest.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
@Test
public void test45() throws ParseException {
  SpatialContext ctx = SpatialContext.GEO;
  int maxLevels = 11;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
  RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, "a.id_gis", false);
  Circle circle = ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_MI));
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);

  Query q1 = sq(bq(bc_m(strategy.makeQuery(args))));
  Query q = parseSq("<+a.id_gis:\"Intersects(Circle(33.000000,-80.000000 d=10.0m))\">");
  boolean equals = q1.equals(q);
  assertTrue(equals);
}
 
Example #21
Source File: TestPointVectorStrategy.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void testInvalidQueryShape() {
  this.strategy = PointVectorStrategy.newInstance(ctx, getClass().getSimpleName());
  Point point = ctx.makePoint(0, 0);
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, point);
  this.strategy.makeQuery(args);
}
 
Example #22
Source File: SuperParserTest.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
@Test
public void test46() throws ParseException {
  SpatialContext ctx = SpatialContext.GEO;
  int maxLevels = 11;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
  RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, "a.id_gis", false);
  Circle circle = ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_MI));
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);

  Query q1 = sq(bq(bc_m(strategy.makeQuery(args)), bc(tq("rowid", "12345"))));
  Query q = parseSq("<+a.id_gis:\"Intersects(Circle(33.000000,-80.000000 d=10.0m))\" rowid:12345>");
  boolean equals = q1.equals(q);
  assertTrue(equals);
}
 
Example #23
Source File: SuperParserTest.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
@Test
public void test47() throws ParseException {
  SpatialContext ctx = SpatialContext.GEO;
  int maxLevels = 11;
  SpatialPrefixTree grid = new GeohashPrefixTree(ctx, maxLevels);
  RecursivePrefixTreeStrategy strategy = new RecursivePrefixTreeStrategy(grid, "a.id_gis", false);
  Circle circle = ctx.makeCircle(-80.0, 33.0, DistanceUtils.dist2Degrees(10, DistanceUtils.EARTH_MEAN_RADIUS_MI));
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);

  Query q1 = sq(strategy.makeQuery(args));
  Query q = parseSq("<a.id_gis:\"Intersects(Circle(33.000000,-80.000000 d=10.0m))\">");
  boolean equals = q1.equals(q);
  assertTrue(equals);
}
 
Example #24
Source File: ToMatchQuery.java    From crate with Apache License 2.0 5 votes vote down vote up
private SpatialArgs getArgs(Shape shape, ShapeRelation relation) {
    switch (relation) {
        case INTERSECTS:
            return new SpatialArgs(SpatialOperation.Intersects, shape);
        case DISJOINT:
            return new SpatialArgs(SpatialOperation.IsDisjointTo, shape);
        case WITHIN:
            return new SpatialArgs(SpatialOperation.IsWithin, shape);
        default:
            throw invalidMatchType(relation.getRelationName());
    }
}
 
Example #25
Source File: BaseSpatialFieldTypeDefinition.java    From incubator-retired-blur with Apache License 2.0 5 votes vote down vote up
protected void checkSpatialArgs(SpatialArgs args) {
  SpatialOperation operation = args.getOperation();
  for (SpatialOperation so : _supportedOperations) {
    if (operation == so) {
      return;
    }
  }
  throw new IllegalArgumentException(_strategy.getClass().getName() + " only supports [" + _supportedOperations
      + "] operation.");
}
 
Example #26
Source File: BBoxField.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
protected DoubleValuesSource getValueSourceFromSpatialArgs(QParser parser, SchemaField field, SpatialArgs spatialArgs, String scoreParam, BBoxStrategy strategy) {
  if (scoreParam == null) {
    return null;
  }

  switch (scoreParam) {
    //TODO move these to superclass after LUCENE-5804 ?
    case OVERLAP_RATIO:
      double queryTargetProportion = 0.25;//Suggested default; weights towards target area

      String v = parser.getParam(PARAM_QUERY_TARGET_PROPORTION);
      if (v != null)
        queryTargetProportion = Double.parseDouble(v);

      double minSideLength = 0.0;
      v = parser.getParam(PARAM_MIN_SIDE_LENGTH);
      if (v != null)
        minSideLength = Double.parseDouble(v);

      return new BBoxOverlapRatioValueSource(
          strategy.makeShapeValueSource(), ctx.isGeo(),
          (Rectangle) spatialArgs.getShape(),
          queryTargetProportion, minSideLength);

    case AREA:
      return new ShapeAreaValueSource(strategy.makeShapeValueSource(), ctx, ctx.isGeo(),
          distanceUnits.multiplierFromDegreesToThisUnit() * distanceUnits.multiplierFromDegreesToThisUnit());

    case AREA2D:
      return new ShapeAreaValueSource(strategy.makeShapeValueSource(), ctx, false,
          distanceUnits.multiplierFromDegreesToThisUnit() * distanceUnits.multiplierFromDegreesToThisUnit());

    default:
      return super.getValueSourceFromSpatialArgs(parser, field, spatialArgs, scoreParam, strategy);
  }
}
 
Example #27
Source File: AbstractSpatialFieldType.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
protected DoubleValuesSource getValueSourceFromSpatialArgs(QParser parser, SchemaField field, SpatialArgs spatialArgs, String score, T strategy) {
  if (score == null) {
    return null;
  }

  final double multiplier; // default multiplier for degrees

  switch(score) {
    case "":
    case NONE:
      return null;
    case RECIP_DISTANCE:
      return strategy.makeRecipDistanceValueSource(spatialArgs.getShape());
    case DISTANCE:
      multiplier = distanceUnits.multiplierFromDegreesToThisUnit();
      break;
    default:
      DistanceUnits du = parseDistanceUnits(score);
      if (du != null) {
        multiplier = du.multiplierFromDegreesToThisUnit();
      } else {
        throw new SolrException(SolrException.ErrorCode.BAD_REQUEST,
                                "'score' local-param must be one of " + supportedScoreModes + ", it was: " + score);
      }
  }

  return strategy.makeDistanceValueSource(spatialArgs.getShape().getCenter(), multiplier);
}
 
Example #28
Source File: AbstractSpatialFieldType.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
protected Query getSpecializedRangeQuery(QParser parser, SchemaField field, String part1, String part2, boolean minInclusive, boolean maxInclusive) {
  if (!minInclusive || !maxInclusive)
    throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "Both sides of spatial range query must be inclusive: " + field.getName());
  Point p1 = SpatialUtils.parsePointSolrException(part1, ctx);
  Point p2 = SpatialUtils.parsePointSolrException(part2, ctx);

  Rectangle bbox = ctx.makeRectangle(p1, p2);
  SpatialArgs spatialArgs = new SpatialArgs(SpatialOperation.Intersects, bbox);
  return getQueryFromSpatialArgs(parser, field, spatialArgs);//won't score by default
}
 
Example #29
Source File: AbstractSpatialFieldType.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
/**
 * Implemented for compatibility with geofilt &amp; bbox query parsers:
 * {@link SpatialQueryable}.
 */
@Override
public Query createSpatialQuery(QParser parser, SpatialOptions options) {
  Point pt = SpatialUtils.parsePointSolrException(options.pointStr, ctx);

  double distDeg = DistanceUtils.dist2Degrees(options.distance, options.radius);

  Shape shape = ctx.makeCircle(pt, distDeg);
  if (options.bbox)
    shape = shape.getBoundingBox();

  SpatialArgs spatialArgs = new SpatialArgs(SpatialOperation.Intersects, shape);
  return getQueryFromSpatialArgs(parser, options.field, spatialArgs);
}
 
Example #30
Source File: DateRangeField.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Override
protected SpatialArgs parseSpatialArgs(QParser parser, String externalVal) {
  //We avoid SpatialArgsParser entirely because it isn't very Solr-friendly
  final Shape shape = parseShape(externalVal);
  final SolrParams localParams = parser.getLocalParams();
  SpatialOperation op = SpatialOperation.Intersects;
  if (localParams != null) {
    String opStr = localParams.get(OP_PARAM);
    if (opStr != null)
      op = SpatialOperation.get(opStr);
  }
  return new SpatialArgs(op, shape);
}