Java Code Examples for org.apache.lucene.spatial.query.SpatialOperation#Intersects

The following examples show how to use org.apache.lucene.spatial.query.SpatialOperation#Intersects . 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: 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 2
Source File: LuceneIndex.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private SpatialOperation toSpatialOp(String relation) {
	if (GEOF.SF_INTERSECTS.stringValue().equals(relation)) {
		return SpatialOperation.Intersects;
	} else if (GEOF.SF_DISJOINT.stringValue().equals(relation)) {
		return SpatialOperation.IsDisjointTo;
	} else if (GEOF.SF_EQUALS.stringValue().equals(relation)) {
		return SpatialOperation.IsEqualTo;
	} else if (GEOF.SF_OVERLAPS.stringValue().equals(relation)) {
		return SpatialOperation.Overlaps;
	} else if (GEOF.EH_COVERED_BY.stringValue().equals(relation)) {
		return SpatialOperation.IsWithin;
	} else if (GEOF.EH_COVERS.stringValue().equals(relation)) {
		return SpatialOperation.Contains;
	}
	return null;
}
 
Example 3
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 4
Source File: OLuceneSpatialIndexManager.java    From orientdb-lucene with Apache License 2.0 6 votes vote down vote up
@Override
public Object get(Object key) {
  try {
    if (key instanceof OSpatialCompositeKey) {
      final OSpatialCompositeKey newKey = (OSpatialCompositeKey) key;

      final SpatialOperation strategy = newKey.getOperation() != null ? newKey.getOperation() : SpatialOperation.Intersects;

      if (SpatialOperation.Intersects.equals(strategy))
        return searchIntersect(newKey, newKey.getMaxDistance(), newKey.getContext());
      else if (SpatialOperation.IsWithin.equals(strategy))
        return searchWithin(newKey, newKey.getContext());

    } else if (key instanceof OCompositeKey)
      return searchIntersect((OCompositeKey) key, 0, null);

  } catch (IOException e) {
    OLogManager.instance().error(this, "Error on getting entry against Lucene index", e);
  }

  return null;
}
 
Example 5
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 6
Source File: QueryEqualsHashCodeTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testEqualsHashCode() {

  switch (random().nextInt(4)) {//0-3
    case 0: predicate = SpatialOperation.Contains; break;
    case 1: predicate = SpatialOperation.IsWithin; break;

    default: predicate = SpatialOperation.Intersects; break;
  }
  final SpatialPrefixTree gridQuad = new QuadPrefixTree(ctx,10);
  final SpatialPrefixTree gridGeohash = new GeohashPrefixTree(ctx,10);

  Collection<SpatialStrategy> strategies = new ArrayList<>();
  RecursivePrefixTreeStrategy recursive_geohash = new RecursivePrefixTreeStrategy(gridGeohash, "recursive_geohash");
  strategies.add(recursive_geohash);
  strategies.add(new TermQueryPrefixTreeStrategy(gridQuad, "termquery_quad"));
  strategies.add(PointVectorStrategy.newInstance(ctx, "pointvector"));
  strategies.add(BBoxStrategy.newInstance(ctx, "bbox"));
  final SerializedDVStrategy serialized = new SerializedDVStrategy(ctx, "serialized");
  strategies.add(serialized);
  strategies.add(new CompositeSpatialStrategy("composite", recursive_geohash, serialized));
  for (SpatialStrategy strategy : strategies) {
    testEqualsHashcode(strategy);
  }
}
 
Example 7
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 8
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 9
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 10
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 11
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 12
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 13
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);
}
 
Example 14
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 15
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 16
Source File: LuceneQueryBuilder.java    From Elasticsearch 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);
    }
    throw invalidMatchType(relation.getRelationName());
}
 
Example 17
Source File: GeoShapeQueryParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public static SpatialArgs getArgs(ShapeBuilder shape, ShapeRelation relation) {
    switch(relation) {
    case DISJOINT:
        return new SpatialArgs(SpatialOperation.IsDisjointTo, shape.build());
    case INTERSECTS:
        return new SpatialArgs(SpatialOperation.Intersects, shape.build());
    case WITHIN:
        return new SpatialArgs(SpatialOperation.IsWithin, shape.build());
    case CONTAINS:
        return new SpatialArgs(SpatialOperation.Contains, shape.build());
    default:
        throw new IllegalArgumentException("");

    }
}
 
Example 18
Source File: JtsPolygonTest.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private SpatialArgs q(String shapeStr, double distErrPct) throws ParseException {
  Shape shape = ctx.readShapeFromWkt(shapeStr);
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, shape);
  args.setDistErrPct(distErrPct);
  return args;
}
 
Example 19
Source File: TestRecursivePrefixTreeStrategy.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
private SpatialArgs q(Point pt, double distDEG, double distErrPct) {
  Shape shape = ctx.getShapeFactory().circle(pt, distDEG);
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects,shape);
  args.setDistErrPct(distErrPct);
  return args;
}
 
Example 20
Source File: TermQueryPrefixTreeStrategy.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
@Override
public Query makeQuery(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));

  //--get a List of BytesRef for each term we want (no parents, no leaf bytes))
  final int GUESS_NUM_TERMS;
  if (shape instanceof Point)
    GUESS_NUM_TERMS = detailLevel;//perfect guess
  else
    GUESS_NUM_TERMS = 4096;//should this be a method on SpatialPrefixTree?

  BytesRefBuilder masterBytes = new BytesRefBuilder();//shared byte array for all terms
  List<BytesRef> terms = new ArrayList<>(GUESS_NUM_TERMS);

  CellIterator cells = grid.getTreeCellIterator(shape, detailLevel);
  while (cells.hasNext()) {
    Cell cell = cells.next();
    if (!cell.isLeaf())
      continue;
    BytesRef term = cell.getTokenBytesNoLeaf(null);//null because we want a new BytesRef
    //We copy out the bytes because it may be re-used across the iteration. This also gives us the opportunity
    // to use one contiguous block of memory for the bytes of all terms we need.
    masterBytes.grow(masterBytes.length() + term.length);
    masterBytes.append(term);
    term.bytes = null;//don't need; will reset later
    term.offset = masterBytes.length() - term.length;
    terms.add(term);
  }
  //doing this now because if we did earlier, it's possible the bytes needed to grow()
  for (BytesRef byteRef : terms) {
    byteRef.bytes = masterBytes.bytes();
  }
  //unfortunately TermsQuery will needlessly sort & dedupe
  //TODO an automatonQuery might be faster?
  return new TermInSetQuery(getFieldName(), terms);
}