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

The following examples show how to use org.apache.lucene.spatial.query.SpatialArgs. 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: 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 3
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 4
@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
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 Project: lucene-solr   Source File: QueryEqualsHashCodeTest.java    License: 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 7
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 8
Source Project: lucene-solr   Source File: SpatialArgsTest.java    License: 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 9
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 10
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 11
Source Project: lucene-solr   Source File: AbstractSpatialFieldType.java    License: 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 12
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 13
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 14
@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 15
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 16
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 17
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 18
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 19
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 20
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 21
Source Project: lucene-solr   Source File: SpatialFileQueryMaker.java    License: Apache License 2.0 5 votes vote down vote up
protected Query makeQueryFromShape(Shape shape) {
  SpatialArgs args = new SpatialArgs(operation, shape);
  if (!Double.isNaN(distErrPct))
    args.setDistErrPct(distErrPct);

  Query filterQuery = strategy.makeQuery(args);
  if (score) {
    //wrap with distance computing query
    DoubleValuesSource valueSource = strategy.makeDistanceValueSource(shape.getCenter());
    return new FunctionScoreQuery(filterQuery, valueSource);
  } else {
    return filterQuery; // assume constant scoring
  }
}
 
Example 22
Source Project: lucene-solr   Source File: PrefixTreeStrategy.java    License: Apache License 2.0 5 votes vote down vote up
public void setShape(Shape shape) {
  double distErr = SpatialArgs.calcDistanceFromErrPct(shape, distErrPct, ctx);
  int detailLevel = grid.getLevelForDistance(distErr);
  Iterator<Cell> cells = createCellIteratorToIndex(shape, detailLevel, null);
  CellToBytesRefIterator cellToBytesRefIterator = newCellToBytesRefIterator();
  cellToBytesRefIterator.reset(cells);
  setBytesRefIterator(cellToBytesRefIterator);
}
 
Example 23
Source Project: lucene-solr   Source File: SerializedDVStrategy.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a Query that should be used in a random-access fashion.
 * Use in another manner will be SLOW.
 */
@Override
public Query makeQuery(SpatialArgs args) {
  ShapeValuesSource shapeValueSource = makeShapeValueSource();
  ShapeValuesPredicate predicateValueSource = new ShapeValuesPredicate(shapeValueSource, args.getOperation(), args.getShape());
  return new PredicateValueSourceQuery(predicateValueSource);
}
 
Example 24
Source Project: lucene-solr   Source File: SpatialPrefixTreeTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * A PrefixTree pruning optimization gone bad, applicable when optimize=true.
 * See <a href="https://issues.apache.org/jira/browse/LUCENE-4770">LUCENE-4770</a>.
 */
@Test
public void testBadPrefixTreePrune() throws Exception {

  trie = new QuadPrefixTree(ctx, 12);
  TermQueryPrefixTreeStrategy strategy = new TermQueryPrefixTreeStrategy(trie, "geo");
  Document doc = new Document();
  doc.add(new TextField("id", "1", Store.YES));

  Shape area = ctx.makeRectangle(-122.82, -122.78, 48.54, 48.56);

  Field[] fields = strategy.createIndexableFields(area, 0.025);
  for (Field field : fields) {
    doc.add(field);
  }
  addDocument(doc);

  Point upperleft = ctx.makePoint(-122.88, 48.54);
  Point lowerright = ctx.makePoint(-122.82, 48.62);

  Query query = strategy.makeQuery(new SpatialArgs(SpatialOperation.Intersects, ctx.makeRectangle(upperleft, lowerright)));

  commit();

  TopDocs search = indexSearcher.search(query, 10);
  ScoreDoc[] scoreDocs = search.scoreDocs;
  for (ScoreDoc scoreDoc : scoreDocs) {
    System.out.println(indexSearcher.doc(scoreDoc.doc));
  }

  assertEquals(1, search.totalHits.value);
}
 
Example 25
private void checkHits(SpatialArgs args, int assertNumFound, int[] assertIds) {
  SearchResults got = executeQuery(strategy.makeQuery(args), 100);
  assertEquals("" + args, assertNumFound, got.numFound);
  if (assertIds != null) {
    Set<Integer> gotIds = new HashSet<>();
    for (SearchResult result : got.results) {
      gotIds.add(Integer.valueOf(result.document.get("id")));
    }
    for (int assertId : assertIds) {
      assertTrue("has "+assertId,gotIds.contains(assertId));
    }
  }
}
 
Example 26
@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 27
@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);
}
 
Example 28
/** See LUCENE-5062, {@link ContainsPrefixTreeQuery#multiOverlappingIndexedShapes}. */
@Test
public void testContainsPairOverlap() throws IOException {
  setupQuadGrid(3, randomBoolean());
  adoc("0", new ShapePair(ctx.makeRectangle(0, 33, -128, 128), ctx.makeRectangle(33, 128, -128, 128), true));
  commit();
  Query query = strategy.makeQuery(new SpatialArgs(SpatialOperation.Contains,
      ctx.makeRectangle(0, 128, -16, 128)));
  SearchResults searchResults = executeQuery(query, 1);
  assertEquals(1, searchResults.numFound);
}
 
Example 29
@Test
public void testWithinDisjointParts() throws IOException {
  setupQuadGrid(7, randomBoolean());
  //one shape comprised of two parts, quite separated apart
  adoc("0", new ShapePair(ctx.makeRectangle(0, 10, -120, -100), ctx.makeRectangle(220, 240, 110, 125), false));
  commit();
  //query surrounds only the second part of the indexed shape
  Query query = strategy.makeQuery(new SpatialArgs(SpatialOperation.IsWithin,
      ctx.makeRectangle(210, 245, 105, 128)));
  SearchResults searchResults = executeQuery(query, 1);
  //we shouldn't find it because it's not completely within
  assertTrue(searchResults.numFound == 0);
}
 
Example 30
Source Project: lucene-solr   Source File: JtsPolygonTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
/** LUCENE-4464 */
public void testCloseButNoMatch() throws Exception {
  getAddAndVerifyIndexedDocuments("LUCENE-4464.txt");
  SpatialArgs args = q(
      "POLYGON((-93.18100824442227 45.25676372469945," +
          "-93.23182001200654 45.21421290799412," +
          "-93.16315546122038 45.23742639412364," +
          "-93.18100824442227 45.25676372469945))",
      LUCENE_4464_distErrPct);
  SearchResults got = executeQuery(strategy.makeQuery(args), 100);
  assertEquals(1, got.numFound);
  assertEquals("poly2", got.results.get(0).document.get("id"));
  //did not find poly 1 !
}