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

The following examples show how to use org.apache.lucene.spatial.query.SpatialOperation. 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: 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 #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: 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 #5
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 #6
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 #7
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 #8
Source File: OLuceneWithinOperator.java    From orientdb-lucene with Apache License 2.0 6 votes vote down vote up
@Override
public OIndexCursor executeIndexQuery(OCommandContext iContext, OIndex<?> index, List<Object> keyParams, boolean ascSortOrder) {
  OIndexDefinition definition = index.getDefinition();
  int idxSize = definition.getFields().size();
  int paramsSize = keyParams.size();
  OIndexCursor cursor;
  Object indexResult = index.get(new OSpatialCompositeKey(keyParams).setOperation(SpatialOperation.IsWithin));
  if (indexResult == null || indexResult instanceof OIdentifiable)
    cursor = new OIndexCursorSingleValue((OIdentifiable) indexResult, new OSpatialCompositeKey(keyParams));
  else
    cursor = new OIndexCursorCollectionValue(((Collection<OIdentifiable>) indexResult).iterator(), new OSpatialCompositeKey(
        keyParams));

  iContext.setVariable("$luceneIndex", true);
  return cursor;
}
 
Example #9
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 #10
Source File: CompositeStrategyTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testOperations() throws IOException {
  //setup
  if (randomBoolean()) {
    setupQuadGrid(-1);
  } else {
    setupGeohashGrid(-1);
  }
  SerializedDVStrategy serializedDVStrategy = new SerializedDVStrategy(ctx, getClass().getSimpleName() + "_sdv");
  this.strategy = new CompositeSpatialStrategy("composite_" + getClass().getSimpleName(),
      rptStrategy, serializedDVStrategy);

  //Do it!

  for (SpatialOperation pred : SpatialOperation.values()) {
    if (pred == SpatialOperation.BBoxIntersects || pred == SpatialOperation.BBoxWithin) {
      continue;
    }
    if (pred == SpatialOperation.IsDisjointTo) {//TODO
      continue;
    }
    testOperationRandomShapes(pred);
    deleteAll();
    commit();
  }
}
 
Example #11
Source File: RandomSpatialOpStrategyTestCase.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
protected void testOperationRandomShapes(final SpatialOperation operation) throws IOException {

    final int numIndexedShapes = randomIntBetween(1, 6);
    List<Shape> indexedShapes = new ArrayList<>(numIndexedShapes);
    for (int i = 0; i < numIndexedShapes; i++) {
      indexedShapes.add(randomIndexedShape());
    }

    final int numQueryShapes = atLeast(20);
    List<Shape> queryShapes = new ArrayList<>(numQueryShapes);
    for (int i = 0; i < numQueryShapes; i++) {
      queryShapes.add(randomQueryShape());
    }

    testOperation(operation, indexedShapes, queryShapes, true/*havoc*/);
  }
 
Example #12
Source File: SpatialRecursivePrefixTreeStrategyFieldTypeDefinition.java    From incubator-retired-blur with Apache License 2.0 6 votes vote down vote up
@Override
public void configure(String fieldNameForThisInstance, Map<String, String> properties, Configuration configuration) {
  _ctx = SpatialContext.GEO;
  _grid = getSpatialPrefixTree(fieldNameForThisInstance, properties);
  boolean docValue = false;
  if (properties.get(DOC_VALUE) != null) {
    docValue = true;
  }
  _strategy = new RecursivePrefixTreeStrategy(_grid, fieldNameForThisInstance, docValue);
  _shapeReadWriter = new ShapeReadWriter<SpatialContext>(_ctx);
  addSupportedIndexedShapes(Shape.class);
  addSupportedOperations(SpatialOperation.IsDisjointTo);
  addSupportedOperations(SpatialOperation.Intersects);
  addSupportedOperations(SpatialOperation.IsWithin);
  addSupportedOperations(SpatialOperation.Contains);
}
 
Example #13
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 #14
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 #15
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 #16
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 #17
Source File: TestTestFramework.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testQueries() throws IOException {
  String name = StrategyTestCase.QTEST_Cities_Intersects_BBox;

  InputStream in = getClass().getClassLoader().getResourceAsStream(name);
  SpatialContext ctx = SpatialContext.GEO;
  Iterator<SpatialTestQuery> iter = SpatialTestQuery.getTestQueries(
      new SpatialArgsParser(), ctx, name, in );//closes the InputStream
  List<SpatialTestQuery> tests = new ArrayList<>();
  while( iter.hasNext() ) {
    tests.add( iter.next() );
  }
  Assert.assertEquals( 3, tests.size() );

  SpatialTestQuery sf = tests.get(0);
  // assert
  assertEquals( 1, sf.ids.size() );
  Assert.assertTrue( sf.ids.get(0).equals( "G5391959" ) );
  Assert.assertTrue( sf.args.getShape() instanceof Rectangle);
  assertEquals(SpatialOperation.Intersects, sf.args.getOperation());
}
 
Example #18
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 #19
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 #20
Source File: Geo3dRptTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testOperationsFromFile() throws IOException {
  setupStrategy();
  final Iterator<SpatialTestData> indexedSpatialData = getSampleData( "states-poly.txt");
  final List<Shape> indexedShapes = new ArrayList<>();
  while(indexedSpatialData.hasNext()) {
    indexedShapes.add(indexedSpatialData.next().shape);
  }
  final Iterator<SpatialTestData> querySpatialData = getSampleData( "states-bbox.txt");
  final List<Shape> queryShapes = new ArrayList<>();
  while(querySpatialData.hasNext()) {
    queryShapes.add(querySpatialData.next().shape);
    if (TEST_NIGHTLY) {
      queryShapes.add(randomQueryShape());
    }
  }
  queryShapes.add(randomQueryShape());
  testOperation(SpatialOperation.Intersects, indexedShapes, queryShapes, random().nextBoolean());
}
 
Example #21
Source File: Geo3dRptTest.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Test
public void testFailureLucene6535() throws IOException {
  setupStrategy();

  final List<GeoPoint> points = new ArrayList<>();
  points.add(new GeoPoint(planetModel, 18 * DEGREES_TO_RADIANS, -27 * DEGREES_TO_RADIANS));
  points.add(new GeoPoint(planetModel, -57 * DEGREES_TO_RADIANS, 146 * DEGREES_TO_RADIANS));
  points.add(new GeoPoint(planetModel, 14 * DEGREES_TO_RADIANS, -180 * DEGREES_TO_RADIANS));
  points.add(new GeoPoint(planetModel, -15 * DEGREES_TO_RADIANS, 153 * DEGREES_TO_RADIANS));
  final GeoPoint[] pathPoints = new GeoPoint[] {
      new GeoPoint(planetModel, 55.0 * DEGREES_TO_RADIANS, -26.0 * DEGREES_TO_RADIANS),
      new GeoPoint(planetModel, -90.0 * DEGREES_TO_RADIANS, 0.0),
      new GeoPoint(planetModel, 54.0 * DEGREES_TO_RADIANS, 165.0 * DEGREES_TO_RADIANS),
      new GeoPoint(planetModel, -90.0 * DEGREES_TO_RADIANS, 0.0)};
  final GeoPath path = GeoPathFactory.makeGeoPath(planetModel, 29 * DEGREES_TO_RADIANS, pathPoints);
  final Shape shape = new Geo3dShape<>(path,ctx);
  final Rectangle rect = ctx.makeRectangle(131, 143, 39, 54);
  testOperation(rect,SpatialOperation.Intersects,shape,true);
}
 
Example #22
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 #23
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 #24
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 #25
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 #26
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 #27
Source File: StrategyTestCase.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
protected void testOperation(Shape indexedShape, SpatialOperation operation,
                             Shape queryShape, boolean match) throws IOException {
  assertTrue("Faulty test",
      operation.evaluate(indexedShape, queryShape) == match ||
          indexedShape.equals(queryShape) &&
            (operation == SpatialOperation.Contains || operation == SpatialOperation.IsWithin));
  adoc("0", indexedShape);
  commit();
  Query query = strategy.makeQuery(new SpatialArgs(operation, queryShape));
  SearchResults got = executeQuery(query, 1);
  assert got.numFound <= 1 : "unclean test env";
  if ((got.numFound == 1) != match)
    fail(operation+" I:" + indexedShape + " Q:" + queryShape);
  deleteAll();//clean up after ourselves
}
 
Example #28
Source File: TestPointVectorStrategy.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testFieldOptions() throws IOException, ParseException {
  // It's not stored; test it isn't.
  this.strategy = PointVectorStrategy.newInstance(ctx, getClass().getSimpleName());
  adoc("99", "POINT(-5.0 8.2)");
  commit();
  SearchResults results = executeQuery(new MatchAllDocsQuery(), 1);
  Document document = results.results.get(0).document;
  assertNull("not stored", document.getField(strategy.getFieldName() + PointVectorStrategy.SUFFIX_X));
  assertNull("not stored", document.getField(strategy.getFieldName() + PointVectorStrategy.SUFFIX_Y));
  deleteAll();

  // Now we mark it stored.  We also disable pointvalues...
  FieldType fieldType = new FieldType(PointVectorStrategy.DEFAULT_FIELDTYPE);
  fieldType.setStored(true);
  fieldType.setDimensions(0, 0);//disable point values
  this.strategy = new PointVectorStrategy(ctx, getClass().getSimpleName(), fieldType);
  adoc("99", "POINT(-5.0 8.2)");
  commit();
  results = executeQuery(new MatchAllDocsQuery(), 1);
  document = results.results.get(0).document;
  assertEquals("stored", -5.0, document.getField(strategy.getFieldName() + PointVectorStrategy.SUFFIX_X).numericValue());
  assertEquals("stored", 8.2,  document.getField(strategy.getFieldName() + PointVectorStrategy.SUFFIX_Y).numericValue());

  // Test a query fails without point values
  expectThrows(UnsupportedOperationException.class, () -> {
    SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, ctx.makeRectangle(-10.0, 10.0, -5.0, 5.0));
    this.strategy.makeQuery(args);
  });
}
 
Example #29
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 #30
Source File: TestPointVectorStrategy.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testCircleShapeSupport() {
  this.strategy = PointVectorStrategy.newInstance(ctx, getClass().getSimpleName());
  Circle circle = ctx.makeCircle(ctx.makePoint(0, 0), 10);
  SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);
  Query query = this.strategy.makeQuery(args);

  assertNotNull(query);
}