Search in sources :

Example 96 with SearchSourceBuilder

use of org.opensearch.search.builder.SearchSourceBuilder in project OpenSearch by opensearch-project.

the class SearchSlowLogTests method testSlowLogsWithStats.

public void testSlowLogsWithStats() throws IOException {
    IndexService index = createIndex("foo");
    SearchContext searchContext = createSearchContext(index, "group1");
    SearchSourceBuilder source = SearchSourceBuilder.searchSource().query(QueryBuilders.matchAllQuery());
    searchContext.request().source(source);
    searchContext.setTask(new SearchShardTask(0, "n/a", "n/a", "test", null, Collections.singletonMap(Task.X_OPAQUE_ID, "my_id")));
    SearchSlowLog.SearchSlowLogMessage p = new SearchSlowLog.SearchSlowLogMessage(searchContext, 10);
    assertThat(p.getValueFor("stats"), equalTo("[\\\"group1\\\"]"));
    searchContext = createSearchContext(index, "group1", "group2");
    source = SearchSourceBuilder.searchSource().query(QueryBuilders.matchAllQuery());
    searchContext.request().source(source);
    searchContext.setTask(new SearchShardTask(0, "n/a", "n/a", "test", null, Collections.singletonMap(Task.X_OPAQUE_ID, "my_id")));
    p = new SearchSlowLog.SearchSlowLogMessage(searchContext, 10);
    assertThat(p.getValueFor("stats"), equalTo("[\\\"group1\\\", \\\"group2\\\"]"));
}
Also used : SearchContext(org.opensearch.search.internal.SearchContext) TestSearchContext(org.opensearch.test.TestSearchContext) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) SearchShardTask(org.opensearch.action.search.SearchShardTask)

Example 97 with SearchSourceBuilder

use of org.opensearch.search.builder.SearchSourceBuilder in project OpenSearch by opensearch-project.

the class SearchSlowLogTests method searchContextWithSourceAndTask.

private SearchContext searchContextWithSourceAndTask(IndexService index) {
    SearchContext ctx = createSearchContext(index);
    SearchSourceBuilder source = SearchSourceBuilder.searchSource().query(QueryBuilders.matchAllQuery());
    ctx.request().source(source);
    ctx.setTask(new SearchShardTask(0, "n/a", "n/a", "test", null, Collections.singletonMap(Task.X_OPAQUE_ID, "my_id")));
    return ctx;
}
Also used : SearchContext(org.opensearch.search.internal.SearchContext) TestSearchContext(org.opensearch.test.TestSearchContext) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) SearchShardTask(org.opensearch.action.search.SearchShardTask)

Example 98 with SearchSourceBuilder

use of org.opensearch.search.builder.SearchSourceBuilder in project OpenSearch by opensearch-project.

the class TransportSearchActionTests method testShouldPreFilterSearchShards.

public void testShouldPreFilterSearchShards() {
    int numIndices = randomIntBetween(2, 10);
    String[] indices = new String[numIndices];
    for (int i = 0; i < numIndices; i++) {
        indices[i] = randomAlphaOfLengthBetween(5, 10);
    }
    ClusterState clusterState = ClusterState.builder(ClusterName.DEFAULT).build();
    {
        SearchRequest searchRequest = new SearchRequest();
        assertFalse(TransportSearchAction.shouldPreFilterSearchShards(clusterState, searchRequest, indices, randomIntBetween(2, 128)));
        assertFalse(TransportSearchAction.shouldPreFilterSearchShards(clusterState, searchRequest, indices, randomIntBetween(129, 10000)));
    }
    {
        SearchRequest searchRequest = new SearchRequest().source(new SearchSourceBuilder().query(QueryBuilders.rangeQuery("timestamp")));
        assertFalse(TransportSearchAction.shouldPreFilterSearchShards(clusterState, searchRequest, indices, randomIntBetween(2, 128)));
        assertTrue(TransportSearchAction.shouldPreFilterSearchShards(clusterState, searchRequest, indices, randomIntBetween(129, 10000)));
    }
    {
        SearchRequest searchRequest = new SearchRequest().source(new SearchSourceBuilder().sort(SortBuilders.fieldSort("timestamp")));
        assertTrue(TransportSearchAction.shouldPreFilterSearchShards(clusterState, searchRequest, indices, randomIntBetween(2, 127)));
        assertTrue(TransportSearchAction.shouldPreFilterSearchShards(clusterState, searchRequest, indices, randomIntBetween(127, 10000)));
    }
    {
        SearchRequest searchRequest = new SearchRequest().source(new SearchSourceBuilder().sort(SortBuilders.fieldSort("timestamp"))).scroll("5m");
        assertTrue(TransportSearchAction.shouldPreFilterSearchShards(clusterState, searchRequest, indices, randomIntBetween(2, 128)));
        assertTrue(TransportSearchAction.shouldPreFilterSearchShards(clusterState, searchRequest, indices, randomIntBetween(129, 10000)));
    }
}
Also used : ClusterState(org.opensearch.cluster.ClusterState) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder)

Example 99 with SearchSourceBuilder

use of org.opensearch.search.builder.SearchSourceBuilder in project OpenSearch by opensearch-project.

the class SearchPhaseControllerTests method testConsumerConcurrently.

public void testConsumerConcurrently() throws Exception {
    int expectedNumResults = randomIntBetween(1, 100);
    int bufferSize = randomIntBetween(2, 200);
    SearchRequest request = randomSearchRequest();
    request.source(new SearchSourceBuilder().aggregation(AggregationBuilders.avg("foo")));
    request.setBatchedReduceSize(bufferSize);
    ArraySearchPhaseResults<SearchPhaseResult> consumer = searchPhaseController.newSearchPhaseResults(fixedExecutor, new NoopCircuitBreaker(CircuitBreaker.REQUEST), SearchProgressListener.NOOP, request, expectedNumResults, exc -> {
    });
    AtomicInteger max = new AtomicInteger();
    Thread[] threads = new Thread[expectedNumResults];
    CountDownLatch latch = new CountDownLatch(expectedNumResults);
    for (int i = 0; i < expectedNumResults; i++) {
        int id = i;
        threads[i] = new Thread(() -> {
            int number = randomIntBetween(1, 1000);
            max.updateAndGet(prev -> Math.max(prev, number));
            QuerySearchResult result = new QuerySearchResult(new ShardSearchContextId("", id), new SearchShardTarget("node", new ShardId("a", "b", id), null, OriginalIndices.NONE), null);
            result.topDocs(new TopDocsAndMaxScore(new TopDocs(new TotalHits(1, TotalHits.Relation.EQUAL_TO), new ScoreDoc[] { new ScoreDoc(0, number) }), number), new DocValueFormat[0]);
            InternalAggregations aggs = InternalAggregations.from(Collections.singletonList(new InternalMax("test", (double) number, DocValueFormat.RAW, Collections.emptyMap())));
            result.aggregations(aggs);
            result.setShardIndex(id);
            result.size(1);
            consumer.consumeResult(result, latch::countDown);
        });
        threads[i].start();
    }
    for (int i = 0; i < expectedNumResults; i++) {
        threads[i].join();
    }
    latch.await();
    SearchPhaseController.ReducedQueryPhase reduce = consumer.reduce();
    assertAggReduction(request);
    InternalMax internalMax = (InternalMax) reduce.aggregations.asList().get(0);
    assertEquals(max.get(), internalMax.getValue(), 0.0D);
    assertEquals(1, reduce.sortedTopDocs.scoreDocs.length);
    assertEquals(max.get(), reduce.maxScore, 0.0f);
    assertEquals(expectedNumResults, reduce.totalHits.value);
    assertEquals(max.get(), reduce.sortedTopDocs.scoreDocs[0].score, 0.0f);
    assertFalse(reduce.sortedTopDocs.isSortedByField);
    assertNull(reduce.sortedTopDocs.sortFields);
    assertNull(reduce.sortedTopDocs.collapseField);
    assertNull(reduce.sortedTopDocs.collapseValues);
}
Also used : InternalAggregationTestCase(org.opensearch.test.InternalAggregationTestCase) ScoreDoc(org.apache.lucene.search.ScoreDoc) ShardSearchContextId(org.opensearch.search.internal.ShardSearchContextId) SearchContext(org.opensearch.search.internal.SearchContext) TestThreadPool(org.opensearch.threadpool.TestThreadPool) FieldDoc(org.apache.lucene.search.FieldDoc) CircuitBreaker(org.opensearch.common.breaker.CircuitBreaker) SortBy(org.opensearch.search.suggest.SortBy) Strings(org.opensearch.common.Strings) Collections.singletonList(java.util.Collections.singletonList) InternalMax(org.opensearch.search.aggregations.metrics.InternalMax) CollapseTopFieldDocs(org.apache.lucene.search.grouping.CollapseTopFieldDocs) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) After(org.junit.After) Map(java.util.Map) Lucene(org.opensearch.common.lucene.Lucene) SortField(org.apache.lucene.search.SortField) RandomizedContext(com.carrotsearch.randomizedtesting.RandomizedContext) BytesRef(org.apache.lucene.util.BytesRef) SearchHit(org.opensearch.search.SearchHit) Collections.emptyList(java.util.Collections.emptyList) Matchers.lessThanOrEqualTo(org.hamcrest.Matchers.lessThanOrEqualTo) OpenSearchTestCase(org.opensearch.test.OpenSearchTestCase) Settings(org.opensearch.common.settings.Settings) CompletionSuggestion(org.opensearch.search.suggest.completion.CompletionSuggestion) PhraseSuggestion(org.opensearch.search.suggest.phrase.PhraseSuggestion) Collectors(java.util.stream.Collectors) OriginalIndices(org.opensearch.action.OriginalIndices) OpenSearchThreadPoolExecutor(org.opensearch.common.util.concurrent.OpenSearchThreadPoolExecutor) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Stream(java.util.stream.Stream) SearchPhaseResult(org.opensearch.search.SearchPhaseResult) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Optional(java.util.Optional) TopFieldDocs(org.apache.lucene.search.TopFieldDocs) BigArrays(org.opensearch.common.util.BigArrays) InternalAggregation(org.opensearch.search.aggregations.InternalAggregation) Matchers.containsString(org.hamcrest.Matchers.containsString) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) TermSuggestion(org.opensearch.search.suggest.term.TermSuggestion) DocValueFormat(org.opensearch.search.DocValueFormat) ReduceContext(org.opensearch.search.aggregations.InternalAggregation.ReduceContext) ThreadPool(org.opensearch.threadpool.ThreadPool) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) SearchHits(org.opensearch.search.SearchHits) QuerySearchResult(org.opensearch.search.query.QuerySearchResult) OpenSearchExecutors(org.opensearch.common.util.concurrent.OpenSearchExecutors) AtomicReference(java.util.concurrent.atomic.AtomicReference) NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) ArrayList(java.util.ArrayList) PipelineTree(org.opensearch.search.aggregations.pipeline.PipelineAggregator.PipelineTree) Matchers.lessThan(org.hamcrest.Matchers.lessThan) UUIDs(org.opensearch.common.UUIDs) Before(org.junit.Before) CircuitBreakingException(org.opensearch.common.breaker.CircuitBreakingException) TopDocs(org.apache.lucene.search.TopDocs) NoopCircuitBreaker(org.opensearch.common.breaker.NoopCircuitBreaker) Collections.emptyMap(java.util.Collections.emptyMap) Matchers.greaterThanOrEqualTo(org.hamcrest.Matchers.greaterThanOrEqualTo) Relation(org.apache.lucene.search.TotalHits.Relation) InternalSearchResponse(org.opensearch.search.internal.InternalSearchResponse) TotalHits(org.apache.lucene.search.TotalHits) ShardId(org.opensearch.index.shard.ShardId) AggregationBuilders(org.opensearch.search.aggregations.AggregationBuilders) AtomicArray(org.opensearch.common.util.concurrent.AtomicArray) SearchShardTarget(org.opensearch.search.SearchShardTarget) TopDocsAndMaxScore(org.opensearch.common.lucene.search.TopDocsAndMaxScore) Suggest(org.opensearch.search.suggest.Suggest) FetchSearchResult(org.opensearch.search.fetch.FetchSearchResult) Collections(java.util.Collections) Text(org.opensearch.common.text.Text) SearchModule(org.opensearch.search.SearchModule) TotalHits(org.apache.lucene.search.TotalHits) InternalMax(org.opensearch.search.aggregations.metrics.InternalMax) DocValueFormat(org.opensearch.search.DocValueFormat) CountDownLatch(java.util.concurrent.CountDownLatch) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) TopDocsAndMaxScore(org.opensearch.common.lucene.search.TopDocsAndMaxScore) ScoreDoc(org.apache.lucene.search.ScoreDoc) ShardId(org.opensearch.index.shard.ShardId) TopDocs(org.apache.lucene.search.TopDocs) ShardSearchContextId(org.opensearch.search.internal.ShardSearchContextId) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) QuerySearchResult(org.opensearch.search.query.QuerySearchResult) SearchPhaseResult(org.opensearch.search.SearchPhaseResult) SearchShardTarget(org.opensearch.search.SearchShardTarget) NoopCircuitBreaker(org.opensearch.common.breaker.NoopCircuitBreaker)

Example 100 with SearchSourceBuilder

use of org.opensearch.search.builder.SearchSourceBuilder in project OpenSearch by opensearch-project.

the class SearchPhaseControllerTests method testConsumerOnlyAggs.

public void testConsumerOnlyAggs() throws Exception {
    int expectedNumResults = randomIntBetween(1, 100);
    int bufferSize = randomIntBetween(2, 200);
    SearchRequest request = randomSearchRequest();
    request.source(new SearchSourceBuilder().aggregation(AggregationBuilders.avg("foo")).size(0));
    request.setBatchedReduceSize(bufferSize);
    QueryPhaseResultConsumer consumer = searchPhaseController.newSearchPhaseResults(fixedExecutor, new NoopCircuitBreaker(CircuitBreaker.REQUEST), SearchProgressListener.NOOP, request, expectedNumResults, exc -> {
    });
    AtomicInteger max = new AtomicInteger();
    CountDownLatch latch = new CountDownLatch(expectedNumResults);
    for (int i = 0; i < expectedNumResults; i++) {
        int number = randomIntBetween(1, 1000);
        max.updateAndGet(prev -> Math.max(prev, number));
        QuerySearchResult result = new QuerySearchResult(new ShardSearchContextId("", i), new SearchShardTarget("node", new ShardId("a", "b", i), null, OriginalIndices.NONE), null);
        result.topDocs(new TopDocsAndMaxScore(new TopDocs(new TotalHits(1, TotalHits.Relation.EQUAL_TO), new ScoreDoc[0]), number), new DocValueFormat[0]);
        InternalAggregations aggs = InternalAggregations.from(Collections.singletonList(new InternalMax("test", (double) number, DocValueFormat.RAW, Collections.emptyMap())));
        result.aggregations(aggs);
        result.setShardIndex(i);
        result.size(1);
        consumer.consumeResult(result, latch::countDown);
    }
    latch.await();
    SearchPhaseController.ReducedQueryPhase reduce = consumer.reduce();
    assertAggReduction(request);
    InternalMax internalMax = (InternalMax) reduce.aggregations.asList().get(0);
    assertEquals(max.get(), internalMax.getValue(), 0.0D);
    assertEquals(0, reduce.sortedTopDocs.scoreDocs.length);
    assertEquals(max.get(), reduce.maxScore, 0.0f);
    assertEquals(expectedNumResults, reduce.totalHits.value);
    assertFalse(reduce.sortedTopDocs.isSortedByField);
    assertNull(reduce.sortedTopDocs.sortFields);
    assertNull(reduce.sortedTopDocs.collapseField);
    assertNull(reduce.sortedTopDocs.collapseValues);
}
Also used : TotalHits(org.apache.lucene.search.TotalHits) InternalMax(org.opensearch.search.aggregations.metrics.InternalMax) CountDownLatch(java.util.concurrent.CountDownLatch) SearchSourceBuilder(org.opensearch.search.builder.SearchSourceBuilder) TopDocsAndMaxScore(org.opensearch.common.lucene.search.TopDocsAndMaxScore) ShardId(org.opensearch.index.shard.ShardId) TopDocs(org.apache.lucene.search.TopDocs) ShardSearchContextId(org.opensearch.search.internal.ShardSearchContextId) InternalAggregations(org.opensearch.search.aggregations.InternalAggregations) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) QuerySearchResult(org.opensearch.search.query.QuerySearchResult) SearchShardTarget(org.opensearch.search.SearchShardTarget) NoopCircuitBreaker(org.opensearch.common.breaker.NoopCircuitBreaker)

Aggregations

SearchSourceBuilder (org.opensearch.search.builder.SearchSourceBuilder)309 SearchRequest (org.opensearch.action.search.SearchRequest)150 SearchResponse (org.opensearch.action.search.SearchResponse)133 ArrayList (java.util.ArrayList)56 ActionListener (org.opensearch.action.ActionListener)51 IOException (java.io.IOException)49 List (java.util.List)49 BoolQueryBuilder (org.opensearch.index.query.BoolQueryBuilder)47 Map (java.util.Map)42 HashMap (java.util.HashMap)38 OpenSearchAssertions.assertSearchResponse (org.opensearch.test.hamcrest.OpenSearchAssertions.assertSearchResponse)36 Client (org.opensearch.client.Client)35 LogManager (org.apache.logging.log4j.LogManager)34 Logger (org.apache.logging.log4j.Logger)34 AnomalyDetector (org.opensearch.ad.model.AnomalyDetector)34 Optional (java.util.Optional)32 ClusterService (org.opensearch.cluster.service.ClusterService)32 TermQueryBuilder (org.opensearch.index.query.TermQueryBuilder)32 Collectors (java.util.stream.Collectors)31 MultiSearchRequest (org.opensearch.action.search.MultiSearchRequest)30