Search in sources :

Example 1 with BoolQueryBuilder

use of org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.BoolQueryBuilder in project elasticsearch by elastic.

the class ContextAndHeaderTransportIT method testThatTermsLookupGetRequestContainsContextAndHeaders.

public void testThatTermsLookupGetRequestContainsContextAndHeaders() throws Exception {
    transportClient().prepareIndex(lookupIndex, "type", "1").setSource(jsonBuilder().startObject().array("followers", "foo", "bar", "baz").endObject()).get();
    transportClient().prepareIndex(queryIndex, "type", "1").setSource(jsonBuilder().startObject().field("username", "foo").endObject()).get();
    transportClient().admin().indices().prepareRefresh(queryIndex, lookupIndex).get();
    TermsLookup termsLookup = new TermsLookup(lookupIndex, "type", "1", "followers");
    TermsQueryBuilder termsLookupFilterBuilder = QueryBuilders.termsLookupQuery("username", termsLookup);
    BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery().must(QueryBuilders.matchAllQuery()).must(termsLookupFilterBuilder);
    SearchResponse searchResponse = transportClient().prepareSearch(queryIndex).setQuery(queryBuilder).get();
    assertNoFailures(searchResponse);
    assertHitCount(searchResponse, 1);
    assertGetRequestsContainHeaders();
}
Also used : BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) TermsQueryBuilder(org.elasticsearch.index.query.TermsQueryBuilder) TermsLookup(org.elasticsearch.indices.TermsLookup) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Example 2 with BoolQueryBuilder

use of org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.BoolQueryBuilder in project elasticsearch by elastic.

the class ShardSearchRequest method parseAliasFilter.

/**
     * Returns the filter associated with listed filtering aliases.
     * <p>
     * The list of filtering aliases should be obtained by calling MetaData.filteringAliases.
     * Returns <tt>null</tt> if no filtering is required.</p>
     */
static QueryBuilder parseAliasFilter(CheckedFunction<byte[], QueryBuilder, IOException> filterParser, IndexMetaData metaData, String... aliasNames) {
    if (aliasNames == null || aliasNames.length == 0) {
        return null;
    }
    Index index = metaData.getIndex();
    ImmutableOpenMap<String, AliasMetaData> aliases = metaData.getAliases();
    Function<AliasMetaData, QueryBuilder> parserFunction = (alias) -> {
        if (alias.filter() == null) {
            return null;
        }
        try {
            return filterParser.apply(alias.filter().uncompressed());
        } catch (IOException ex) {
            throw new AliasFilterParsingException(index, alias.getAlias(), "Invalid alias filter", ex);
        }
    };
    if (aliasNames.length == 1) {
        AliasMetaData alias = aliases.get(aliasNames[0]);
        if (alias == null) {
            // This shouldn't happen unless alias disappeared after filteringAliases was called.
            throw new InvalidAliasNameException(index, aliasNames[0], "Unknown alias name was passed to alias Filter");
        }
        return parserFunction.apply(alias);
    } else {
        // we need to bench here a bit, to see maybe it makes sense to use OrFilter
        BoolQueryBuilder combined = new BoolQueryBuilder();
        for (String aliasName : aliasNames) {
            AliasMetaData alias = aliases.get(aliasName);
            if (alias == null) {
                // This shouldn't happen unless alias disappeared after filteringAliases was called.
                throw new InvalidAliasNameException(index, aliasNames[0], "Unknown alias name was passed to alias Filter");
            }
            QueryBuilder parsedFilter = parserFunction.apply(alias);
            if (parsedFilter != null) {
                combined.should(parsedFilter);
            } else {
                // The filter might be null only if filter was removed after filteringAliases was called
                return null;
            }
        }
        return combined;
    }
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) SearchType(org.elasticsearch.action.search.SearchType) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap) QueryShardContext(org.elasticsearch.index.query.QueryShardContext) AliasMetaData(org.elasticsearch.cluster.metadata.AliasMetaData) Scroll(org.elasticsearch.search.Scroll) IOException(java.io.IOException) Index(org.elasticsearch.index.Index) BytesReference(org.elasticsearch.common.bytes.BytesReference) Function(java.util.function.Function) CheckedFunction(org.elasticsearch.common.CheckedFunction) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) AliasFilterParsingException(org.elasticsearch.indices.AliasFilterParsingException) InvalidAliasNameException(org.elasticsearch.indices.InvalidAliasNameException) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) AliasMetaData(org.elasticsearch.cluster.metadata.AliasMetaData) AliasFilterParsingException(org.elasticsearch.indices.AliasFilterParsingException) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) Index(org.elasticsearch.index.Index) IOException(java.io.IOException) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) InvalidAliasNameException(org.elasticsearch.indices.InvalidAliasNameException)

Example 3 with BoolQueryBuilder

use of org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.BoolQueryBuilder 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 BoolQueryBuilder

use of org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.BoolQueryBuilder in project elasticsearch by elastic.

the class SearchQueryIT method testBoolQueryMinShouldMatchBiggerThanNumberOfShouldClauses.

public void testBoolQueryMinShouldMatchBiggerThanNumberOfShouldClauses() throws IOException {
    createIndex("test");
    client().prepareIndex("test", "type1", "1").setSource("field1", new String[] { "value1", "value2", "value3" }).get();
    client().prepareIndex("test", "type1", "2").setSource("field2", "value1").get();
    refresh();
    BoolQueryBuilder boolQuery = boolQuery().must(termQuery("field1", "value1")).should(boolQuery().should(termQuery("field1", "value1")).should(termQuery("field1", "value2")).minimumShouldMatch(3));
    SearchResponse searchResponse = client().prepareSearch().setQuery(boolQuery).get();
    assertHitCount(searchResponse, 1L);
    assertFirstHit(searchResponse, hasId("1"));
    boolQuery = boolQuery().must(termQuery("field1", "value1")).should(boolQuery().should(termQuery("field1", "value1")).should(termQuery("field1", "value2")).minimumShouldMatch(1)).minimumShouldMatch(2);
    searchResponse = client().prepareSearch().setQuery(boolQuery).get();
    assertHitCount(searchResponse, 0L);
    boolQuery = boolQuery().should(termQuery("field1", "value1")).should(boolQuery().should(termQuery("field1", "value1")).should(termQuery("field1", "value2")).minimumShouldMatch(3)).minimumShouldMatch(1);
    searchResponse = client().prepareSearch().setQuery(boolQuery).get();
    assertHitCount(searchResponse, 1L);
    assertFirstHit(searchResponse, hasId("1"));
    boolQuery = boolQuery().must(termQuery("field1", "value1")).must(boolQuery().should(termQuery("field1", "value1")).should(termQuery("field1", "value2")).minimumShouldMatch(3));
    searchResponse = client().prepareSearch().setQuery(boolQuery).get();
    assertHitCount(searchResponse, 0L);
}
Also used : BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) Matchers.containsString(org.hamcrest.Matchers.containsString) SearchResponse(org.elasticsearch.action.search.SearchResponse) ElasticsearchAssertions.assertSearchResponse(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)

Example 5 with BoolQueryBuilder

use of org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.BoolQueryBuilder in project elasticsearch by elastic.

the class SearchQueryIT method testMultiMatchQueryZeroTermsQuery.

public void testMultiMatchQueryZeroTermsQuery() {
    assertAcked(prepareCreate("test").addMapping("type1", "field1", "type=text,analyzer=classic", "field2", "type=text,analyzer=classic"));
    client().prepareIndex("test", "type1", "1").setSource("field1", "value1", "field2", "value2").get();
    client().prepareIndex("test", "type1", "2").setSource("field1", "value3", "field2", "value4").get();
    refresh();
    BoolQueryBuilder boolQuery = boolQuery().must(multiMatchQuery("a", "field1", "field2").zeroTermsQuery(MatchQuery.ZeroTermsQuery.NONE)).must(// Fields are ORed together
    multiMatchQuery("value1", "field1", "field2").zeroTermsQuery(MatchQuery.ZeroTermsQuery.NONE));
    SearchResponse searchResponse = client().prepareSearch().setQuery(boolQuery).get();
    assertHitCount(searchResponse, 0L);
    boolQuery = boolQuery().must(multiMatchQuery("a", "field1", "field2").zeroTermsQuery(MatchQuery.ZeroTermsQuery.ALL)).must(multiMatchQuery("value4", "field1", "field2").zeroTermsQuery(MatchQuery.ZeroTermsQuery.ALL));
    searchResponse = client().prepareSearch().setQuery(boolQuery).get();
    assertHitCount(searchResponse, 1L);
    boolQuery = boolQuery().must(multiMatchQuery("a", "field1").zeroTermsQuery(MatchQuery.ZeroTermsQuery.ALL));
    searchResponse = client().prepareSearch().setQuery(boolQuery).get();
    assertHitCount(searchResponse, 2L);
}
Also used : BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) SearchResponse(org.elasticsearch.action.search.SearchResponse) ElasticsearchAssertions.assertSearchResponse(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)

Aggregations

BoolQueryBuilder (org.elasticsearch.index.query.BoolQueryBuilder)189 SearchResponse (org.elasticsearch.action.search.SearchResponse)67 QueryBuilder (org.elasticsearch.index.query.QueryBuilder)57 SearchHit (org.elasticsearch.search.SearchHit)40 SearchRequestBuilder (org.elasticsearch.action.search.SearchRequestBuilder)38 Map (java.util.Map)28 ArrayList (java.util.ArrayList)26 HashMap (java.util.HashMap)23 List (java.util.List)23 SearchSourceBuilder (org.elasticsearch.search.builder.SearchSourceBuilder)23 Test (org.junit.Test)18 SearchRequest (org.elasticsearch.action.search.SearchRequest)15 RangeQueryBuilder (org.elasticsearch.index.query.RangeQueryBuilder)15 TermsAggregationBuilder (org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder)15 QueryBuilders (org.elasticsearch.index.query.QueryBuilders)13 FilterAggregationBuilder (org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder)13 LinkedList (java.util.LinkedList)11 FieldSortBuilder (org.elasticsearch.search.sort.FieldSortBuilder)11 Logger (org.slf4j.Logger)11 LoggerFactory (org.slf4j.LoggerFactory)11