Search in sources :

Example 1 with InternalSearchResponse

use of org.elasticsearch.search.internal.InternalSearchResponse in project elasticsearch by elastic.

the class FetchSearchPhase method moveToNextPhase.

private void moveToNextPhase(SearchPhaseController searchPhaseController, ScoreDoc[] sortedDocs, String scrollId, SearchPhaseController.ReducedQueryPhase reducedQueryPhase, AtomicArray<? extends QuerySearchResultProvider> fetchResultsArr) {
    final InternalSearchResponse internalResponse = searchPhaseController.merge(context.getRequest().scroll() != null, sortedDocs, reducedQueryPhase, fetchResultsArr);
    context.executeNextPhase(this, nextPhaseFactory.apply(context.buildSearchResponse(internalResponse, scrollId)));
}
Also used : InternalSearchResponse(org.elasticsearch.search.internal.InternalSearchResponse)

Example 2 with InternalSearchResponse

use of org.elasticsearch.search.internal.InternalSearchResponse in project elasticsearch by elastic.

the class SearchPhaseControllerTests method testMerge.

public void testMerge() throws IOException {
    List<CompletionSuggestion> suggestions = new ArrayList<>();
    for (int i = 0; i < randomIntBetween(1, 5); i++) {
        suggestions.add(new CompletionSuggestion(randomAsciiOfLength(randomIntBetween(1, 5)), randomIntBetween(1, 20)));
    }
    int nShards = randomIntBetween(1, 20);
    int queryResultSize = randomBoolean() ? 0 : randomIntBetween(1, nShards * 2);
    AtomicArray<QuerySearchResultProvider> queryResults = generateQueryResults(nShards, suggestions, queryResultSize, false);
    // calculate offsets and score doc array
    List<ScoreDoc> mergedScoreDocs = new ArrayList<>();
    ScoreDoc[] mergedSearchDocs = getTopShardDocs(queryResults);
    mergedScoreDocs.addAll(Arrays.asList(mergedSearchDocs));
    Suggest mergedSuggest = reducedSuggest(queryResults);
    for (Suggest.Suggestion<?> suggestion : mergedSuggest) {
        if (suggestion instanceof CompletionSuggestion) {
            CompletionSuggestion completionSuggestion = ((CompletionSuggestion) suggestion);
            mergedScoreDocs.addAll(completionSuggestion.getOptions().stream().map(CompletionSuggestion.Entry.Option::getDoc).collect(Collectors.toList()));
        }
    }
    ScoreDoc[] sortedDocs = mergedScoreDocs.toArray(new ScoreDoc[mergedScoreDocs.size()]);
    InternalSearchResponse mergedResponse = searchPhaseController.merge(true, sortedDocs, searchPhaseController.reducedQueryPhase(queryResults.asList()), generateFetchResults(nShards, mergedSearchDocs, mergedSuggest));
    assertThat(mergedResponse.hits().getHits().length, equalTo(mergedSearchDocs.length));
    Suggest suggestResult = mergedResponse.suggest();
    for (Suggest.Suggestion<?> suggestion : mergedSuggest) {
        assertThat(suggestion, instanceOf(CompletionSuggestion.class));
        if (suggestion.getEntries().get(0).getOptions().size() > 0) {
            CompletionSuggestion suggestionResult = suggestResult.getSuggestion(suggestion.getName());
            assertNotNull(suggestionResult);
            List<CompletionSuggestion.Entry.Option> options = suggestionResult.getEntries().get(0).getOptions();
            assertThat(options.size(), equalTo(suggestion.getEntries().get(0).getOptions().size()));
            for (CompletionSuggestion.Entry.Option option : options) {
                assertNotNull(option.getHit());
            }
        }
    }
}
Also used : CompletionSuggestion(org.elasticsearch.search.suggest.completion.CompletionSuggestion) QuerySearchResultProvider(org.elasticsearch.search.query.QuerySearchResultProvider) ArrayList(java.util.ArrayList) Suggest(org.elasticsearch.search.suggest.Suggest) ScoreDoc(org.apache.lucene.search.ScoreDoc) InternalSearchResponse(org.elasticsearch.search.internal.InternalSearchResponse)

Example 3 with InternalSearchResponse

use of org.elasticsearch.search.internal.InternalSearchResponse 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 4 with InternalSearchResponse

use of org.elasticsearch.search.internal.InternalSearchResponse in project elasticsearch by elastic.

the class AsyncBulkByScrollActionTests method testScrollDelay.

public void testScrollDelay() throws Exception {
    /*
         * Replace the thread pool with one that will save the delay sent for the command. We'll use that to check that we used a proper
         * delay for throttling.
         */
    AtomicReference<TimeValue> capturedDelay = new AtomicReference<>();
    AtomicReference<Runnable> capturedCommand = new AtomicReference<>();
    setupClient(new TestThreadPool(getTestName()) {

        @Override
        public ScheduledFuture<?> schedule(TimeValue delay, String name, Runnable command) {
            capturedDelay.set(delay);
            capturedCommand.set(command);
            return null;
        }
    });
    DummyAsyncBulkByScrollAction action = new DummyAsyncBulkByScrollAction();
    action.setScroll(scrollId());
    // Set the base for the scroll to wait - this is added to the figure we calculate below
    firstSearchRequest.scroll(timeValueSeconds(10));
    // Set throttle to 1 request per second to make the math simpler
    testTask.rethrottle(1f);
    // Make the last batch look nearly instant but have 100 documents
    action.startNextScroll(timeValueNanos(System.nanoTime()), 100);
    // So the next request is going to have to wait an extra 100 seconds or so (base was 10 seconds, so 110ish)
    assertThat(client.lastScroll.get().request.scroll().keepAlive().seconds(), either(equalTo(110L)).or(equalTo(109L)));
    // Now we can simulate a response and check the delay that we used for the task
    SearchHit hit = new SearchHit(0, "id", new Text("type"), emptyMap());
    SearchHits hits = new SearchHits(new SearchHit[] { hit }, 0, 0);
    InternalSearchResponse internalResponse = new InternalSearchResponse(hits, null, null, null, false, false, 1);
    SearchResponse searchResponse = new SearchResponse(internalResponse, scrollId(), 5, 4, randomLong(), null);
    if (randomBoolean()) {
        client.lastScroll.get().listener.onResponse(searchResponse);
        // The delay is still 100ish seconds because there hasn't been much time between when we requested the bulk and when we got it.
        assertThat(capturedDelay.get().seconds(), either(equalTo(100L)).or(equalTo(99L)));
    } else {
        // Let's rethrottle between the starting the scroll and getting the response
        testTask.rethrottle(10f);
        client.lastScroll.get().listener.onResponse(searchResponse);
        // The delay uses the new throttle
        assertThat(capturedDelay.get().seconds(), either(equalTo(10L)).or(equalTo(9L)));
    }
    // Running the command ought to increment the delay counter on the task.
    capturedCommand.get().run();
    assertEquals(capturedDelay.get(), testTask.getStatus().getThrottled());
}
Also used : SearchHit(org.elasticsearch.search.SearchHit) AtomicReference(java.util.concurrent.atomic.AtomicReference) Text(org.elasticsearch.common.text.Text) Matchers.containsString(org.hamcrest.Matchers.containsString) TestUtil.randomSimpleString(org.apache.lucene.util.TestUtil.randomSimpleString) TestThreadPool(org.elasticsearch.threadpool.TestThreadPool) ScheduledFuture(java.util.concurrent.ScheduledFuture) SearchResponse(org.elasticsearch.action.search.SearchResponse) InternalSearchResponse(org.elasticsearch.search.internal.InternalSearchResponse) AbstractRunnable(org.elasticsearch.common.util.concurrent.AbstractRunnable) SearchHits(org.elasticsearch.search.SearchHits) TimeValue(org.elasticsearch.common.unit.TimeValue) InternalSearchResponse(org.elasticsearch.search.internal.InternalSearchResponse)

Example 5 with InternalSearchResponse

use of org.elasticsearch.search.internal.InternalSearchResponse in project elasticsearch by elastic.

the class SearchScrollQueryAndFetchAsyncAction method innerFinishHim.

private void innerFinishHim() throws Exception {
    ScoreDoc[] sortedShardDocs = searchPhaseController.sortDocs(true, queryFetchResults);
    final InternalSearchResponse internalResponse = searchPhaseController.merge(true, sortedShardDocs, searchPhaseController.reducedQueryPhase(queryFetchResults.asList()), queryFetchResults);
    String scrollId = null;
    if (request.scroll() != null) {
        scrollId = request.scrollId();
    }
    listener.onResponse(new SearchResponse(internalResponse, scrollId, this.scrollId.getContext().length, successfulOps.get(), buildTookInMillis(), buildShardFailures()));
}
Also used : ScoreDoc(org.apache.lucene.search.ScoreDoc) InternalSearchResponse(org.elasticsearch.search.internal.InternalSearchResponse) InternalSearchResponse(org.elasticsearch.search.internal.InternalSearchResponse)

Aggregations

InternalSearchResponse (org.elasticsearch.search.internal.InternalSearchResponse)8 AtomicReference (java.util.concurrent.atomic.AtomicReference)4 Text (org.elasticsearch.common.text.Text)4 SearchHit (org.elasticsearch.search.SearchHit)4 SearchHits (org.elasticsearch.search.SearchHits)4 IOException (java.io.IOException)3 SearchHitField (org.elasticsearch.search.SearchHitField)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 ScoreDoc (org.apache.lucene.search.ScoreDoc)2 InnerHitBuilder (org.elasticsearch.index.query.InnerHitBuilder)2 SearchSourceBuilder (org.elasticsearch.search.builder.SearchSourceBuilder)2 CollapseBuilder (org.elasticsearch.search.collapse.CollapseBuilder)2 ArrayList (java.util.ArrayList)1 ScheduledFuture (java.util.concurrent.ScheduledFuture)1 TestUtil.randomSimpleString (org.apache.lucene.util.TestUtil.randomSimpleString)1 SearchResponse (org.elasticsearch.action.search.SearchResponse)1 TimeValue (org.elasticsearch.common.unit.TimeValue)1 AbstractRunnable (org.elasticsearch.common.util.concurrent.AbstractRunnable)1 BoolQueryBuilder (org.elasticsearch.index.query.BoolQueryBuilder)1 QueryBuilder (org.elasticsearch.index.query.QueryBuilder)1