Search in sources :

Example 6 with SearchContext

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

the class MockSearchServiceTests method testAssertNoInFlightContext.

public void testAssertNoInFlightContext() {
    final long nowInMillis = randomNonNegativeLong();
    SearchContext s = new TestSearchContext(new QueryShardContext(0, new IndexSettings(EMPTY_INDEX_METADATA, Settings.EMPTY), null, null, null, null, null, xContentRegistry(), null, null, () -> nowInMillis)) {

        @Override
        public SearchShardTarget shardTarget() {
            return new SearchShardTarget("node", new Index("idx", "ignored"), 0);
        }

        @Override
        public SearchType searchType() {
            return SearchType.DEFAULT;
        }

        @Override
        public Query query() {
            return Queries.newMatchAllQuery();
        }
    };
    MockSearchService.addActiveContext(s);
    try {
        Throwable e = expectThrows(AssertionError.class, () -> MockSearchService.assertNoInFlightContext());
        assertEquals("There are still [1] in-flight contexts. The first one's creation site is listed as the cause of this exception.", e.getMessage());
        e = e.getCause();
        // The next line with throw an exception if the date looks wrong
        assertEquals("[node][idx][0] query=[*:*]", e.getMessage());
        assertEquals(MockSearchService.class.getName(), e.getStackTrace()[0].getClassName());
        assertEquals(MockSearchServiceTests.class.getName(), e.getStackTrace()[1].getClassName());
    } finally {
        MockSearchService.removeActiveContext(s);
    }
}
Also used : TestSearchContext(org.elasticsearch.test.TestSearchContext) IndexSettings(org.elasticsearch.index.IndexSettings) SearchContext(org.elasticsearch.search.internal.SearchContext) TestSearchContext(org.elasticsearch.test.TestSearchContext) QueryShardContext(org.elasticsearch.index.query.QueryShardContext) Index(org.elasticsearch.index.Index)

Example 7 with SearchContext

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

the class AbstractQueryTestCase method testToQuery.

/**
     * Test creates the {@link Query} from the {@link QueryBuilder} under test and delegates the
     * assertions being made on the result to the implementing subclass.
     */
public void testToQuery() throws IOException {
    for (int runs = 0; runs < NUMBER_OF_TESTQUERIES; runs++) {
        QueryShardContext context = createShardContext();
        assert context.isCachable();
        context.setAllowUnmappedFields(true);
        QB firstQuery = createTestQueryBuilder();
        QB controlQuery = copyQuery(firstQuery);
        SearchContext searchContext = getSearchContext(randomTypes, context);
        /* we use a private rewrite context here since we want the most realistic way of asserting that we are cacheable or not.
             * We do it this way in SearchService where
             * we first rewrite the query with a private context, then reset the context and then build the actual lucene query*/
        QueryBuilder rewritten = rewriteQuery(firstQuery, new QueryShardContext(context));
        Query firstLuceneQuery = rewritten.toQuery(context);
        if (isCachable(firstQuery)) {
            assertTrue("query was marked as not cacheable in the context but this test indicates it should be cacheable: " + firstQuery.toString(), context.isCachable());
        } else {
            assertFalse("query was marked as cacheable in the context but this test indicates it should not be cacheable: " + firstQuery.toString(), context.isCachable());
        }
        assertNotNull("toQuery should not return null", firstLuceneQuery);
        assertLuceneQuery(firstQuery, firstLuceneQuery, searchContext);
        //remove after assertLuceneQuery since the assertLuceneQuery impl might access the context as well
        assertTrue("query is not equal to its copy after calling toQuery, firstQuery: " + firstQuery + ", secondQuery: " + controlQuery, firstQuery.equals(controlQuery));
        assertTrue("equals is not symmetric after calling toQuery, firstQuery: " + firstQuery + ", secondQuery: " + controlQuery, controlQuery.equals(firstQuery));
        assertThat("query copy's hashcode is different from original hashcode after calling toQuery, firstQuery: " + firstQuery + ", secondQuery: " + controlQuery, controlQuery.hashCode(), equalTo(firstQuery.hashCode()));
        QB secondQuery = copyQuery(firstQuery);
        // query _name never should affect the result of toQuery, we randomly set it to make sure
        if (randomBoolean()) {
            secondQuery.queryName(secondQuery.queryName() == null ? randomAsciiOfLengthBetween(1, 30) : secondQuery.queryName() + randomAsciiOfLengthBetween(1, 10));
        }
        searchContext = getSearchContext(randomTypes, context);
        Query secondLuceneQuery = rewriteQuery(secondQuery, context).toQuery(context);
        assertNotNull("toQuery should not return null", secondLuceneQuery);
        assertLuceneQuery(secondQuery, secondLuceneQuery, searchContext);
        if (builderGeneratesCacheableQueries()) {
            assertEquals("two equivalent query builders lead to different lucene queries", rewrite(secondLuceneQuery), rewrite(firstLuceneQuery));
        }
        if (supportsBoostAndQueryName()) {
            secondQuery.boost(firstQuery.boost() + 1f + randomFloat());
            Query thirdLuceneQuery = rewriteQuery(secondQuery, context).toQuery(context);
            assertNotEquals("modifying the boost doesn't affect the corresponding lucene query", rewrite(firstLuceneQuery), rewrite(thirdLuceneQuery));
        }
        // check that context#isFilter is not changed by invoking toQuery/rewrite
        boolean filterFlag = randomBoolean();
        context.setIsFilter(filterFlag);
        rewriteQuery(firstQuery, context).toQuery(context);
        assertEquals("isFilter should be unchanged", filterFlag, context.isFilter());
    }
}
Also used : Query(org.apache.lucene.search.Query) SpanBoostQuery(org.apache.lucene.search.spans.SpanBoostQuery) BoostQuery(org.apache.lucene.search.BoostQuery) TermQuery(org.apache.lucene.search.TermQuery) QueryShardContext(org.elasticsearch.index.query.QueryShardContext) SearchContext(org.elasticsearch.search.internal.SearchContext) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) AbstractQueryBuilder(org.elasticsearch.index.query.AbstractQueryBuilder)

Example 8 with SearchContext

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

the class IndexModuleTests method testAddSearchOperationListener.

public void testAddSearchOperationListener() throws IOException {
    IndexModule module = new IndexModule(IndexSettingsModule.newIndexSettings(index, settings), new AnalysisRegistry(environment, emptyMap(), emptyMap(), emptyMap(), emptyMap(), emptyMap()));
    AtomicBoolean executed = new AtomicBoolean(false);
    SearchOperationListener listener = new SearchOperationListener() {

        @Override
        public void onNewContext(SearchContext context) {
            executed.set(true);
        }
    };
    module.addSearchOperationListener(listener);
    expectThrows(IllegalArgumentException.class, () -> module.addSearchOperationListener(listener));
    expectThrows(IllegalArgumentException.class, () -> module.addSearchOperationListener(null));
    IndexService indexService = newIndexService(module);
    assertEquals(2, indexService.getSearchOperationListener().size());
    assertEquals(SearchSlowLog.class, indexService.getSearchOperationListener().get(0).getClass());
    assertSame(listener, indexService.getSearchOperationListener().get(1));
    for (SearchOperationListener l : indexService.getSearchOperationListener()) {
        l.onNewContext(new TestSearchContext(null));
    }
    assertTrue(executed.get());
    indexService.close("simon says", false);
}
Also used : AnalysisRegistry(org.elasticsearch.index.analysis.AnalysisRegistry) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TestSearchContext(org.elasticsearch.test.TestSearchContext) TestSearchContext(org.elasticsearch.test.TestSearchContext) SearchContext(org.elasticsearch.search.internal.SearchContext) SearchOperationListener(org.elasticsearch.index.shard.SearchOperationListener)

Example 9 with SearchContext

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

the class SearchSlowLogTests method testSlowLogSearchContextPrinterToLog.

public void testSlowLogSearchContextPrinterToLog() throws IOException {
    IndexService index = createIndex("foo");
    SearchContext searchContext = createSearchContext(index);
    SearchSourceBuilder source = SearchSourceBuilder.searchSource().query(QueryBuilders.matchAllQuery());
    searchContext.request().source(source);
    SearchSlowLog.SlowLogSearchContextPrinter p = new SearchSlowLog.SlowLogSearchContextPrinter(searchContext, 10);
    assertThat(p.toString(), startsWith("[foo][0]"));
    // Makes sure that output doesn't contain any new lines
    assertThat(p.toString(), not(containsString("\n")));
}
Also used : SearchContext(org.elasticsearch.search.internal.SearchContext) TestSearchContext(org.elasticsearch.test.TestSearchContext) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder)

Example 10 with SearchContext

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

the class InnerHitBuilderTests method testBuild_ignoreUnmappedHasChildQuery.

public void testBuild_ignoreUnmappedHasChildQuery() throws Exception {
    QueryShardContext queryShardContext = mock(QueryShardContext.class);
    when(queryShardContext.documentMapper("type")).thenReturn(null);
    SearchContext searchContext = mock(SearchContext.class);
    when(searchContext.getQueryShardContext()).thenReturn(queryShardContext);
    InnerHitBuilder leafInnerHits = randomInnerHits();
    HasChildQueryBuilder query1 = new HasChildQueryBuilder("type", new MatchAllQueryBuilder(), ScoreMode.None).innerHit(leafInnerHits, false);
    expectThrows(IllegalStateException.class, () -> query1.innerHit().build(searchContext, new InnerHitsContext()));
    HasChildQueryBuilder query2 = new HasChildQueryBuilder("type", new MatchAllQueryBuilder(), ScoreMode.None).innerHit(leafInnerHits, true);
    InnerHitsContext innerHitsContext = new InnerHitsContext();
    query2.innerHit().build(searchContext, innerHitsContext);
    assertThat(innerHitsContext.getInnerHits().size(), equalTo(0));
}
Also used : SearchContext(org.elasticsearch.search.internal.SearchContext) InnerHitsContext(org.elasticsearch.search.fetch.subphase.InnerHitsContext)

Aggregations

SearchContext (org.elasticsearch.search.internal.SearchContext)33 IOException (java.io.IOException)11 ElasticsearchException (org.elasticsearch.ElasticsearchException)7 ExecutionException (java.util.concurrent.ExecutionException)6 IndexSearcher (org.apache.lucene.search.IndexSearcher)6 SearchOperationListener (org.elasticsearch.index.shard.SearchOperationListener)6 AggregationInitializationException (org.elasticsearch.search.aggregations.AggregationInitializationException)6 TestSearchContext (org.elasticsearch.test.TestSearchContext)6 ArrayList (java.util.ArrayList)5 FetchSubPhase (org.elasticsearch.search.fetch.FetchSubPhase)5 Term (org.apache.lucene.index.Term)4 Encoder (org.apache.lucene.search.highlight.Encoder)4 FieldMapper (org.elasticsearch.index.mapper.FieldMapper)4 QueryShardContext (org.elasticsearch.index.query.QueryShardContext)4 FetchPhaseExecutionException (org.elasticsearch.search.fetch.FetchPhaseExecutionException)4 Analyzer (org.apache.lucene.analysis.Analyzer)3 TermQuery (org.apache.lucene.search.TermQuery)3 InnerHitsContext (org.elasticsearch.search.fetch.subphase.InnerHitsContext)3 Document (org.apache.lucene.document.Document)2 IndexReader (org.apache.lucene.index.IndexReader)2