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

The following examples show how to use org.apache.lucene.spatial.query.SpatialOperation. These examples are extracted from open source projects. 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 Project: rdf4j   Source File: LuceneIndex.java    License: 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 2
Source Project: rdf4j   Source File: LuceneIndex.java    License: 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 Project: lucene-solr   Source File: RecursivePrefixTreeStrategy.java    License: 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 4
Source Project: lucene-solr   Source File: BBoxStrategy.java    License: 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 5
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 6
@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 7
Source Project: lucene-solr   Source File: Geo3dRptTest.java    License: 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 8
Source Project: lucene-solr   Source File: Geo3dRptTest.java    License: 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 9
Source Project: lucene-solr   Source File: QueryEqualsHashCodeTest.java    License: 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 10
Source Project: lucene-solr   Source File: TestTestFramework.java    License: 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 11
Source Project: lucene-solr   Source File: CompositeStrategyTest.java    License: 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 12
Source Project: lucene-solr   Source File: PortedSolr3Test.java    License: 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 13
Source Project: lucene-solr   Source File: BBoxStrategy.java    License: 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 Project: lucene-solr   Source File: LatLonPointSpatialField.java    License: 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 15
Source Project: lucene-geo-gazetteer   Source File: GeoNameResolver.java    License: 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 16
@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 17
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 18
Source Project: orientdb-lucene   Source File: OLuceneWithinOperator.java    License: 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 19
@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 20
@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 21
Source Project: incubator-retired-blur   Source File: SuperParserTest.java    License: 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 22
Source Project: geode-examples   Source File: SpatialHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Return a lucene query that finds all points within the given radius from the given point
 */
public static Query findWithin(double longitude, double latitude, double radiusMiles) {
  // Covert the radius in miles to a radius in degrees
  double radiusDEG = DistanceUtils.dist2Degrees(radiusMiles, EARTH_MEAN_RADIUS_MI);

  // Create a query that looks for all points within a circle around the given point
  SpatialArgs args = new SpatialArgs(SpatialOperation.IsWithin,
      new GeoCircle(createPoint(longitude, latitude), radiusDEG, CONTEXT));
  return STRATEGY.makeQuery(args);
}
 
Example 23
Source Project: Elasticsearch   Source File: LuceneQueryBuilder.java    License: 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 24
Source Project: Elasticsearch   Source File: GeoShapeQueryParser.java    License: 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 25
Source Project: linden   Source File: SpatialFilterConstructor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Filter construct(LindenFilter lindenFilter, LindenConfig config) throws IOException {
  LindenSpatialFilter spatialFilter = lindenFilter.getSpatialFilter();
  SpatialArgs spatialArgs = new SpatialArgs(
      SpatialOperation.Intersects,
      spatialContext.makeCircle(
          spatialFilter.getSpatialParam().coordinate.getLongitude(),
          spatialFilter.getSpatialParam().coordinate.getLatitude(),
          DistanceUtils
              .dist2Degrees(spatialFilter.getSpatialParam().getDistanceRange(), DistanceUtils.EARTH_MEAN_RADIUS_KM)));
  return spatialStrategy.makeFilter(spatialArgs);
}
 
Example 26
Source Project: rdf4j   Source File: LuceneIndex.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected Iterable<? extends DocumentResult> geoRelationQuery(String relation, IRI geoProperty, Shape shape,
		Var contextVar) throws MalformedQueryException, IOException {
	SpatialOperation op = toSpatialOp(relation);
	if (op == null) {
		return null;
	}

	final String geoField = SearchFields.getPropertyField(geoProperty);
	SpatialStrategy strategy = getSpatialStrategyMapper().apply(geoField);
	Query q = strategy.makeQuery(new SpatialArgs(op, shape));
	if (contextVar != null) {
		q = addContextTerm(q, (Resource) contextVar.getValue());
	}

	TopDocs docs = search(q);
	final Set<String> fields = Sets.newHashSet(SearchFields.URI_FIELD_NAME, geoField);
	if (contextVar != null && !contextVar.hasValue()) {
		fields.add(SearchFields.CONTEXT_FIELD_NAME);
	}
	return Iterables.transform(Arrays.asList(docs.scoreDocs), new Function<ScoreDoc, DocumentResult>() {

		@Override
		public DocumentResult apply(ScoreDoc doc) {
			return new LuceneDocumentResult(doc, LuceneIndex.this, fields);
		}
	});
}
 
Example 27
Source Project: lucene-solr   Source File: SpatialFileQueryMaker.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void setConfig(Config config) throws Exception {
  strategy = SpatialDocMaker.getSpatialStrategy(config.getRoundNumber());
  shapeConverter = SpatialDocMaker.makeShapeConverter(strategy, config, "query.spatial.");

  distErrPct = config.get("query.spatial.distErrPct", Double.NaN);
  operation = SpatialOperation.get(config.get("query.spatial.predicate", "Intersects"));
  score = config.get("query.spatial.score", false);

  super.setConfig(config);//call last, will call prepareQueries()
}
 
Example 28
Source Project: crate   Source File: ToMatchQuery.java    License: 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 29
@Test
public void testPackedQuadPointsOnlyBug() throws IOException {
  setupQuadGrid(1, true); // packed quad.  maxLevels doesn't matter.
  setupCtx2D(ctx);
  ((PrefixTreeStrategy) strategy).setPointsOnly(true);
  Point point = ctx.makePoint(169.0, 107.0);
  adoc("0", point);
  commit();
  Query query = strategy.makeQuery(new SpatialArgs(SpatialOperation.Intersects, point));
  assertEquals(1, executeQuery(query, 1).numFound);
}
 
Example 30
@Test
public void testPointsOnlyOptBug() throws IOException {
  setupQuadGrid(8, false);
  setupCtx2D(ctx);
  ((PrefixTreeStrategy) strategy).setPointsOnly(true);
  Point point = ctx.makePoint(86, -127.44362190053255);
  adoc("0", point);
  commit();
  Query query = strategy.makeQuery(new SpatialArgs(SpatialOperation.Intersects,
      ctx.makeRectangle(point, point)));
  assertEquals(1, executeQuery(query, 1).numFound);
}