Search in sources :

Example 1 with ShapeRelation

use of org.elasticsearch.common.geo.ShapeRelation in project elasticsearch by elastic.

the class GeoShapeQueryBuilder method fromXContent.

public static GeoShapeQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
    XContentParser parser = parseContext.parser();
    String fieldName = null;
    ShapeRelation shapeRelation = null;
    SpatialStrategy strategy = null;
    ShapeBuilder shape = null;
    String id = null;
    String type = null;
    String index = null;
    String shapePath = null;
    XContentParser.Token token;
    String currentFieldName = null;
    float boost = AbstractQueryBuilder.DEFAULT_BOOST;
    String queryName = null;
    boolean ignoreUnmapped = DEFAULT_IGNORE_UNMAPPED;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token == XContentParser.Token.START_OBJECT) {
            if (fieldName != null) {
                throw new ParsingException(parser.getTokenLocation(), "[" + GeoShapeQueryBuilder.NAME + "] point specified twice. [" + currentFieldName + "]");
            }
            fieldName = currentFieldName;
            while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                if (token == XContentParser.Token.FIELD_NAME) {
                    currentFieldName = parser.currentName();
                    token = parser.nextToken();
                    if (SHAPE_FIELD.match(currentFieldName)) {
                        shape = ShapeBuilder.parse(parser);
                    } else if (STRATEGY_FIELD.match(currentFieldName)) {
                        String strategyName = parser.text();
                        strategy = SpatialStrategy.fromString(strategyName);
                        if (strategy == null) {
                            throw new ParsingException(parser.getTokenLocation(), "Unknown strategy [" + strategyName + " ]");
                        }
                    } else if (RELATION_FIELD.match(currentFieldName)) {
                        shapeRelation = ShapeRelation.getRelationByName(parser.text());
                        if (shapeRelation == null) {
                            throw new ParsingException(parser.getTokenLocation(), "Unknown shape operation [" + parser.text() + " ]");
                        }
                    } else if (INDEXED_SHAPE_FIELD.match(currentFieldName)) {
                        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                            if (token == XContentParser.Token.FIELD_NAME) {
                                currentFieldName = parser.currentName();
                            } else if (token.isValue()) {
                                if (SHAPE_ID_FIELD.match(currentFieldName)) {
                                    id = parser.text();
                                } else if (SHAPE_TYPE_FIELD.match(currentFieldName)) {
                                    type = parser.text();
                                } else if (SHAPE_INDEX_FIELD.match(currentFieldName)) {
                                    index = parser.text();
                                } else if (SHAPE_PATH_FIELD.match(currentFieldName)) {
                                    shapePath = parser.text();
                                }
                            } else {
                                throw new ParsingException(parser.getTokenLocation(), "[" + GeoShapeQueryBuilder.NAME + "] unknown token [" + token + "] after [" + currentFieldName + "]");
                            }
                        }
                    } else {
                        throw new ParsingException(parser.getTokenLocation(), "[" + GeoShapeQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]");
                    }
                }
            }
        } else if (token.isValue()) {
            if (AbstractQueryBuilder.BOOST_FIELD.match(currentFieldName)) {
                boost = parser.floatValue();
            } else if (AbstractQueryBuilder.NAME_FIELD.match(currentFieldName)) {
                queryName = parser.text();
            } else if (IGNORE_UNMAPPED_FIELD.match(currentFieldName)) {
                ignoreUnmapped = parser.booleanValue();
            } else {
                throw new ParsingException(parser.getTokenLocation(), "[" + GeoShapeQueryBuilder.NAME + "] query does not support [" + currentFieldName + "]");
            }
        }
    }
    GeoShapeQueryBuilder builder;
    if (shape != null) {
        builder = new GeoShapeQueryBuilder(fieldName, shape);
    } else {
        builder = new GeoShapeQueryBuilder(fieldName, id, type);
    }
    if (index != null) {
        builder.indexedShapeIndex(index);
    }
    if (shapePath != null) {
        builder.indexedShapePath(shapePath);
    }
    if (shapeRelation != null) {
        builder.relation(shapeRelation);
    }
    if (strategy != null) {
        builder.strategy(strategy);
    }
    if (queryName != null) {
        builder.queryName(queryName);
    }
    builder.boost(boost);
    builder.ignoreUnmapped(ignoreUnmapped);
    return builder;
}
Also used : ShapeRelation(org.elasticsearch.common.geo.ShapeRelation) ShapeBuilder(org.elasticsearch.common.geo.builders.ShapeBuilder) ParsingException(org.elasticsearch.common.ParsingException) SpatialStrategy(org.elasticsearch.common.geo.SpatialStrategy) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 2 with ShapeRelation

use of org.elasticsearch.common.geo.ShapeRelation in project elasticsearch by elastic.

the class RangeFieldTypeTests method testRangeQuery.

public void testRangeQuery() throws Exception {
    Settings indexSettings = Settings.builder().put(IndexMetaData.SETTING_VERSION_CREATED, Version.CURRENT).build();
    IndexSettings idxSettings = IndexSettingsModule.newIndexSettings(randomAsciiOfLengthBetween(1, 10), indexSettings);
    QueryShardContext context = new QueryShardContext(0, idxSettings, null, null, null, null, null, xContentRegistry(), null, null, () -> nowInMillis);
    RangeFieldMapper.RangeFieldType ft = new RangeFieldMapper.RangeFieldType(type);
    ft.setName(FIELDNAME);
    ft.setIndexOptions(IndexOptions.DOCS);
    ShapeRelation relation = RandomPicks.randomFrom(random(), ShapeRelation.values());
    boolean includeLower = random().nextBoolean();
    boolean includeUpper = random().nextBoolean();
    Object from = nextFrom();
    Object to = nextTo(from);
    assertEquals(getExpectedRangeQuery(relation, from, to, includeLower, includeUpper), ft.rangeQuery(from, to, includeLower, includeUpper, relation, context));
}
Also used : ShapeRelation(org.elasticsearch.common.geo.ShapeRelation) IndexSettings(org.elasticsearch.index.IndexSettings) QueryShardContext(org.elasticsearch.index.query.QueryShardContext) Settings(org.elasticsearch.common.settings.Settings) IndexSettings(org.elasticsearch.index.IndexSettings)

Example 3 with ShapeRelation

use of org.elasticsearch.common.geo.ShapeRelation in project crate by crate.

the class MatchPredicate method geoMatch.

private Query geoMatch(LuceneQueryBuilder.Context context, List<Symbol> arguments, Object queryTerm) {
    Map fields = (Map) ((Literal) arguments.get(0)).value();
    String fieldName = (String) fields.keySet().iterator().next();
    MappedFieldType fieldType = context.queryShardContext().getMapperService().fullName(fieldName);
    GeoShapeFieldMapper.GeoShapeFieldType geoShapeFieldType = (GeoShapeFieldMapper.GeoShapeFieldType) fieldType;
    String matchType = (String) ((Input) arguments.get(2)).value();
    @SuppressWarnings("unchecked") Shape shape = GeoJSONUtils.map2Shape((Map<String, Object>) queryTerm);
    ShapeRelation relation = ShapeRelation.getRelationByName(matchType);
    assert relation != null : "invalid matchType: " + matchType;
    PrefixTreeStrategy prefixTreeStrategy = geoShapeFieldType.defaultStrategy();
    if (relation == ShapeRelation.DISJOINT) {
        /**
         * See {@link org.elasticsearch.index.query.GeoShapeQueryParser}:
         */
        // this strategy doesn't support disjoint anymore: but it did before, including creating lucene fieldcache (!)
        // in this case, execute disjoint as exists && !intersects
        BooleanQuery.Builder bool = new BooleanQuery.Builder();
        Query exists = new TermRangeQuery(fieldName, null, null, true, true);
        Query intersects = prefixTreeStrategy.makeQuery(getArgs(shape, ShapeRelation.INTERSECTS));
        bool.add(exists, BooleanClause.Occur.MUST);
        bool.add(intersects, BooleanClause.Occur.MUST_NOT);
        return new ConstantScoreQuery(bool.build());
    }
    SpatialArgs spatialArgs = getArgs(shape, relation);
    return prefixTreeStrategy.makeQuery(spatialArgs);
}
Also used : ShapeRelation(org.elasticsearch.common.geo.ShapeRelation) BooleanQuery(org.apache.lucene.search.BooleanQuery) SpatialArgs(org.apache.lucene.spatial.query.SpatialArgs) Shape(org.locationtech.spatial4j.shape.Shape) Query(org.apache.lucene.search.Query) ConstantScoreQuery(org.apache.lucene.search.ConstantScoreQuery) FunctionToQuery(io.crate.lucene.FunctionToQuery) BooleanQuery(org.apache.lucene.search.BooleanQuery) BoostQuery(org.apache.lucene.search.BoostQuery) TermRangeQuery(org.apache.lucene.search.TermRangeQuery) LuceneQueryBuilder(io.crate.lucene.LuceneQueryBuilder) TermRangeQuery(org.apache.lucene.search.TermRangeQuery) GeoShapeFieldMapper(org.elasticsearch.index.mapper.GeoShapeFieldMapper) MappedFieldType(org.elasticsearch.index.mapper.MappedFieldType) ConstantScoreQuery(org.apache.lucene.search.ConstantScoreQuery) Map(java.util.Map) PrefixTreeStrategy(org.apache.lucene.spatial.prefix.PrefixTreeStrategy)

Example 4 with ShapeRelation

use of org.elasticsearch.common.geo.ShapeRelation in project vertexium by visallo.

the class ElasticsearchSearchQueryBase method getFilterForGeoComparePredicate.

protected QueryBuilder getFilterForGeoComparePredicate(GeoCompare compare, HasValueContainer has) {
    PropertyDefinition[] propertyDefinitions = StreamSupport.stream(has.getKeys().spliterator(), false).map(this::getPropertyDefinition).filter(Objects::nonNull).toArray(PropertyDefinition[]::new);
    if (propertyDefinitions.length == 0) {
        // If we didn't find any property definitions, this means none of them are defined on the graph
        throw new VertexiumNoMatchingPropertiesException(Joiner.on(", ").join(has.getKeys()));
    }
    if (!(has.value instanceof GeoShape)) {
        throw new VertexiumNotSupportedException("GeoCompare searches only accept values of type GeoShape");
    }
    GeoShape value = (GeoShape) has.value;
    if (value instanceof GeoHash) {
        value = ((GeoHash) value).toGeoRect();
    }
    List<QueryBuilder> filters = new ArrayList<>();
    for (PropertyDefinition propertyDefinition : propertyDefinitions) {
        if (propertyDefinition != null && !GeoShape.class.isAssignableFrom(propertyDefinition.getDataType())) {
            throw new VertexiumNotSupportedException("Unable to perform geo query on field of type: " + propertyDefinition.getDataType().getName());
        }
        String[] propertyNames = Arrays.stream(getPropertyNames(propertyDefinition.getPropertyName())).map(propertyName -> propertyName + Elasticsearch5SearchIndex.GEO_PROPERTY_NAME_SUFFIX).toArray(String[]::new);
        for (String propertyName : propertyNames) {
            ShapeBuilder shapeBuilder = getShapeBuilder(value);
            ShapeRelation relation = ShapeRelation.getRelationByName(compare.getCompareName());
            filters.add(new GeoShapeQueryBuilder(propertyName, shapeBuilder).ignoreUnmapped(true).relation(relation));
        }
    }
    if (filters.isEmpty()) {
        // If we didn't add any filters, this means it doesn't exist on any elements so raise an error
        throw new VertexiumNoMatchingPropertiesException(Joiner.on(", ").join(has.getKeys()));
    }
    return getSingleFilterOrOrTheFilters(filters, has);
}
Also used : SortBuilders(org.elasticsearch.search.sort.SortBuilders) ElasticsearchTypes(org.vertexium.elasticsearch5.utils.ElasticsearchTypes) ScriptSortBuilder(org.elasticsearch.search.sort.ScriptSortBuilder) SearchHits(org.elasticsearch.search.SearchHits) RangeAggregationBuilder(org.elasticsearch.search.aggregations.bucket.range.RangeAggregationBuilder) BigDecimal(java.math.BigDecimal) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) SearchResponse(org.elasticsearch.action.search.SearchResponse) BigInteger(java.math.BigInteger) DateHistogramInterval(org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval) SearchHit(org.elasticsearch.search.SearchHit) InfiniteScrollIterable(org.vertexium.elasticsearch5.utils.InfiniteScrollIterable) GeoGridAggregationBuilder(org.elasticsearch.search.aggregations.bucket.geogrid.GeoGridAggregationBuilder) ImmutableMap(com.google.common.collect.ImmutableMap) SortMode(org.elasticsearch.search.sort.SortMode) ShapeRelation(org.elasticsearch.common.geo.ShapeRelation) Collectors(java.util.stream.Collectors) StandardAnalyzer(org.apache.lucene.analysis.standard.StandardAnalyzer) org.elasticsearch.index.query(org.elasticsearch.index.query) ScoringStrategy(org.vertexium.elasticsearch5.score.ScoringStrategy) SortOrder(org.elasticsearch.search.sort.SortOrder) org.vertexium.type(org.vertexium.type) Pattern(java.util.regex.Pattern) Joiner(com.google.common.base.Joiner) ExtendedBounds(org.elasticsearch.search.aggregations.bucket.histogram.ExtendedBounds) java.util(java.util) AbstractAggregationBuilder(org.elasticsearch.search.aggregations.AbstractAggregationBuilder) AggregationBuilder(org.elasticsearch.search.aggregations.AggregationBuilder) ELEMENT_ID_FIELD_NAME(org.vertexium.elasticsearch5.Elasticsearch5SearchIndex.ELEMENT_ID_FIELD_NAME) ScriptType(org.elasticsearch.script.ScriptType) DateRangeAggregationBuilder(org.elasticsearch.search.aggregations.bucket.range.date.DateRangeAggregationBuilder) org.vertexium(org.vertexium) Strings(com.google.common.base.Strings) PercentilesAggregationBuilder(org.elasticsearch.search.aggregations.metrics.percentiles.PercentilesAggregationBuilder) org.elasticsearch.common.geo.builders(org.elasticsearch.common.geo.builders) org.vertexium.query(org.vertexium.query) TimeValue(org.elasticsearch.common.unit.TimeValue) ExtendedStatsAggregationBuilder(org.elasticsearch.search.aggregations.metrics.stats.extended.ExtendedStatsAggregationBuilder) PagingIterable(org.vertexium.elasticsearch5.utils.PagingIterable) StreamSupport(java.util.stream.StreamSupport) TermsAggregationBuilder(org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder) CharTermAttribute(org.apache.lucene.analysis.tokenattributes.CharTermAttribute) Coordinate(com.vividsolutions.jts.geom.Coordinate) Script(org.elasticsearch.script.Script) TokenStream(org.apache.lucene.analysis.TokenStream) Client(org.elasticsearch.client.Client) DateTime(org.joda.time.DateTime) AggregationBuilders(org.elasticsearch.search.aggregations.AggregationBuilders) IOException(java.io.IOException) HistogramAggregationBuilder(org.elasticsearch.search.aggregations.bucket.histogram.HistogramAggregationBuilder) Maps(com.google.common.collect.Maps) HIDDEN_VERTEX_FIELD_NAME(org.vertexium.elasticsearch5.Elasticsearch5SearchIndex.HIDDEN_VERTEX_FIELD_NAME) org.vertexium.util(org.vertexium.util) DateHistogramAggregationBuilder(org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramAggregationBuilder) DistanceUnit(org.elasticsearch.common.unit.DistanceUnit) SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) SearchResponseUtils.checkForFailures(org.vertexium.elasticsearch5.utils.SearchResponseUtils.checkForFailures) ShapeRelation(org.elasticsearch.common.geo.ShapeRelation)

Aggregations

ShapeRelation (org.elasticsearch.common.geo.ShapeRelation)4 Joiner (com.google.common.base.Joiner)1 Strings (com.google.common.base.Strings)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 Maps (com.google.common.collect.Maps)1 Coordinate (com.vividsolutions.jts.geom.Coordinate)1 FunctionToQuery (io.crate.lucene.FunctionToQuery)1 LuceneQueryBuilder (io.crate.lucene.LuceneQueryBuilder)1 IOException (java.io.IOException)1 BigDecimal (java.math.BigDecimal)1 BigInteger (java.math.BigInteger)1 java.util (java.util)1 Map (java.util.Map)1 Pattern (java.util.regex.Pattern)1 Collectors (java.util.stream.Collectors)1 StreamSupport (java.util.stream.StreamSupport)1 TokenStream (org.apache.lucene.analysis.TokenStream)1 StandardAnalyzer (org.apache.lucene.analysis.standard.StandardAnalyzer)1 CharTermAttribute (org.apache.lucene.analysis.tokenattributes.CharTermAttribute)1 BooleanQuery (org.apache.lucene.search.BooleanQuery)1