Search in sources :

Example 21 with Rectangle

use of org.locationtech.spatial4j.shape.Rectangle in project elasticsearch by elastic.

the class GeoBoundingBoxQueryBuilderTests method doCreateTestQueryBuilder.

@Override
protected GeoBoundingBoxQueryBuilder doCreateTestQueryBuilder() {
    GeoBoundingBoxQueryBuilder builder = new GeoBoundingBoxQueryBuilder(GEO_POINT_FIELD_NAME);
    Rectangle box = RandomShapeGenerator.xRandomRectangle(random(), RandomShapeGenerator.xRandomPoint(random()));
    if (randomBoolean()) {
        // check the top-left/bottom-right combination of setters
        int path = randomIntBetween(0, 2);
        switch(path) {
            case 0:
                builder.setCorners(new GeoPoint(box.getMaxY(), box.getMinX()), new GeoPoint(box.getMinY(), box.getMaxX()));
                break;
            case 1:
                builder.setCorners(GeohashUtils.encodeLatLon(box.getMaxY(), box.getMinX()), GeohashUtils.encodeLatLon(box.getMinY(), box.getMaxX()));
                break;
            default:
                builder.setCorners(box.getMaxY(), box.getMinX(), box.getMinY(), box.getMaxX());
        }
    } else {
        // check the bottom-left/ top-right combination of setters
        if (randomBoolean()) {
            builder.setCornersOGC(new GeoPoint(box.getMinY(), box.getMinX()), new GeoPoint(box.getMaxY(), box.getMaxX()));
        } else {
            builder.setCornersOGC(GeohashUtils.encodeLatLon(box.getMinY(), box.getMinX()), GeohashUtils.encodeLatLon(box.getMaxY(), box.getMaxX()));
        }
    }
    if (randomBoolean()) {
        builder.setValidationMethod(randomFrom(GeoValidationMethod.values()));
    }
    if (randomBoolean()) {
        builder.ignoreUnmapped(randomBoolean());
    }
    builder.type(randomFrom(GeoExecType.values()));
    return builder;
}
Also used : GeoPoint(org.elasticsearch.common.geo.GeoPoint) Rectangle(org.locationtech.spatial4j.shape.Rectangle) LatLonPoint(org.apache.lucene.document.LatLonPoint) GeoPoint(org.elasticsearch.common.geo.GeoPoint)

Example 22 with Rectangle

use of org.locationtech.spatial4j.shape.Rectangle in project elasticsearch by elastic.

the class GeoShapeQueryTests method testContainsShapeQuery.

public void testContainsShapeQuery() throws Exception {
    // Create a random geometry collection.
    Rectangle mbr = xRandomRectangle(random(), xRandomPoint(random()), true);
    GeometryCollectionBuilder gcb = createGeometryCollectionWithin(random(), mbr);
    client().admin().indices().prepareCreate("test").addMapping("type", "location", "type=geo_shape,tree=quadtree").execute().actionGet();
    XContentBuilder docSource = gcb.toXContent(jsonBuilder().startObject().field("location"), null).endObject();
    client().prepareIndex("test", "type", "1").setSource(docSource).setRefreshPolicy(IMMEDIATE).get();
    // index the mbr of the collection
    EnvelopeBuilder env = new EnvelopeBuilder(new Coordinate(mbr.getMinX(), mbr.getMaxY()), new Coordinate(mbr.getMaxX(), mbr.getMinY()));
    docSource = env.toXContent(jsonBuilder().startObject().field("location"), null).endObject();
    client().prepareIndex("test", "type", "2").setSource(docSource).setRefreshPolicy(IMMEDIATE).get();
    ShapeBuilder filterShape = (gcb.getShapeAt(randomIntBetween(0, gcb.numShapes() - 1)));
    GeoShapeQueryBuilder filter = QueryBuilders.geoShapeQuery("location", filterShape).relation(ShapeRelation.CONTAINS);
    SearchResponse response = client().prepareSearch("test").setTypes("type").setQuery(QueryBuilders.matchAllQuery()).setPostFilter(filter).get();
    assertSearchResponse(response);
    assertThat(response.getHits().getTotalHits(), greaterThan(0L));
}
Also used : GeometryCollectionBuilder(org.elasticsearch.common.geo.builders.GeometryCollectionBuilder) ShapeBuilder(org.elasticsearch.common.geo.builders.ShapeBuilder) GeoShapeQueryBuilder(org.elasticsearch.index.query.GeoShapeQueryBuilder) Coordinate(com.vividsolutions.jts.geom.Coordinate) Rectangle(org.locationtech.spatial4j.shape.Rectangle) RandomShapeGenerator.xRandomRectangle(org.elasticsearch.test.geo.RandomShapeGenerator.xRandomRectangle) EnvelopeBuilder(org.elasticsearch.common.geo.builders.EnvelopeBuilder) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) SearchResponse(org.elasticsearch.action.search.SearchResponse) ElasticsearchAssertions.assertSearchResponse(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)

Example 23 with Rectangle

use of org.locationtech.spatial4j.shape.Rectangle in project elasticsearch by elastic.

the class GeoJSONShapeParserTests method testParseEnvelope.

public void testParseEnvelope() throws IOException {
    // test #1: envelope with expected coordinate order (TopLeft, BottomRight)
    XContentBuilder multilinesGeoJson = XContentFactory.jsonBuilder().startObject().field("type", "envelope").startArray("coordinates").startArray().value(-50).value(30).endArray().startArray().value(50).value(-30).endArray().endArray().endObject();
    Rectangle expected = SPATIAL_CONTEXT.makeRectangle(-50, 50, -30, 30);
    assertGeometryEquals(expected, multilinesGeoJson);
    // test #2: envelope with agnostic coordinate order (TopRight, BottomLeft)
    multilinesGeoJson = XContentFactory.jsonBuilder().startObject().field("type", "envelope").startArray("coordinates").startArray().value(50).value(30).endArray().startArray().value(-50).value(-30).endArray().endArray().endObject();
    expected = SPATIAL_CONTEXT.makeRectangle(-50, 50, -30, 30);
    assertGeometryEquals(expected, multilinesGeoJson);
    // test #3: "envelope" (actually a triangle) with invalid number of coordinates (TopRight, BottomLeft, BottomRight)
    multilinesGeoJson = XContentFactory.jsonBuilder().startObject().field("type", "envelope").startArray("coordinates").startArray().value(50).value(30).endArray().startArray().value(-50).value(-30).endArray().startArray().value(50).value(-39).endArray().endArray().endObject();
    XContentParser parser = createParser(multilinesGeoJson);
    parser.nextToken();
    ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class);
    // test #4: "envelope" with empty coordinates
    multilinesGeoJson = XContentFactory.jsonBuilder().startObject().field("type", "envelope").startArray("coordinates").endArray().endObject();
    parser = createParser(multilinesGeoJson);
    parser.nextToken();
    ElasticsearchGeoAssertions.assertValidException(parser, ElasticsearchParseException.class);
}
Also used : Rectangle(org.locationtech.spatial4j.shape.Rectangle) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 24 with Rectangle

use of org.locationtech.spatial4j.shape.Rectangle in project lucene-solr by apache.

the class TestSolr4Spatial method checkHits.

private void checkHits(String fieldName, boolean exact, String ptStr, double distKM, double sphereRadius, int count, int... docIds) throws ParseException {
    if (exact && fieldName.equalsIgnoreCase("bbox")) {
        // bbox field only supports rectangular query
        return;
    }
    String[] tests = new String[docIds != null && docIds.length > 0 ? docIds.length + 1 : 1];
    //test for presence of required ids first
    int i = 0;
    if (docIds != null && docIds.length > 0) {
        for (int docId : docIds) {
            tests[i++] = "//result/doc/*[@name='id'][.='" + docId + "']";
        }
    }
    //check total length last; maybe response includes ids it shouldn't.  Nicer to check this last instead of first so
    // that there may be a more specific detailed id to investigate.
    tests[i++] = "*[count(//doc)=" + count + "]";
    //Test using the Lucene spatial syntax
    {
        //never actually need the score but lets test
        String score = randomScoreMode();
        double distDEG = DistanceUtils.dist2Degrees(distKM, DistanceUtils.EARTH_MEAN_RADIUS_KM);
        Point point = SpatialUtils.parsePoint(ptStr, SpatialContext.GEO);
        String circleStr = "BUFFER(POINT(" + point.getX() + " " + point.getY() + ")," + distDEG + ")";
        String shapeStr;
        if (exact) {
            shapeStr = circleStr;
        } else {
            //bbox
            //the GEO is an assumption
            SpatialContext ctx = SpatialContext.GEO;
            Rectangle bbox = ctx.readShapeFromWkt(circleStr).getBoundingBox();
            shapeStr = "ENVELOPE(" + bbox.getMinX() + ", " + bbox.getMaxX() + ", " + bbox.getMaxY() + ", " + bbox.getMinY() + ")";
        }
        //FYI default distErrPct=0.025 works with the tests in this file
        assertQ(req("fl", "id", "q", "*:*", "rows", "1000", "fq", "{!field f=" + fieldName + (score == null ? "" : " score=" + score) + "}Intersects(" + shapeStr + ")"), tests);
    }
    //Test using geofilt
    {
        assertQ(req("fl", "id", "q", "*:*", "rows", "1000", "fq", "{!" + (exact ? "geofilt" : "bbox") + " sfield=" + fieldName + " pt='" + ptStr + "' d=" + distKM + " sphere_radius=" + sphereRadius + "}"), tests);
    }
}
Also used : SpatialContext(org.locationtech.spatial4j.context.SpatialContext) Rectangle(org.locationtech.spatial4j.shape.Rectangle) Point(org.locationtech.spatial4j.shape.Point) Point(org.locationtech.spatial4j.shape.Point)

Example 25 with Rectangle

use of org.locationtech.spatial4j.shape.Rectangle in project lucene-solr by apache.

the class SpatialStrategy method makeRecipDistanceValueSource.

/**
   * Returns a ValueSource with values ranging from 1 to 0, depending inversely
   * on the distance from {@link #makeDistanceValueSource(org.locationtech.spatial4j.shape.Point,double)}.
   * The formula is {@code c/(d + c)} where 'd' is the distance and 'c' is
   * one tenth the distance to the farthest edge from the center. Thus the
   * scores will be 1 for indexed points at the center of the query shape and as
   * low as ~0.1 at its furthest edges.
   */
public final ValueSource makeRecipDistanceValueSource(Shape queryShape) {
    Rectangle bbox = queryShape.getBoundingBox();
    double diagonalDist = ctx.getDistCalc().distance(ctx.makePoint(bbox.getMinX(), bbox.getMinY()), bbox.getMaxX(), bbox.getMaxY());
    double distToEdge = diagonalDist * 0.5;
    //one tenth
    float c = (float) distToEdge * 0.1f;
    return new ReciprocalFloatFunction(makeDistanceValueSource(queryShape.getCenter(), 1.0), 1f, c, c);
}
Also used : Rectangle(org.locationtech.spatial4j.shape.Rectangle) ReciprocalFloatFunction(org.apache.lucene.queries.function.valuesource.ReciprocalFloatFunction)

Aggregations

Rectangle (org.locationtech.spatial4j.shape.Rectangle)36 Point (org.locationtech.spatial4j.shape.Point)10 Test (org.junit.Test)8 Shape (org.locationtech.spatial4j.shape.Shape)7 ArrayList (java.util.ArrayList)5 Query (org.apache.lucene.search.Query)5 Coordinate (com.vividsolutions.jts.geom.Coordinate)3 FunctionValues (org.apache.lucene.queries.function.FunctionValues)3 BooleanQuery (org.apache.lucene.search.BooleanQuery)3 SpatialArgs (org.apache.lucene.spatial.query.SpatialArgs)3 SpatialOperation (org.apache.lucene.spatial.query.SpatialOperation)3 GeoShape (org.apache.lucene.spatial3d.geom.GeoShape)3 SpatialContext (org.locationtech.spatial4j.context.SpatialContext)3 Map (java.util.Map)2 LeafReader (org.apache.lucene.index.LeafReader)2 NumericDocValues (org.apache.lucene.index.NumericDocValues)2 ConstantScoreQuery (org.apache.lucene.search.ConstantScoreQuery)2 TermQuery (org.apache.lucene.search.TermQuery)2 UnsupportedSpatialOperation (org.apache.lucene.spatial.query.UnsupportedSpatialOperation)2 GeoPoint (org.apache.lucene.spatial3d.geom.GeoPoint)2