Search in sources :

Example 76 with QueryBuilder

use of org.elasticsearch.index.query.QueryBuilder in project elasticsearch by elastic.

the class FiltersAggregationBuilder method parse.

public static FiltersAggregationBuilder parse(String aggregationName, QueryParseContext context) throws IOException {
    XContentParser parser = context.parser();
    List<FiltersAggregator.KeyedFilter> keyedFilters = null;
    List<QueryBuilder> nonKeyedFilters = null;
    XContentParser.Token token = null;
    String currentFieldName = null;
    String otherBucketKey = null;
    Boolean otherBucket = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
            if (OTHER_BUCKET_FIELD.match(currentFieldName)) {
                otherBucket = parser.booleanValue();
            } else {
                throw new ParsingException(parser.getTokenLocation(), "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].");
            }
        } else if (token == XContentParser.Token.VALUE_STRING) {
            if (OTHER_BUCKET_KEY_FIELD.match(currentFieldName)) {
                otherBucketKey = parser.text();
            } else {
                throw new ParsingException(parser.getTokenLocation(), "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].");
            }
        } else if (token == XContentParser.Token.START_OBJECT) {
            if (FILTERS_FIELD.match(currentFieldName)) {
                keyedFilters = new ArrayList<>();
                String key = null;
                while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                    if (token == XContentParser.Token.FIELD_NAME) {
                        key = parser.currentName();
                    } else {
                        QueryBuilder filter = context.parseInnerQueryBuilder();
                        keyedFilters.add(new FiltersAggregator.KeyedFilter(key, filter));
                    }
                }
            } else {
                throw new ParsingException(parser.getTokenLocation(), "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].");
            }
        } else if (token == XContentParser.Token.START_ARRAY) {
            if (FILTERS_FIELD.match(currentFieldName)) {
                nonKeyedFilters = new ArrayList<>();
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                    QueryBuilder filter = context.parseInnerQueryBuilder();
                    nonKeyedFilters.add(filter);
                }
            } else {
                throw new ParsingException(parser.getTokenLocation(), "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].");
            }
        } else {
            throw new ParsingException(parser.getTokenLocation(), "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].");
        }
    }
    if (otherBucket == null && otherBucketKey != null) {
        // automatically enable the other bucket if a key is set, as per the doc
        otherBucket = true;
    }
    FiltersAggregationBuilder factory;
    if (keyedFilters != null) {
        factory = new FiltersAggregationBuilder(aggregationName, keyedFilters.toArray(new FiltersAggregator.KeyedFilter[keyedFilters.size()]));
    } else {
        factory = new FiltersAggregationBuilder(aggregationName, nonKeyedFilters.toArray(new QueryBuilder[nonKeyedFilters.size()]));
    }
    if (otherBucket != null) {
        factory.otherBucket(otherBucket);
    }
    if (otherBucketKey != null) {
        factory.otherBucketKey(otherBucketKey);
    }
    return factory;
}
Also used : ArrayList(java.util.ArrayList) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) KeyedFilter(org.elasticsearch.search.aggregations.bucket.filters.FiltersAggregator.KeyedFilter) ParsingException(org.elasticsearch.common.ParsingException) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 77 with QueryBuilder

use of org.elasticsearch.index.query.QueryBuilder in project elasticsearch by elastic.

the class AdjacencyMatrixAggregationBuilder method setFiltersAsMap.

protected void setFiltersAsMap(Map<String, QueryBuilder> filters) {
    // Convert uniquely named objects into internal KeyedFilters
    this.filters = new ArrayList<>(filters.size());
    for (Entry<String, QueryBuilder> kv : filters.entrySet()) {
        this.filters.add(new KeyedFilter(kv.getKey(), kv.getValue()));
    }
    // internally we want to have a fixed order of filters, regardless of
    // the order of the filters in the request
    Collections.sort(this.filters, Comparator.comparing(KeyedFilter::key));
}
Also used : KeyedFilter(org.elasticsearch.search.aggregations.bucket.adjacency.AdjacencyMatrixAggregator.KeyedFilter) QueryBuilder(org.elasticsearch.index.query.QueryBuilder)

Example 78 with QueryBuilder

use of org.elasticsearch.index.query.QueryBuilder in project elasticsearch-jdbc by jprante.

the class NodeTestUtils method assertTimestampSort.

protected void assertTimestampSort(String id, int expectedHits) {
    client(id).admin().indices().prepareRefresh(index).execute().actionGet();
    QueryBuilder queryBuilder = QueryBuilders.matchAllQuery();
    SortBuilder sortBuilder = SortBuilders.fieldSort("_timestamp").order(SortOrder.DESC);
    SearchHits hits = client(id).prepareSearch(index).setTypes(type).setQuery(queryBuilder).addSort(sortBuilder).addFields("_source", "_timestamp").setSize(expectedHits).execute().actionGet().getHits();
    Long prev = Long.MAX_VALUE;
    for (SearchHit hit : hits) {
        if (hit.getFields().get("_timestamp") == null) {
            logger.warn("type mapping was not correctly applied for _timestamp field");
        }
        Long curr = hit.getFields().get("_timestamp").getValue();
        logger.info("timestamp = {}", curr);
        assertTrue(curr <= prev);
        prev = curr;
    }
    logger.info("{}/{} = {} hits", index, type, hits.getTotalHits());
    assertEquals(hits.getTotalHits(), expectedHits);
}
Also used : SortBuilder(org.elasticsearch.search.sort.SortBuilder) SearchHit(org.elasticsearch.search.SearchHit) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) SearchHits(org.elasticsearch.search.SearchHits)

Example 79 with QueryBuilder

use of org.elasticsearch.index.query.QueryBuilder in project elasticsearch by elastic.

the class ExpandSearchPhase method run.

@Override
public void run() throws IOException {
    if (isCollapseRequest()) {
        SearchRequest searchRequest = context.getRequest();
        CollapseBuilder collapseBuilder = searchRequest.source().collapse();
        MultiSearchRequest multiRequest = new MultiSearchRequest();
        if (collapseBuilder.getMaxConcurrentGroupRequests() > 0) {
            multiRequest.maxConcurrentSearchRequests(collapseBuilder.getMaxConcurrentGroupRequests());
        }
        for (SearchHit hit : searchResponse.getHits()) {
            BoolQueryBuilder groupQuery = new BoolQueryBuilder();
            Object collapseValue = hit.field(collapseBuilder.getField()).getValue();
            if (collapseValue != null) {
                groupQuery.filter(QueryBuilders.matchQuery(collapseBuilder.getField(), collapseValue));
            } else {
                groupQuery.mustNot(QueryBuilders.existsQuery(collapseBuilder.getField()));
            }
            QueryBuilder origQuery = searchRequest.source().query();
            if (origQuery != null) {
                groupQuery.must(origQuery);
            }
            SearchSourceBuilder sourceBuilder = buildExpandSearchSourceBuilder(collapseBuilder.getInnerHit()).query(groupQuery);
            SearchRequest groupRequest = new SearchRequest(searchRequest.indices()).types(searchRequest.types()).source(sourceBuilder);
            multiRequest.add(groupRequest);
        }
        context.getSearchTransport().sendExecuteMultiSearch(multiRequest, context.getTask(), ActionListener.wrap(response -> {
            Iterator<MultiSearchResponse.Item> it = response.iterator();
            for (SearchHit hit : searchResponse.getHits()) {
                MultiSearchResponse.Item item = it.next();
                if (item.isFailure()) {
                    context.onPhaseFailure(this, "failed to expand hits", item.getFailure());
                    return;
                }
                SearchHits innerHits = item.getResponse().getHits();
                if (hit.getInnerHits() == null) {
                    hit.setInnerHits(new HashMap<>(1));
                }
                hit.getInnerHits().put(collapseBuilder.getInnerHit().getName(), innerHits);
            }
            context.executeNextPhase(this, nextPhaseFactory.apply(searchResponse));
        }, context::onFailure));
    } else {
        context.executeNextPhase(this, nextPhaseFactory.apply(searchResponse));
    }
}
Also used : SearchHit(org.elasticsearch.search.SearchHit) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) Iterator(java.util.Iterator) SearchHits(org.elasticsearch.search.SearchHits) IOException(java.io.IOException) HashMap(java.util.HashMap) QueryBuilders(org.elasticsearch.index.query.QueryBuilders) Function(java.util.function.Function) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) InnerHitBuilder(org.elasticsearch.index.query.InnerHitBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) ActionListener(org.elasticsearch.action.ActionListener) CollapseBuilder(org.elasticsearch.search.collapse.CollapseBuilder) CollapseBuilder(org.elasticsearch.search.collapse.CollapseBuilder) SearchHit(org.elasticsearch.search.SearchHit) HashMap(java.util.HashMap) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) Iterator(java.util.Iterator) SearchHits(org.elasticsearch.search.SearchHits)

Example 80 with QueryBuilder

use of org.elasticsearch.index.query.QueryBuilder in project elasticsearch by elastic.

the class SearchSourceBuilder method rewrite.

/**
     * Rewrites this search source builder into its primitive form. e.g. by
     * rewriting the QueryBuilder. If the builder did not change the identity
     * reference must be returned otherwise the builder will be rewritten
     * infinitely.
     */
public SearchSourceBuilder rewrite(QueryShardContext context) throws IOException {
    assert (this.equals(shallowCopy(queryBuilder, postQueryBuilder, sliceBuilder)));
    QueryBuilder queryBuilder = null;
    if (this.queryBuilder != null) {
        queryBuilder = this.queryBuilder.rewrite(context);
    }
    QueryBuilder postQueryBuilder = null;
    if (this.postQueryBuilder != null) {
        postQueryBuilder = this.postQueryBuilder.rewrite(context);
    }
    boolean rewritten = queryBuilder != this.queryBuilder || postQueryBuilder != this.postQueryBuilder;
    if (rewritten) {
        return shallowCopy(queryBuilder, postQueryBuilder, sliceBuilder);
    }
    return this;
}
Also used : QueryBuilder(org.elasticsearch.index.query.QueryBuilder)

Aggregations

QueryBuilder (org.elasticsearch.index.query.QueryBuilder)161 BoolQueryBuilder (org.elasticsearch.index.query.BoolQueryBuilder)51 SearchResponse (org.elasticsearch.action.search.SearchResponse)32 MatchAllQueryBuilder (org.elasticsearch.index.query.MatchAllQueryBuilder)25 Map (java.util.Map)22 ArrayList (java.util.ArrayList)19 AbstractQueryBuilder (org.elasticsearch.index.query.AbstractQueryBuilder)19 RangeQueryBuilder (org.elasticsearch.index.query.RangeQueryBuilder)19 MatchQueryBuilder (org.elasticsearch.index.query.MatchQueryBuilder)18 HashMap (java.util.HashMap)16 SearchRequestBuilder (org.elasticsearch.action.search.SearchRequestBuilder)16 IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)14 HasParentQueryBuilder (org.elasticsearch.index.query.HasParentQueryBuilder)14 TermQueryBuilder (org.elasticsearch.index.query.TermQueryBuilder)14 FunctionScoreQueryBuilder (org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder)14 IOException (java.io.IOException)12 FessConfig (org.codelibs.fess.mylasta.direction.FessConfig)12 MultiSearchResponse (org.elasticsearch.action.search.MultiSearchResponse)11 XContentParser (org.elasticsearch.common.xcontent.XContentParser)11 BytesRef (org.apache.lucene.util.BytesRef)10