org.elasticsearch.common.geo.builders.ShapeBuilder Java Examples

The following examples show how to use org.elasticsearch.common.geo.builders.ShapeBuilder. 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: GeoWKTParser.java    From crate with Apache License 2.0 6 votes vote down vote up
/** throws an exception if the parsed geometry type does not match the expected shape type */
public static ShapeBuilder parseExpectedType(XContentParser parser, final GeoShapeType shapeType,
                                             final GeoShapeFieldMapper shapeMapper)
        throws IOException, ElasticsearchParseException {
    StringReader reader = new StringReader(parser.text());
    try {
        boolean ignoreZValue = (shapeMapper != null && shapeMapper.ignoreZValue().value() == true);
        // setup the tokenizer; configured to read words w/o numbers
        StreamTokenizer tokenizer = new StreamTokenizer(reader);
        tokenizer.resetSyntax();
        tokenizer.wordChars('a', 'z');
        tokenizer.wordChars('A', 'Z');
        tokenizer.wordChars(128 + 32, 255);
        tokenizer.wordChars('0', '9');
        tokenizer.wordChars('-', '-');
        tokenizer.wordChars('+', '+');
        tokenizer.wordChars('.', '.');
        tokenizer.whitespaceChars(0, ' ');
        tokenizer.commentChar('#');
        ShapeBuilder builder = parseGeometry(tokenizer, shapeType, ignoreZValue);
        checkEOF(tokenizer);
        return builder;
    } finally {
        reader.close();
    }
}
 
Example #2
Source File: GeoJsonParser.java    From crate with Apache License 2.0 6 votes vote down vote up
/**
 * Parse the geometries array of a GeometryCollection
 *
 * @param parser Parser that will be read from
 * @return Geometry[] geometries of the GeometryCollection
 * @throws IOException Thrown if an error occurs while reading from the XContentParser
 */
static GeometryCollectionBuilder parseGeometries(XContentParser parser, GeoShapeFieldMapper mapper) throws
    IOException {
    if (parser.currentToken() != XContentParser.Token.START_ARRAY) {
        throw new ElasticsearchParseException("geometries must be an array of geojson objects");
    }

    XContentParser.Token token = parser.nextToken();
    GeometryCollectionBuilder geometryCollection = new GeometryCollectionBuilder();
    while (token != XContentParser.Token.END_ARRAY) {
        ShapeBuilder shapeBuilder = ShapeParser.parse(parser);
        geometryCollection.shape(shapeBuilder);
        token = parser.nextToken();
    }

    return geometryCollection;
}
 
Example #3
Source File: ShapeFetchService.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Fetches the Shape with the given ID in the given type and index.
 *
 * @param getRequest GetRequest containing index, type and id
 * @param path      Name or path of the field in the Shape Document where the Shape itself is located
 * @return Shape with the given ID
 * @throws IOException Can be thrown while parsing the Shape Document and extracting the Shape
 */
public ShapeBuilder fetch(GetRequest getRequest,String path) throws IOException {
    getRequest.preference("_local");
    getRequest.operationThreaded(false);
    GetResponse response = client.get(getRequest).actionGet();
    if (!response.isExists()) {
        throw new IllegalArgumentException("Shape with ID [" + getRequest.id() + "] in type [" + getRequest.type() + "] not found");
    }

    String[] pathElements = Strings.splitStringToArray(path, '.');
    int currentPathSlot = 0;

    XContentParser parser = null;
    try {
        parser = XContentHelper.createParser(response.getSourceAsBytesRef());
        XContentParser.Token currentToken;
        while ((currentToken = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (currentToken == XContentParser.Token.FIELD_NAME) {
                if (pathElements[currentPathSlot].equals(parser.currentName())) {
                    parser.nextToken();
                    if (++currentPathSlot == pathElements.length) {
                        return ShapeBuilder.parse(parser);
                    }
                } else {
                    parser.nextToken();
                    parser.skipChildren();
                }
            }
        }
        throw new IllegalStateException("Shape with name [" + getRequest.id() + "] found but missing " + path + " field");
    } finally {
        if (parser != null) {
            parser.close();
        }
    }
}
 
Example #4
Source File: Maker.java    From elasticsearch-sql with Apache License 2.0 5 votes vote down vote up
private ShapeBuilder getShapeBuilderFromString(String str) throws IOException {
    String json;
    if(str.contains("{")) json  = fixJsonFromElastic(str);
    else json = WktToGeoJsonConverter.toGeoJson(trimApostrophes(str));

    return getShapeBuilderFromJson(json);
}
 
Example #5
Source File: GeoExtensionProcessor.java    From elasticsearch-plugin-geoshape with MIT License 5 votes vote down vote up
private ShapeBuilder<?,?, ?> getShapeBuilderFromObject(Object object) throws IOException{
    XContentBuilder contentBuilder = JsonXContent.contentBuilder().value(object);

    XContentParser parser = JsonXContent.jsonXContent.createParser(
            NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION,
            BytesReference.bytes(contentBuilder).streamInput()
    );

    parser.nextToken();
    return ShapeParser.parse(parser);
}
 
Example #6
Source File: GeoJSONUtils.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public static Shape geoJSONString2Shape(String geoJSON) {
    try {
        XContentParser parser = JsonXContent.jsonXContent.createParser(geoJSON);
        parser.nextToken();
        return ShapeBuilder.parse(parser).build();
    } catch (Throwable t) {
        throw new IllegalArgumentException(String.format(Locale.ENGLISH,
                "Cannot convert GeoJSON \"%s\" to shape", geoJSON), t);
    }
}
 
Example #7
Source File: GeoShapeFieldMapper.java    From crate with Apache License 2.0 5 votes vote down vote up
@Override
public void parse(ParseContext context) throws IOException {
    try {
        Shape shape = context.parseExternalValue(Shape.class);
        if (shape == null) {
            ShapeBuilder shapeBuilder = ShapeParser.parse(context.parser(), this);
            if (shapeBuilder == null) {
                return;
            }
            shape = shapeBuilder.build();
        }
        if (fieldType().pointsOnly() == true) {
            // index configured for pointsOnly
            if (shape instanceof XShapeCollection && XShapeCollection.class.cast(shape).pointsOnly()) {
                // MULTIPOINT data: index each point separately
                List<Shape> shapes = ((XShapeCollection) shape).getShapes();
                for (Shape s : shapes) {
                    indexShape(context, s);
                }
                return;
            } else if (shape instanceof Point == false) {
                throw new MapperParsingException("[{" + fieldType().name() + "}] is configured for points only but a " +
                    ((shape instanceof JtsGeometry) ? ((JtsGeometry)shape).getGeom().getGeometryType() : shape.getClass()) + " was found");
            }
        }
        indexShape(context, shape);
    } catch (Exception e) {
        if (ignoreMalformed.value() == false) {
            throw new MapperParsingException("failed to parse field [{}] of type [{}]", e, fieldType().name(),
                    fieldType().typeName());
        }
        context.addIgnoredField(fieldType.name());
    }
}
 
Example #8
Source File: T_IEsQueryDao.java    From AsuraFramework with Apache License 2.0 5 votes vote down vote up
@org.junit.Test
public void t_queryByEsQueryDo2()throws Exception {
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    QueryBuilder qb = QueryBuilders.matchAllQuery();
    searchSourceBuilder.query(qb);
    ShapeBuilder shapeBuilder = ShapeBuilder.newPoint(new Coordinate(116.402257, 39.914548));
    QueryBuilder qb2 = QueryBuilders.geoShapeQuery("geometry", shapeBuilder, ShapeRelation.CONTAINS);

    QueryBuilder qb3 = QueryBuilders.boolQuery().must(qb).filter(qb2);
    searchSourceBuilder.query(qb3);
   iEsQueryDao.query(searchSourceBuilder,"twitter","user","user2");
    /*logger.info(JSON.toJSONString(es));
    Assert.assertNotEquals("1", es.getStatus());*/
}
 
Example #9
Source File: GeoShapeFieldMapper.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public Mapper parse(ParseContext context) throws IOException {
    try {
        Shape shape = context.parseExternalValue(Shape.class);
        if (shape == null) {
            ShapeBuilder shapeBuilder = ShapeBuilder.parse(context.parser(), this);
            if (shapeBuilder == null) {
                return null;
            }
            shape = shapeBuilder.build();
        }
        if (fieldType().pointsOnly() && !(shape instanceof Point)) {
            throw new MapperParsingException("[{" + fieldType().names().fullName() + "}] is configured for points only but a " +
                    ((shape instanceof JtsGeometry) ? ((JtsGeometry)shape).getGeom().getGeometryType() : shape.getClass()) + " was found");
        }
        Field[] fields = fieldType().defaultStrategy().createIndexableFields(shape);
        if (fields == null || fields.length == 0) {
            return null;
        }
        for (Field field : fields) {
            if (!customBoost()) {
                field.setBoost(fieldType().boost());
            }
            context.doc().add(field);
        }
    } catch (Exception e) {
        throw new MapperParsingException("failed to parse [" + fieldType().names().fullName() + "]", e);
    }
    return null;
}
 
Example #10
Source File: GeoShapeFieldMapper.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
    Builder builder = geoShapeField(name);
    for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) {
        Map.Entry<String, Object> entry = iterator.next();
        String fieldName = Strings.toUnderscoreCase(entry.getKey());
        Object fieldNode = entry.getValue();
        if (Names.TREE.equals(fieldName)) {
            builder.fieldType().setTree(fieldNode.toString());
            iterator.remove();
        } else if (Names.TREE_LEVELS.equals(fieldName)) {
            builder.fieldType().setTreeLevels(Integer.parseInt(fieldNode.toString()));
            iterator.remove();
        } else if (Names.TREE_PRESISION.equals(fieldName)) {
            builder.fieldType().setPrecisionInMeters(DistanceUnit.parse(fieldNode.toString(), DistanceUnit.DEFAULT, DistanceUnit.DEFAULT));
            iterator.remove();
        } else if (Names.DISTANCE_ERROR_PCT.equals(fieldName)) {
            builder.fieldType().setDistanceErrorPct(Double.parseDouble(fieldNode.toString()));
            iterator.remove();
        } else if (Names.ORIENTATION.equals(fieldName)) {
            builder.fieldType().setOrientation(ShapeBuilder.orientationFromString(fieldNode.toString()));
            iterator.remove();
        } else if (Names.STRATEGY.equals(fieldName)) {
            builder.fieldType().setStrategyName(fieldNode.toString());
            iterator.remove();
        } else if (Names.COERCE.equals(fieldName)) {
            builder.coerce(nodeBooleanValue(fieldNode));
            iterator.remove();
        } else if (Names.STRATEGY_POINTS_ONLY.equals(fieldName)
            && builder.fieldType().strategyName.equals(SpatialStrategy.TERM.getStrategyName()) == false) {
            builder.fieldType().setPointsOnly(XContentMapValues.nodeBooleanValue(fieldNode));
            iterator.remove();
        }
    }
    return builder;
}
 
Example #11
Source File: GeoShapeQueryParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public static SpatialArgs getArgs(ShapeBuilder shape, ShapeRelation relation) {
    switch(relation) {
    case DISJOINT:
        return new SpatialArgs(SpatialOperation.IsDisjointTo, shape.build());
    case INTERSECTS:
        return new SpatialArgs(SpatialOperation.Intersects, shape.build());
    case WITHIN:
        return new SpatialArgs(SpatialOperation.IsWithin, shape.build());
    case CONTAINS:
        return new SpatialArgs(SpatialOperation.Contains, shape.build());
    default:
        throw new IllegalArgumentException("");

    }
}
 
Example #12
Source File: ShapeParser.java    From crate with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link ShapeBuilder} from {@link XContent}
 * @param parser parser to read the GeoShape from
 * @param shapeMapper document field mapper reference required for spatial parameters relevant
 *                     to the shape construction process (e.g., orientation)
 *                     todo: refactor to place build specific parameters in the SpatialContext
 * @return {@link ShapeBuilder} read from the parser or null
 *          if the parsers current token has been <code>null</code>
 * @throws IOException if the input could not be read
 */
static ShapeBuilder parse(XContentParser parser, GeoShapeFieldMapper shapeMapper) throws IOException {
    if (parser.currentToken() == XContentParser.Token.VALUE_NULL) {
        return null;
    }
    if (parser.currentToken() == XContentParser.Token.START_OBJECT) {
        return GeoJsonParser.parse(parser, shapeMapper);
    } else if (parser.currentToken() == XContentParser.Token.VALUE_STRING) {
        return GeoWKTParser.parse(parser, shapeMapper);
    }
    throw new ElasticsearchParseException("shape must be an object consisting of type and coordinates");
}
 
Example #13
Source File: GeoShapeQueryBuilder.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private GeoShapeQueryBuilder(String name, ShapeBuilder shape, String indexedShapeId, String indexedShapeType, ShapeRelation relation) {
    this.name = name;
    this.shape = shape;
    this.indexedShapeId = indexedShapeId;
    this.relation = relation;
    this.indexedShapeType = indexedShapeType;
}
 
Example #14
Source File: GeoWKTParser.java    From crate with Apache License 2.0 5 votes vote down vote up
/** parse geometry from the stream tokenizer */
private static ShapeBuilder parseGeometry(StreamTokenizer stream, GeoShapeType shapeType, final boolean ignoreZValue)
        throws IOException, ElasticsearchParseException {
    final GeoShapeType type = GeoShapeType.forName(nextWord(stream));
    if (shapeType != null && shapeType != GeoShapeType.GEOMETRYCOLLECTION) {
        if (type.wktName().equals(shapeType.wktName()) == false) {
            throw new ElasticsearchParseException("Expected geometry type [{}] but found [{}]", shapeType, type);
        }
    }
    switch (type) {
        case POINT:
            return parsePoint(stream, ignoreZValue);
        case MULTIPOINT:
            return parseMultiPoint(stream, ignoreZValue);
        case LINESTRING:
            return parseLine(stream, ignoreZValue);
        case MULTILINESTRING:
            return parseMultiLine(stream, ignoreZValue);
        case POLYGON:
            return parsePolygon(stream, ignoreZValue);
        case MULTIPOLYGON:
            return parseMultiPolygon(stream, ignoreZValue);
        case ENVELOPE:
            return parseBBox(stream);
        case GEOMETRYCOLLECTION:
            return parseGeometryCollection(stream, ignoreZValue);
        default:
            throw new IllegalArgumentException("Unknown geometry type: " + type);
    }
}
 
Example #15
Source File: GeoWKTParser.java    From crate with Apache License 2.0 5 votes vote down vote up
private static PolygonBuilder parsePolygon(StreamTokenizer stream, final boolean ignoreZValue)
        throws IOException, ElasticsearchParseException {
    if (nextEmptyOrOpen(stream).equals(EMPTY)) {
        return null;
    }
    PolygonBuilder builder = new PolygonBuilder(parseLine(stream, ignoreZValue), ShapeBuilder.Orientation.RIGHT);
    while (nextCloserOrComma(stream).equals(COMMA)) {
        builder.hole(parseLine(stream, ignoreZValue));
    }
    return builder;
}
 
Example #16
Source File: ElasticsearchSpatialSupport.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@Override
protected ShapeBuilder toShapeBuilder(Shape s) {
	throw new UnsupportedOperationException(
			"This shape is not supported due to licensing issues. Feel free to provide your own implementation by using something like JTS: "
					+ s.getClass().getName());
}
 
Example #17
Source File: GeoWKTParser.java    From crate with Apache License 2.0 4 votes vote down vote up
public static ShapeBuilder parse(XContentParser parser, final GeoShapeFieldMapper shapeMapper)
        throws IOException, ElasticsearchParseException {
    return parseExpectedType(parser, null, shapeMapper);
}
 
Example #18
Source File: GeoJsonParser.java    From crate with Apache License 2.0 4 votes vote down vote up
protected static ShapeBuilder parse(XContentParser parser, GeoShapeFieldMapper shapeMapper)
    throws IOException {
    GeoShapeType shapeType = null;
    DistanceUnit.Distance radius = null;
    CoordinateNode coordinateNode = null;
    GeometryCollectionBuilder geometryCollections = null;

    ShapeBuilder.Orientation requestedOrientation =
        (shapeMapper == null) ? ShapeBuilder.Orientation.RIGHT : shapeMapper.fieldType().orientation();
    final Explicit<Boolean> coerce = (shapeMapper == null) ? GeoShapeFieldMapper.Defaults.COERCE : shapeMapper.coerce();
    final Explicit<Boolean> ignoreZValue = (shapeMapper == null) ? GeoShapeFieldMapper.Defaults.IGNORE_Z_VALUE : shapeMapper.ignoreZValue();

    String malformedException = null;

    XContentParser.Token token;
    try {
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                String fieldName = parser.currentName();

                if (ShapeParser.FIELD_TYPE.match(fieldName, parser.getDeprecationHandler())) {
                    parser.nextToken();
                    final GeoShapeType type = GeoShapeType.forName(parser.text());
                    if (shapeType != null && shapeType.equals(type) == false) {
                        malformedException = ShapeParser.FIELD_TYPE + " already parsed as ["
                            + shapeType + "] cannot redefine as [" + type + "]";
                    } else {
                        shapeType = type;
                    }
                } else if (ShapeParser.FIELD_COORDINATES.match(fieldName, parser.getDeprecationHandler())) {
                    parser.nextToken();
                    CoordinateNode tempNode = parseCoordinates(parser, ignoreZValue.value());
                    if (coordinateNode != null && tempNode.numDimensions() != coordinateNode.numDimensions()) {
                        throw new ElasticsearchParseException("Exception parsing coordinates: " +
                            "number of dimensions do not match");
                    }
                    coordinateNode = tempNode;
                } else if (ShapeParser.FIELD_GEOMETRIES.match(fieldName, parser.getDeprecationHandler())) {
                    if (shapeType == null) {
                        shapeType = GeoShapeType.GEOMETRYCOLLECTION;
                    } else if (shapeType.equals(GeoShapeType.GEOMETRYCOLLECTION) == false) {
                        malformedException = "cannot have [" + ShapeParser.FIELD_GEOMETRIES + "] with type set to ["
                            + shapeType + "]";
                    }
                    parser.nextToken();
                    geometryCollections = parseGeometries(parser, shapeMapper);
                } else if (CircleBuilder.FIELD_RADIUS.match(fieldName, parser.getDeprecationHandler())) {
                    if (shapeType == null) {
                        shapeType = GeoShapeType.CIRCLE;
                    } else if (shapeType.equals(GeoShapeType.CIRCLE) == false) {
                        malformedException = "cannot have [" + CircleBuilder.FIELD_RADIUS + "] with type set to ["
                            + shapeType + "]";
                    }
                    parser.nextToken();
                    radius = DistanceUnit.Distance.parseDistance(parser.text());
                } else if (ShapeParser.FIELD_ORIENTATION.match(fieldName, parser.getDeprecationHandler())) {
                    if (shapeType != null
                        && (shapeType.equals(GeoShapeType.POLYGON) || shapeType.equals(GeoShapeType.MULTIPOLYGON)) == false) {
                        malformedException = "cannot have [" + ShapeParser.FIELD_ORIENTATION + "] with type set to [" + shapeType + "]";
                    }
                    parser.nextToken();
                    requestedOrientation = ShapeBuilder.Orientation.fromString(parser.text());
                } else {
                    parser.nextToken();
                    parser.skipChildren();
                }
            }
        }
    } catch (Exception ex) {
        // Skip all other fields until the end of the object
        while (parser.currentToken() != XContentParser.Token.END_OBJECT && parser.currentToken() != null) {
            parser.nextToken();
            parser.skipChildren();
        }
        throw ex;
    }

    if (malformedException != null) {
        throw new ElasticsearchParseException(malformedException);
    } else if (shapeType == null) {
        throw new ElasticsearchParseException("shape type not included");
    } else if (coordinateNode == null && GeoShapeType.GEOMETRYCOLLECTION != shapeType) {
        throw new ElasticsearchParseException("coordinates not included");
    } else if (geometryCollections == null && GeoShapeType.GEOMETRYCOLLECTION == shapeType) {
        throw new ElasticsearchParseException("geometries not included");
    } else if (radius != null && GeoShapeType.CIRCLE != shapeType) {
        throw new ElasticsearchParseException("field [{}] is supported for [{}] only", CircleBuilder.FIELD_RADIUS,
            CircleBuilder.TYPE);
    }

    if (shapeType.equals(GeoShapeType.GEOMETRYCOLLECTION)) {
        return geometryCollections;
    }

    return shapeType.getBuilder(coordinateNode, radius, requestedOrientation, coerce.value());
}
 
Example #19
Source File: GeoWKTParser.java    From crate with Apache License 2.0 4 votes vote down vote up
public static ShapeBuilder parseExpectedType(XContentParser parser, final GeoShapeType shapeType)
        throws IOException, ElasticsearchParseException {
    return parseExpectedType(parser, shapeType, null);
}
 
Example #20
Source File: GeoShapeFieldMapper.java    From crate with Apache License 2.0 4 votes vote down vote up
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
    Builder builder = new Builder(name);
    Boolean pointsOnly = null;
    for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) {
        Map.Entry<String, Object> entry = iterator.next();
        String fieldName = entry.getKey();
        Object fieldNode = entry.getValue();
        if (Names.TREE.equals(fieldName)) {
            builder.fieldType().setTree(fieldNode.toString());
            iterator.remove();
        } else if (Names.TREE_LEVELS.equals(fieldName)) {
            builder.fieldType().setTreeLevels(Integer.parseInt(fieldNode.toString()));
            iterator.remove();
        } else if (Names.TREE_PRESISION.equals(fieldName)) {
            builder.fieldType().setPrecisionInMeters(DistanceUnit.parse(fieldNode.toString(), DistanceUnit.DEFAULT, DistanceUnit.DEFAULT));
            iterator.remove();
        } else if (Names.DISTANCE_ERROR_PCT.equals(fieldName)) {
            builder.fieldType().setDistanceErrorPct(Double.parseDouble(fieldNode.toString()));
            iterator.remove();
        } else if (Names.ORIENTATION.equals(fieldName)) {
            builder.fieldType().setOrientation(ShapeBuilder.Orientation.fromString(fieldNode.toString()));
            iterator.remove();
        } else if (Names.STRATEGY.equals(fieldName)) {
            builder.fieldType().setStrategyName(fieldNode.toString());
            iterator.remove();
        } else if (IGNORE_MALFORMED.equals(fieldName)) {
            builder.ignoreMalformed(nodeBooleanValue(fieldNode, fieldName + ".ignore_malformed"));
            iterator.remove();
        } else if (Names.COERCE.equals(fieldName)) {
            builder.coerce(nodeBooleanValue(fieldNode, fieldName + '.' + Names.COERCE));
            iterator.remove();
        } else if (GeoPointFieldMapper.Names.IGNORE_Z_VALUE.getPreferredName().equals(fieldName)) {
            builder.ignoreZValue(
                nodeBooleanValue(fieldNode, fieldName + '.' + GeoPointFieldMapper.Names.IGNORE_Z_VALUE.getPreferredName()));
            iterator.remove();
        } else if (Names.STRATEGY_POINTS_ONLY.equals(fieldName)) {
            pointsOnly = nodeBooleanValue(fieldNode, fieldName + '.' + Names.STRATEGY_POINTS_ONLY);
            iterator.remove();
        } else if ("position".equals(fieldName)) {
            builder.position(nodeIntegerValue(fieldNode));
            iterator.remove();
        }
    }
    if (pointsOnly != null) {
        if (builder.fieldType().strategyName.equals(SpatialStrategy.TERM.getStrategyName()) && pointsOnly == false) {
            throw new IllegalArgumentException("points_only cannot be set to false for term strategy");
        } else {
            builder.fieldType().setPointsOnly(pointsOnly);
        }
    }
    return builder;
}
 
Example #21
Source File: Maker.java    From elasticsearch-sql with Apache License 2.0 4 votes vote down vote up
private ShapeBuilder getShapeBuilderFromJson(String json) throws IOException {
    try (XContentParser parser = JsonXContent.jsonXContent.createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, json)) {
        parser.nextToken();
        return ShapeParser.parse(parser);
    }
}
 
Example #22
Source File: GeoExtensionProcessor.java    From elasticsearch-plugin-geoshape with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public IngestDocument execute(IngestDocument ingestDocument) throws IOException, ParseException {
    List<String> geo_objects_list = getGeoShapeFieldsFromDoc(ingestDocument);
    for (String geoShapeField : geo_objects_list) {

        Object geoShapeObject = ingestDocument.getFieldValue(geoShapeField, Object.class);

        if (geoShapeObject == null) {
            continue;
        }

        ShapeBuilder<?,?, ?> shapeBuilder = getShapeBuilderFromObject(geoShapeObject);

        Shape shape = null;
        try {
            shape = shapeBuilder.buildS4J();
        }
        catch (InvalidShapeException ignored) {}

        if (shape == null && fixedField == null) {
            throw new IllegalArgumentException("unable to parse shape [" + shapeBuilder.toWKT() + "]");
        }

        Geometry geom = new WKTReader().read(shapeBuilder.toWKT());

        // fix shapes if needed
        if (shape == null && fixedField != null) {
            geom = GeoUtils.removeDuplicateCoordinates(geom);
        }

        ingestDocument.removeField(geoShapeField);

        if (keepShape) {
            ingestDocument.setFieldValue(geoShapeField + "." + shapeField, geoShapeObject);
        }

        if (fixedField != null) {
            ingestDocument.setFieldValue(geoShapeField + "." + fixedField, new WKTWriter().write(geom));
        }

        // compute and add extra geo sub-fields
        byte[] wkb = new WKBWriter().write(geom);  // elastic will auto-encode this as b64

        if (hashField != null) ingestDocument.setFieldValue(
                geoShapeField + ".hash", String.valueOf(GeoUtils.getHashFromWKB(new BytesRef(wkb))));
        if (wkbField != null) ingestDocument.setFieldValue(
                geoShapeField + "." + wkbField, wkb);
        if (typeField != null) ingestDocument.setFieldValue(
                geoShapeField + "." + typeField, geom.getGeometryType());
        if (areaField != null) ingestDocument.setFieldValue(
                geoShapeField + "." + areaField, geom.getArea());
        if (centroidField != null) ingestDocument.setFieldValue(
                geoShapeField + "." + centroidField, GeoUtils.getCentroidFromGeom(geom));
        if (bboxField != null) {
            Coordinate[] coords = geom.getEnvelope().getCoordinates();
            if (coords.length >= 4) ingestDocument.setFieldValue(
                    geoShapeField + "." + bboxField,
                    GeoUtils.getBboxFromCoords(coords));
        }
    }
    return ingestDocument;
}
 
Example #23
Source File: Test.java    From AsuraFramework with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
   /* QueryBuilder qb1 = QueryBuilders.matchQuery("a","b");
    System.out.println(qb1.toString());*/
    String json="{\"query\":{\"match_all\":{}},\"filter\":{\"geo_shape\":{\"geometry\":{\"relation\":\"CONTAINS\",\"shape\":{\"coordinates\":[116.402257,39.914548],\"type\":\"point\"}}}}}";
    QueryBuilder qb= QueryBuilders.matchAllQuery();
    //System.out.println(qb.toString());
    SearchSourceBuilder searchSourceBuilder=new SearchSourceBuilder();
    searchSourceBuilder.query(qb);
   // System.out.println(searchSourceBuilder.toString());
    ShapeBuilder shapeBuilder= ShapeBuilder.newPoint(new Coordinate(116.402257,39.914548));
    QueryBuilder qb2= QueryBuilders.geoShapeQuery("geometry",shapeBuilder, ShapeRelation.CONTAINS);
    System.out.println(qb2.toString());

    //searchSourceBuilder.postFilter(qb2);
    QueryBuilder qb3= QueryBuilders.boolQuery().must(qb).filter(qb2);
    searchSourceBuilder.query(qb3);
    System.out.println(qb3.toString());
    System.out.println(searchSourceBuilder.toString());
    QueryBuilder qb4= QueryBuilders.boolQuery().must(qb).must(qb2);
    System.out.println(qb4.toString());


    SortBuilder sort= SortBuilders.geoDistanceSort("pin.location") .point(40, -70).
            unit(DistanceUnit.fromString(DistanceUnit.KILOMETERS.toString())).order(SortOrder.DESC);
  /*  QueryBuilder qb5 = QueryBuilders.geoDistanceQuery("pin.location")
            .point(40, -70)
            .distance(400,  DistanceUnit.fromString(DistanceUnit.KILOMETERS.toString()))
            .geoDistance(GeoDistance.ARC);
             System.out.println(qb5.toString());
            */
    searchSourceBuilder.sort(sort);
    System.out.println(searchSourceBuilder.toString());
    //QueryBuilder qb3=QueryBuilders.filteredQuery(null,qb2);
    //QueryBuilder qb4=QueryBuilders.filteredQuery(qb,qb2);
    //searchSourceBuilder.query(qb3.toString());
   // searchSourceBuilder.query(qb4);
   // System.out.println(qb4.toString());
    //System.out.println(searchSourceBuilder.toString());

    // System.out.println(qb.toString());
   /* QueryBuilder qb2 = QueryBuilders.geoBoundingBoxQuery("pin.location")
            .topLeft(40.73, -74.1)
            .bottomRight(40.717, -73.99);
    //String  strstr= JSON.toJSONString(qb2);
    System.out.println(qb2.toString());
    System.out.println("1111111");*/
}
 
Example #24
Source File: QueryBuilders.java    From Elasticsearch with Apache License 2.0 2 votes vote down vote up
/**
 * A filter to filter indexed shapes that are not intersection with the query shape
 *
 * @param name  The shape field name
 * @param shape Shape to use in the filter
 */
public static GeoShapeQueryBuilder geoDisjointQuery(String name, ShapeBuilder shape) {
    return geoShapeQuery(name, shape, ShapeRelation.DISJOINT);
}
 
Example #25
Source File: QueryBuilders.java    From Elasticsearch with Apache License 2.0 2 votes vote down vote up
/**
 * A filter to filter indexed shapes that are contained by a shape
 *
 * @param name  The shape field name
 * @param shape Shape to use in the filter
 */
public static GeoShapeQueryBuilder geoWithinQuery(String name, ShapeBuilder shape) {
    return geoShapeQuery(name, shape, ShapeRelation.WITHIN);
}
 
Example #26
Source File: ShapeParser.java    From crate with Apache License 2.0 2 votes vote down vote up
/**
 * Create a new {@link ShapeBuilder} from {@link XContent}
 * @param parser parser to read the GeoShape from
 * @return {@link ShapeBuilder} read from the parser or null
 *          if the parsers current token has been <code>null</code>
 * @throws IOException if the input could not be read
 */
static ShapeBuilder parse(XContentParser parser) throws IOException {
    return parse(parser, null);
}
 
Example #27
Source File: QueryBuilders.java    From Elasticsearch with Apache License 2.0 2 votes vote down vote up
/**
 * A filter to filter indexed shapes intersecting with shapes
 *
 * @param name  The shape field name
 * @param shape Shape to use in the filter
 */
public static GeoShapeQueryBuilder geoIntersectionQuery(String name, ShapeBuilder shape) {
    return geoShapeQuery(name, shape, ShapeRelation.INTERSECTS);
}
 
Example #28
Source File: QueryBuilders.java    From Elasticsearch with Apache License 2.0 2 votes vote down vote up
/**
 * A filter based on the relationship of a shape and indexed shapes
 *
 * @param name  The shape field name
 * @param shape Shape to use in the filter
 * @param relation relation of the shapes
 */
public static GeoShapeQueryBuilder geoShapeQuery(String name, ShapeBuilder shape, ShapeRelation relation) {
    return new GeoShapeQueryBuilder(name, shape, relation);
}
 
Example #29
Source File: QueryBuilders.java    From Elasticsearch with Apache License 2.0 2 votes vote down vote up
/**
 * Query that matches Documents based on the relationship between the given shape and
 * indexed shapes
 *
 * @param name  The shape field name
 * @param shape Shape to use in the Query
 */
public static GeoShapeQueryBuilder geoShapeQuery(String name, ShapeBuilder shape) {
    return new GeoShapeQueryBuilder(name, shape);
}
 
Example #30
Source File: GeoShapeQueryBuilder.java    From Elasticsearch with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a new GeoShapeQueryBuilder whose Filter will be against the
 * given field name using the given Shape
 *
 * @param name  Name of the field that will be filtered
 * @param relation {@link ShapeRelation} of query and indexed shape
 * @param shape Shape used in the filter
 */
public GeoShapeQueryBuilder(String name, ShapeBuilder shape, ShapeRelation relation) {
    this(name, shape, null, null, relation);
}