Search in sources :

Example 6 with QueryBuilder

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

the class ExpandSearchPhaseTests method testCollapseSingleHit.

public void testCollapseSingleHit() throws IOException {
    final int iters = randomIntBetween(5, 10);
    for (int i = 0; i < iters; i++) {
        SearchHits collapsedHits = new SearchHits(new SearchHit[] { new SearchHit(2, "ID", new Text("type"), Collections.emptyMap()), new SearchHit(3, "ID", new Text("type"), Collections.emptyMap()) }, 1, 1.0F);
        AtomicBoolean executedMultiSearch = new AtomicBoolean(false);
        QueryBuilder originalQuery = randomBoolean() ? null : QueryBuilders.termQuery("foo", "bar");
        MockSearchPhaseContext mockSearchPhaseContext = new MockSearchPhaseContext(1);
        String collapseValue = randomBoolean() ? null : "boom";
        mockSearchPhaseContext.getRequest().source(new SearchSourceBuilder().collapse(new CollapseBuilder("someField").setInnerHits(new InnerHitBuilder().setName("foobarbaz"))));
        mockSearchPhaseContext.getRequest().source().query(originalQuery);
        mockSearchPhaseContext.searchTransport = new SearchTransportService(Settings.builder().put("search.remote.connect", false).build(), null, null) {

            @Override
            void sendExecuteMultiSearch(MultiSearchRequest request, SearchTask task, ActionListener<MultiSearchResponse> listener) {
                assertTrue(executedMultiSearch.compareAndSet(false, true));
                assertEquals(1, request.requests().size());
                SearchRequest searchRequest = request.requests().get(0);
                assertTrue(searchRequest.source().query() instanceof BoolQueryBuilder);
                BoolQueryBuilder groupBuilder = (BoolQueryBuilder) searchRequest.source().query();
                if (collapseValue == null) {
                    assertThat(groupBuilder.mustNot(), Matchers.contains(QueryBuilders.existsQuery("someField")));
                } else {
                    assertThat(groupBuilder.filter(), Matchers.contains(QueryBuilders.matchQuery("someField", "boom")));
                }
                if (originalQuery != null) {
                    assertThat(groupBuilder.must(), Matchers.contains(QueryBuilders.termQuery("foo", "bar")));
                }
                assertArrayEquals(mockSearchPhaseContext.getRequest().indices(), searchRequest.indices());
                assertArrayEquals(mockSearchPhaseContext.getRequest().types(), searchRequest.types());
                InternalSearchResponse internalSearchResponse = new InternalSearchResponse(collapsedHits, null, null, null, false, null, 1);
                SearchResponse response = mockSearchPhaseContext.buildSearchResponse(internalSearchResponse, null);
                listener.onResponse(new MultiSearchResponse(new MultiSearchResponse.Item[] { new MultiSearchResponse.Item(response, null) }));
            }
        };
        SearchHits hits = new SearchHits(new SearchHit[] { new SearchHit(1, "ID", new Text("type"), Collections.singletonMap("someField", new SearchHitField("someField", Collections.singletonList(collapseValue)))) }, 1, 1.0F);
        InternalSearchResponse internalSearchResponse = new InternalSearchResponse(hits, null, null, null, false, null, 1);
        SearchResponse response = mockSearchPhaseContext.buildSearchResponse(internalSearchResponse, null);
        AtomicReference<SearchResponse> reference = new AtomicReference<>();
        ExpandSearchPhase phase = new ExpandSearchPhase(mockSearchPhaseContext, response, r -> new SearchPhase("test") {

            @Override
            public void run() throws IOException {
                reference.set(r);
            }
        });
        phase.run();
        mockSearchPhaseContext.assertNoFailure();
        assertNotNull(reference.get());
        SearchResponse theResponse = reference.get();
        assertSame(theResponse, response);
        assertEquals(1, theResponse.getHits().getHits()[0].getInnerHits().size());
        assertSame(theResponse.getHits().getHits()[0].getInnerHits().get("foobarbaz"), collapsedHits);
        assertTrue(executedMultiSearch.get());
        assertEquals(1, mockSearchPhaseContext.phasesExecuted.get());
    }
}
Also used : SearchHit(org.elasticsearch.search.SearchHit) InnerHitBuilder(org.elasticsearch.index.query.InnerHitBuilder) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) SearchHits(org.elasticsearch.search.SearchHits) CollapseBuilder(org.elasticsearch.search.collapse.CollapseBuilder) Text(org.elasticsearch.common.text.Text) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) InternalSearchResponse(org.elasticsearch.search.internal.InternalSearchResponse) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) SearchHitField(org.elasticsearch.search.SearchHitField) InternalSearchResponse(org.elasticsearch.search.internal.InternalSearchResponse)

Example 7 with QueryBuilder

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

the class IndicesService method buildAliasFilter.

public AliasFilter buildAliasFilter(ClusterState state, String index, String... expressions) {
    /* Being static, parseAliasFilter doesn't have access to whatever guts it needs to parse a query. Instead of passing in a bunch
         * of dependencies we pass in a function that can perform the parsing. */
    CheckedFunction<byte[], QueryBuilder, IOException> filterParser = bytes -> {
        try (XContentParser parser = XContentFactory.xContent(bytes).createParser(xContentRegistry, bytes)) {
            return new QueryParseContext(parser).parseInnerQueryBuilder();
        }
    };
    String[] aliases = indexNameExpressionResolver.filteringAliases(state, index, expressions);
    IndexMetaData indexMetaData = state.metaData().index(index);
    return new AliasFilter(ShardSearchRequest.parseAliasFilter(filterParser, indexMetaData, aliases), aliases);
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) StreamOutput(org.elasticsearch.common.io.stream.StreamOutput) Nullable(org.elasticsearch.common.Nullable) BigArrays(org.elasticsearch.common.util.BigArrays) FlushStats(org.elasticsearch.index.flush.FlushStats) RecoveryStats(org.elasticsearch.index.recovery.RecoveryStats) ClusterState(org.elasticsearch.cluster.ClusterState) QueryPhase(org.elasticsearch.search.query.QueryPhase) IndexingStats(org.elasticsearch.index.shard.IndexingStats) IndexNotFoundException(org.elasticsearch.index.IndexNotFoundException) Map(java.util.Map) EnumSet(java.util.EnumSet) MergeStats(org.elasticsearch.index.merge.MergeStats) SearchType(org.elasticsearch.action.search.SearchType) PeerRecoveryTargetService(org.elasticsearch.indices.recovery.PeerRecoveryTargetService) Set(java.util.Set) CollectionUtils.arrayAsArrayList(org.elasticsearch.common.util.CollectionUtils.arrayAsArrayList) Executors(java.util.concurrent.Executors) RecoverySource(org.elasticsearch.cluster.routing.RecoverySource) CheckedFunction(org.elasticsearch.common.CheckedFunction) AliasFilter(org.elasticsearch.search.internal.AliasFilter) CountDownLatch(java.util.concurrent.CountDownLatch) Logger(org.apache.logging.log4j.Logger) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) Callback(org.elasticsearch.common.util.Callback) XContentFactory(org.elasticsearch.common.xcontent.XContentFactory) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) IndexShardStats(org.elasticsearch.action.admin.indices.stats.IndexShardStats) ClusterService(org.elasticsearch.cluster.service.ClusterService) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput) IndexModule(org.elasticsearch.index.IndexModule) Supplier(java.util.function.Supplier) CircuitBreakerService(org.elasticsearch.indices.breaker.CircuitBreakerService) ArrayList(java.util.ArrayList) BytesArray(org.elasticsearch.common.bytes.BytesArray) ShardRequestCache(org.elasticsearch.index.cache.request.ShardRequestCache) NamedWriteableRegistry(org.elasticsearch.common.io.stream.NamedWriteableRegistry) CircuitBreaker(org.elasticsearch.common.breaker.CircuitBreaker) MetaDataStateFormat(org.elasticsearch.gateway.MetaDataStateFormat) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) FileSystemUtils(org.elasticsearch.common.io.FileSystemUtils) IndexEventListener(org.elasticsearch.index.shard.IndexEventListener) Files(java.nio.file.Files) Client(org.elasticsearch.client.Client) IndexService(org.elasticsearch.index.IndexService) IndexShard(org.elasticsearch.index.shard.IndexShard) IOUtils(org.apache.lucene.util.IOUtils) IOException(java.io.IOException) ShardLock(org.elasticsearch.env.ShardLock) RepositoriesService(org.elasticsearch.repositories.RepositoriesService) CollectionUtil(org.apache.lucene.util.CollectionUtil) XContentParser(org.elasticsearch.common.xcontent.XContentParser) NamedWriteableAwareStreamInput(org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput) IndicesFieldDataCache(org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache) CommonStatsFlags(org.elasticsearch.action.admin.indices.stats.CommonStatsFlags) SearchStats(org.elasticsearch.index.search.stats.SearchStats) ScriptService(org.elasticsearch.script.ScriptService) ElasticsearchException(org.elasticsearch.ElasticsearchException) Property(org.elasticsearch.common.settings.Setting.Property) MapperRegistry(org.elasticsearch.indices.mapper.MapperRegistry) Settings(org.elasticsearch.common.settings.Settings) ShardSearchRequest(org.elasticsearch.search.internal.ShardSearchRequest) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MappedFieldType(org.elasticsearch.index.mapper.MappedFieldType) ThreadPool(org.elasticsearch.threadpool.ThreadPool) NamedXContentRegistry(org.elasticsearch.common.xcontent.NamedXContentRegistry) Releasable(org.elasticsearch.common.lease.Releasable) ByteSizeValue(org.elasticsearch.common.unit.ByteSizeValue) PluginsService(org.elasticsearch.plugins.PluginsService) Setting(org.elasticsearch.common.settings.Setting) Collections.emptyList(java.util.Collections.emptyList) DirectoryReader(org.apache.lucene.index.DirectoryReader) ShardLockObtainFailedException(org.elasticsearch.env.ShardLockObtainFailedException) AnalysisRegistry(org.elasticsearch.index.analysis.AnalysisRegistry) Flag(org.elasticsearch.action.admin.indices.stats.CommonStatsFlags.Flag) BytesReference(org.elasticsearch.common.bytes.BytesReference) IllegalIndexShardStateException(org.elasticsearch.index.shard.IllegalIndexShardStateException) Collectors(java.util.stream.Collectors) MapBuilder.newMapBuilder(org.elasticsearch.common.collect.MapBuilder.newMapBuilder) QueryParseContext(org.elasticsearch.index.query.QueryParseContext) Engine(org.elasticsearch.index.engine.Engine) RamUsageEstimator(org.apache.lucene.util.RamUsageEstimator) MapperService(org.elasticsearch.index.mapper.MapperService) RefreshStats(org.elasticsearch.index.refresh.RefreshStats) List(java.util.List) QuerySearchResult(org.elasticsearch.search.query.QuerySearchResult) IndicesClusterStateService(org.elasticsearch.indices.cluster.IndicesClusterStateService) RecoveryState(org.elasticsearch.indices.recovery.RecoveryState) GetStats(org.elasticsearch.index.get.GetStats) CommonStats(org.elasticsearch.action.admin.indices.stats.CommonStats) FieldStats(org.elasticsearch.action.fieldstats.FieldStats) IndexingOperationListener(org.elasticsearch.index.shard.IndexingOperationListener) ShardRouting(org.elasticsearch.cluster.routing.ShardRouting) XContentType(org.elasticsearch.common.xcontent.XContentType) SearchContext(org.elasticsearch.search.internal.SearchContext) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) MetaStateService(org.elasticsearch.gateway.MetaStateService) Index(org.elasticsearch.index.Index) ParameterizedMessage(org.apache.logging.log4j.message.ParameterizedMessage) ResourceAlreadyExistsException(org.elasticsearch.ResourceAlreadyExistsException) ShardStats(org.elasticsearch.action.admin.indices.stats.ShardStats) TimeValue(org.elasticsearch.common.unit.TimeValue) Iterables(org.elasticsearch.common.util.iterable.Iterables) IndexSettings(org.elasticsearch.index.IndexSettings) ExecutorService(java.util.concurrent.ExecutorService) Collections.emptyMap(java.util.Collections.emptyMap) EsExecutors(org.elasticsearch.common.util.concurrent.EsExecutors) IndexShardState(org.elasticsearch.index.shard.IndexShardState) IndexFieldDataCache(org.elasticsearch.index.fielddata.IndexFieldDataCache) Iterator(java.util.Iterator) AbstractLifecycleComponent(org.elasticsearch.common.component.AbstractLifecycleComponent) IndexScopedSettings(org.elasticsearch.common.settings.IndexScopedSettings) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) ClusterSettings(org.elasticsearch.common.settings.ClusterSettings) NodeEnvironment(org.elasticsearch.env.NodeEnvironment) StreamInput(org.elasticsearch.common.io.stream.StreamInput) Closeable(java.io.Closeable) Collections.unmodifiableMap(java.util.Collections.unmodifiableMap) IndexNameExpressionResolver(org.elasticsearch.cluster.metadata.IndexNameExpressionResolver) AliasFilter(org.elasticsearch.search.internal.AliasFilter) QueryParseContext(org.elasticsearch.index.query.QueryParseContext) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) IOException(java.io.IOException) XContentParser(org.elasticsearch.common.xcontent.XContentParser) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData)

Example 8 with QueryBuilder

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

the class DefaultSearchContext method preProcess.

/**
     * Should be called before executing the main query and after all other parameters have been set.
     */
@Override
public void preProcess(boolean rewrite) {
    if (hasOnlySuggest()) {
        return;
    }
    long from = from() == -1 ? 0 : from();
    long size = size() == -1 ? 10 : size();
    long resultWindow = from + size;
    int maxResultWindow = indexService.getIndexSettings().getMaxResultWindow();
    if (resultWindow > maxResultWindow) {
        if (scrollContext == null) {
            throw new QueryPhaseExecutionException(this, "Result window is too large, from + size must be less than or equal to: [" + maxResultWindow + "] but was [" + resultWindow + "]. See the scroll api for a more efficient way to request large data sets. " + "This limit can be set by changing the [" + IndexSettings.MAX_RESULT_WINDOW_SETTING.getKey() + "] index level setting.");
        }
        throw new QueryPhaseExecutionException(this, "Batch size is too large, size must be less than or equal to: [" + maxResultWindow + "] but was [" + resultWindow + "]. Scroll batch sizes cost as much memory as result windows so they are controlled by the [" + IndexSettings.MAX_RESULT_WINDOW_SETTING.getKey() + "] index level setting.");
    }
    if (rescore != null) {
        int maxWindow = indexService.getIndexSettings().getMaxRescoreWindow();
        for (RescoreSearchContext rescoreContext : rescore) {
            if (rescoreContext.window() > maxWindow) {
                throw new QueryPhaseExecutionException(this, "Rescore window [" + rescoreContext.window() + "] is too large. It must " + "be less than [" + maxWindow + "]. This prevents allocating massive heaps for storing the results to be " + "rescored. This limit can be set by changing the [" + IndexSettings.MAX_RESCORE_WINDOW_SETTING.getKey() + "] index level setting.");
            }
        }
    }
    if (sliceBuilder != null) {
        int sliceLimit = indexService.getIndexSettings().getMaxSlicesPerScroll();
        int numSlices = sliceBuilder.getMax();
        if (numSlices > sliceLimit) {
            throw new QueryPhaseExecutionException(this, "The number of slices [" + numSlices + "] is too large. It must " + "be less than [" + sliceLimit + "]. This limit can be set by changing the [" + IndexSettings.MAX_SLICES_PER_SCROLL.getKey() + "] index level setting.");
        }
    }
    // initialize the filtering alias based on the provided filters
    try {
        final QueryBuilder queryBuilder = request.filteringAliases();
        aliasFilter = queryBuilder == null ? null : queryBuilder.toFilter(queryShardContext);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    if (query() == null) {
        parsedQuery(ParsedQuery.parsedMatchAllQuery());
    }
    if (queryBoost() != AbstractQueryBuilder.DEFAULT_BOOST) {
        parsedQuery(new ParsedQuery(new FunctionScoreQuery(query(), new WeightFactorFunction(queryBoost)), parsedQuery()));
    }
    this.query = buildFilteredQuery(query);
    if (rewrite) {
        try {
            this.query = searcher.rewrite(query);
        } catch (IOException e) {
            throw new QueryPhaseExecutionException(this, "Failed to rewrite main query", e);
        }
    }
}
Also used : WeightFactorFunction(org.elasticsearch.common.lucene.search.function.WeightFactorFunction) RescoreSearchContext(org.elasticsearch.search.rescore.RescoreSearchContext) ParsedQuery(org.elasticsearch.index.query.ParsedQuery) FunctionScoreQuery(org.elasticsearch.common.lucene.search.function.FunctionScoreQuery) QueryPhaseExecutionException(org.elasticsearch.search.query.QueryPhaseExecutionException) UncheckedIOException(java.io.UncheckedIOException) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) AbstractQueryBuilder(org.elasticsearch.index.query.AbstractQueryBuilder) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException)

Example 9 with QueryBuilder

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

the class RestSearchAction method parseSearchSource.

/**
     * Parses the rest request on top of the SearchSourceBuilder, preserving
     * values that are not overridden by the rest request.
     */
private static void parseSearchSource(final SearchSourceBuilder searchSourceBuilder, RestRequest request) {
    QueryBuilder queryBuilder = RestActions.urlParamsToQueryBuilder(request);
    if (queryBuilder != null) {
        searchSourceBuilder.query(queryBuilder);
    }
    int from = request.paramAsInt("from", -1);
    if (from != -1) {
        searchSourceBuilder.from(from);
    }
    int size = request.paramAsInt("size", -1);
    if (size != -1) {
        searchSourceBuilder.size(size);
    }
    if (request.hasParam("explain")) {
        searchSourceBuilder.explain(request.paramAsBoolean("explain", null));
    }
    if (request.hasParam("version")) {
        searchSourceBuilder.version(request.paramAsBoolean("version", null));
    }
    if (request.hasParam("timeout")) {
        searchSourceBuilder.timeout(request.paramAsTime("timeout", null));
    }
    if (request.hasParam("terminate_after")) {
        int terminateAfter = request.paramAsInt("terminate_after", SearchContext.DEFAULT_TERMINATE_AFTER);
        if (terminateAfter < 0) {
            throw new IllegalArgumentException("terminateAfter must be > 0");
        } else if (terminateAfter > 0) {
            searchSourceBuilder.terminateAfter(terminateAfter);
        }
    }
    if (request.param("fields") != null) {
        throw new IllegalArgumentException("The parameter [" + SearchSourceBuilder.FIELDS_FIELD + "] is no longer supported, please use [" + SearchSourceBuilder.STORED_FIELDS_FIELD + "] to retrieve stored fields or _source filtering " + "if the field is not stored");
    }
    StoredFieldsContext storedFieldsContext = StoredFieldsContext.fromRestRequest(SearchSourceBuilder.STORED_FIELDS_FIELD.getPreferredName(), request);
    if (storedFieldsContext != null) {
        searchSourceBuilder.storedFields(storedFieldsContext);
    }
    String sDocValueFields = request.param("docvalue_fields");
    if (sDocValueFields == null) {
        sDocValueFields = request.param("fielddata_fields");
    }
    if (sDocValueFields != null) {
        if (Strings.hasText(sDocValueFields)) {
            String[] sFields = Strings.splitStringByCommaToArray(sDocValueFields);
            for (String field : sFields) {
                searchSourceBuilder.docValueField(field);
            }
        }
    }
    FetchSourceContext fetchSourceContext = FetchSourceContext.parseFromRestRequest(request);
    if (fetchSourceContext != null) {
        searchSourceBuilder.fetchSource(fetchSourceContext);
    }
    if (request.hasParam("track_scores")) {
        searchSourceBuilder.trackScores(request.paramAsBoolean("track_scores", false));
    }
    String sSorts = request.param("sort");
    if (sSorts != null) {
        String[] sorts = Strings.splitStringByCommaToArray(sSorts);
        for (String sort : sorts) {
            int delimiter = sort.lastIndexOf(":");
            if (delimiter != -1) {
                String sortField = sort.substring(0, delimiter);
                String reverse = sort.substring(delimiter + 1);
                if ("asc".equals(reverse)) {
                    searchSourceBuilder.sort(sortField, SortOrder.ASC);
                } else if ("desc".equals(reverse)) {
                    searchSourceBuilder.sort(sortField, SortOrder.DESC);
                }
            } else {
                searchSourceBuilder.sort(sort);
            }
        }
    }
    String sStats = request.param("stats");
    if (sStats != null) {
        searchSourceBuilder.stats(Arrays.asList(Strings.splitStringByCommaToArray(sStats)));
    }
    String suggestField = request.param("suggest_field");
    if (suggestField != null) {
        String suggestText = request.param("suggest_text", request.param("q"));
        int suggestSize = request.paramAsInt("suggest_size", 5);
        String suggestMode = request.param("suggest_mode");
        searchSourceBuilder.suggest(new SuggestBuilder().addSuggestion(suggestField, termSuggestion(suggestField).text(suggestText).size(suggestSize).suggestMode(SuggestMode.resolve(suggestMode))));
    }
}
Also used : StoredFieldsContext(org.elasticsearch.search.fetch.StoredFieldsContext) SuggestBuilder(org.elasticsearch.search.suggest.SuggestBuilder) FetchSourceContext(org.elasticsearch.search.fetch.subphase.FetchSourceContext) QueryBuilder(org.elasticsearch.index.query.QueryBuilder)

Example 10 with QueryBuilder

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

the class RestCountAction method prepareRequest.

@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
    SearchRequest countRequest = new SearchRequest(Strings.splitStringByCommaToArray(request.param("index")));
    countRequest.indicesOptions(IndicesOptions.fromRequest(request, countRequest.indicesOptions()));
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().size(0);
    countRequest.source(searchSourceBuilder);
    request.withContentOrSourceParamParserOrNull(parser -> {
        if (parser == null) {
            QueryBuilder queryBuilder = RestActions.urlParamsToQueryBuilder(request);
            if (queryBuilder != null) {
                searchSourceBuilder.query(queryBuilder);
            }
        } else {
            searchSourceBuilder.query(RestActions.getQueryContent(parser));
        }
    });
    countRequest.routing(request.param("routing"));
    float minScore = request.paramAsFloat("min_score", -1f);
    if (minScore != -1f) {
        searchSourceBuilder.minScore(minScore);
    }
    countRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
    countRequest.preference(request.param("preference"));
    final int terminateAfter = request.paramAsInt("terminate_after", DEFAULT_TERMINATE_AFTER);
    if (terminateAfter < 0) {
        throw new IllegalArgumentException("terminateAfter must be > 0");
    } else if (terminateAfter > 0) {
        searchSourceBuilder.terminateAfter(terminateAfter);
    }
    return channel -> client.search(countRequest, new RestBuilderListener<SearchResponse>(channel) {

        @Override
        public RestResponse buildResponse(SearchResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            if (terminateAfter != DEFAULT_TERMINATE_AFTER) {
                builder.field("terminated_early", response.isTerminatedEarly());
            }
            builder.field("count", response.getHits().getTotalHits());
            buildBroadcastShardsHeader(builder, request, response.getTotalShards(), response.getSuccessfulShards(), response.getFailedShards(), response.getShardFailures());
            builder.endObject();
            return new BytesRestResponse(response.status(), builder);
        }
    });
}
Also used : BaseRestHandler(org.elasticsearch.rest.BaseRestHandler) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) GET(org.elasticsearch.rest.RestRequest.Method.GET) RestResponse(org.elasticsearch.rest.RestResponse) RestBuilderListener(org.elasticsearch.rest.action.RestBuilderListener) IOException(java.io.IOException) SearchRequest(org.elasticsearch.action.search.SearchRequest) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) RestController(org.elasticsearch.rest.RestController) Strings(org.elasticsearch.common.Strings) RestActions(org.elasticsearch.rest.action.RestActions) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) DEFAULT_TERMINATE_AFTER(org.elasticsearch.search.internal.SearchContext.DEFAULT_TERMINATE_AFTER) POST(org.elasticsearch.rest.RestRequest.Method.POST) Settings(org.elasticsearch.common.settings.Settings) RestActions.buildBroadcastShardsHeader(org.elasticsearch.rest.action.RestActions.buildBroadcastShardsHeader) SearchResponse(org.elasticsearch.action.search.SearchResponse) IndicesOptions(org.elasticsearch.action.support.IndicesOptions) RestRequest(org.elasticsearch.rest.RestRequest) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) NodeClient(org.elasticsearch.client.node.NodeClient) SearchRequest(org.elasticsearch.action.search.SearchRequest) RestResponse(org.elasticsearch.rest.RestResponse) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) IOException(java.io.IOException) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) SearchResponse(org.elasticsearch.action.search.SearchResponse) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder)

Aggregations

QueryBuilder (org.elasticsearch.index.query.QueryBuilder)344 BoolQueryBuilder (org.elasticsearch.index.query.BoolQueryBuilder)233 Test (org.testng.annotations.Test)156 DynamicEntity (org.molgenis.data.support.DynamicEntity)137 SearchResponse (org.elasticsearch.action.search.SearchResponse)52 QueryImpl (org.molgenis.data.support.QueryImpl)36 ArrayList (java.util.ArrayList)28 Map (java.util.Map)28 RangeQueryBuilder (org.elasticsearch.index.query.RangeQueryBuilder)27 MatchAllQueryBuilder (org.elasticsearch.index.query.MatchAllQueryBuilder)26 HashMap (java.util.HashMap)25 SearchRequestBuilder (org.elasticsearch.action.search.SearchRequestBuilder)22 SearchHit (org.elasticsearch.search.SearchHit)20 IOException (java.io.IOException)19 AbstractQueryBuilder (org.elasticsearch.index.query.AbstractQueryBuilder)19 MatchQueryBuilder (org.elasticsearch.index.query.MatchQueryBuilder)17 Test (org.junit.Test)16 IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)15 List (java.util.List)14 HasParentQueryBuilder (org.elasticsearch.index.query.HasParentQueryBuilder)14