Search in sources :

Example 1 with MatchAllQueryBuilder

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

the class FunctionScoreQueryBuilder method parseFiltersAndFunctions.

private static String parseFiltersAndFunctions(QueryParseContext parseContext, List<FunctionScoreQueryBuilder.FilterFunctionBuilder> filterFunctionBuilders) throws IOException {
    String currentFieldName = null;
    XContentParser.Token token;
    XContentParser parser = parseContext.parser();
    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
        QueryBuilder filter = null;
        ScoreFunctionBuilder<?> scoreFunction = null;
        Float functionWeight = null;
        if (token != XContentParser.Token.START_OBJECT) {
            throw new ParsingException(parser.getTokenLocation(), "failed to parse [{}]. malformed query, expected a [{}] while parsing functions but got a [{}] instead", XContentParser.Token.START_OBJECT, token, NAME);
        } else {
            while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                if (token == XContentParser.Token.FIELD_NAME) {
                    currentFieldName = parser.currentName();
                } else if (token == XContentParser.Token.START_OBJECT) {
                    if (FILTER_FIELD.match(currentFieldName)) {
                        filter = parseContext.parseInnerQueryBuilder();
                    } else {
                        if (scoreFunction != null) {
                            throw new ParsingException(parser.getTokenLocation(), "failed to parse function_score functions. already found [{}], now encountering [{}].", scoreFunction.getName(), currentFieldName);
                        }
                        scoreFunction = parser.namedObject(ScoreFunctionBuilder.class, currentFieldName, parseContext);
                    }
                } else if (token.isValue()) {
                    if (WEIGHT_FIELD.match(currentFieldName)) {
                        functionWeight = parser.floatValue();
                    } else {
                        throw new ParsingException(parser.getTokenLocation(), "failed to parse [{}] query. field [{}] is not supported", NAME, currentFieldName);
                    }
                }
            }
            if (functionWeight != null) {
                if (scoreFunction == null) {
                    scoreFunction = new WeightBuilder().setWeight(functionWeight);
                } else {
                    scoreFunction.setWeight(functionWeight);
                }
            }
        }
        if (filter == null) {
            filter = new MatchAllQueryBuilder();
        }
        if (scoreFunction == null) {
            throw new ParsingException(parser.getTokenLocation(), "failed to parse [{}] query. an entry in functions list is missing a function.", NAME);
        }
        filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(filter, scoreFunction));
    }
    return currentFieldName;
}
Also used : ParsingException(org.elasticsearch.common.ParsingException) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) AbstractQueryBuilder(org.elasticsearch.index.query.AbstractQueryBuilder) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder) XContentParser(org.elasticsearch.common.xcontent.XContentParser) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder)

Example 2 with MatchAllQueryBuilder

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

the class TemplateQueryBuilderTests method testMustRewrite.

@Override
public void testMustRewrite() throws IOException {
    String query = "{ \"match_all\" : {}}";
    QueryBuilder builder = new TemplateQueryBuilder(new Script(ScriptType.INLINE, "mockscript", query, Collections.singletonMap(Script.CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()), Collections.emptyMap()));
    try {
        builder.toQuery(createShardContext());
        fail();
    } catch (UnsupportedOperationException ex) {
        assertEquals("this query must be rewritten first", ex.getMessage());
    }
    assertEquals(new MatchAllQueryBuilder(), builder.rewrite(createShardContext()));
}
Also used : Script(org.elasticsearch.script.Script) Matchers.containsString(org.hamcrest.Matchers.containsString) MatchQueryBuilder(org.elasticsearch.index.query.MatchQueryBuilder) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) TermQueryBuilder(org.elasticsearch.index.query.TermQueryBuilder) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder)

Example 3 with MatchAllQueryBuilder

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

the class NestedHelperTests method testNested.

public void testNested() throws IOException {
    QueryShardContext context = indexService.newQueryShardContext(0, new MultiReader(), () -> 0);
    NestedQueryBuilder queryBuilder = new NestedQueryBuilder("nested1", new MatchAllQueryBuilder(), ScoreMode.Avg);
    ESToParentBlockJoinQuery query = (ESToParentBlockJoinQuery) queryBuilder.toQuery(context);
    Query expectedChildQuery = new BooleanQuery.Builder().add(new MatchAllDocsQuery(), Occur.MUST).add(new TermQuery(new Term("_type", "__nested1")), Occur.FILTER).build();
    assertEquals(expectedChildQuery, query.getChildQuery());
    assertFalse(new NestedHelper(mapperService).mightMatchNestedDocs(query));
    assertTrue(new NestedHelper(mapperService).mightMatchNonNestedDocs(query, "nested1"));
    assertTrue(new NestedHelper(mapperService).mightMatchNonNestedDocs(query, "nested2"));
    assertTrue(new NestedHelper(mapperService).mightMatchNonNestedDocs(query, "nested3"));
    assertTrue(new NestedHelper(mapperService).mightMatchNonNestedDocs(query, "nested_missing"));
    queryBuilder = new NestedQueryBuilder("nested1", new TermQueryBuilder("nested1.foo", "bar"), ScoreMode.Avg);
    query = (ESToParentBlockJoinQuery) queryBuilder.toQuery(context);
    // this time we do not add a filter since the inner query only matches inner docs
    expectedChildQuery = new TermQuery(new Term("nested1.foo", "bar"));
    assertEquals(expectedChildQuery, query.getChildQuery());
    assertFalse(new NestedHelper(mapperService).mightMatchNestedDocs(query));
    assertTrue(new NestedHelper(mapperService).mightMatchNonNestedDocs(query, "nested1"));
    assertTrue(new NestedHelper(mapperService).mightMatchNonNestedDocs(query, "nested2"));
    assertTrue(new NestedHelper(mapperService).mightMatchNonNestedDocs(query, "nested3"));
    assertTrue(new NestedHelper(mapperService).mightMatchNonNestedDocs(query, "nested_missing"));
    queryBuilder = new NestedQueryBuilder("nested2", new TermQueryBuilder("nested2.foo", "bar"), ScoreMode.Avg);
    query = (ESToParentBlockJoinQuery) queryBuilder.toQuery(context);
    // we need to add the filter again because of include_in_parent
    expectedChildQuery = new BooleanQuery.Builder().add(new TermQuery(new Term("nested2.foo", "bar")), Occur.MUST).add(new TermQuery(new Term("_type", "__nested2")), Occur.FILTER).build();
    assertEquals(expectedChildQuery, query.getChildQuery());
    assertFalse(new NestedHelper(mapperService).mightMatchNestedDocs(query));
    assertTrue(new NestedHelper(mapperService).mightMatchNonNestedDocs(query, "nested1"));
    assertTrue(new NestedHelper(mapperService).mightMatchNonNestedDocs(query, "nested2"));
    assertTrue(new NestedHelper(mapperService).mightMatchNonNestedDocs(query, "nested3"));
    assertTrue(new NestedHelper(mapperService).mightMatchNonNestedDocs(query, "nested_missing"));
    queryBuilder = new NestedQueryBuilder("nested3", new TermQueryBuilder("nested3.foo", "bar"), ScoreMode.Avg);
    query = (ESToParentBlockJoinQuery) queryBuilder.toQuery(context);
    // we need to add the filter again because of include_in_root
    expectedChildQuery = new BooleanQuery.Builder().add(new TermQuery(new Term("nested3.foo", "bar")), Occur.MUST).add(new TermQuery(new Term("_type", "__nested3")), Occur.FILTER).build();
    assertEquals(expectedChildQuery, query.getChildQuery());
    assertFalse(new NestedHelper(mapperService).mightMatchNestedDocs(query));
    assertTrue(new NestedHelper(mapperService).mightMatchNonNestedDocs(query, "nested1"));
    assertTrue(new NestedHelper(mapperService).mightMatchNonNestedDocs(query, "nested2"));
    assertTrue(new NestedHelper(mapperService).mightMatchNonNestedDocs(query, "nested3"));
    assertTrue(new NestedHelper(mapperService).mightMatchNonNestedDocs(query, "nested_missing"));
}
Also used : BooleanQuery(org.apache.lucene.search.BooleanQuery) TermQuery(org.apache.lucene.search.TermQuery) Query(org.apache.lucene.search.Query) MatchNoDocsQuery(org.apache.lucene.search.MatchNoDocsQuery) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) TermQuery(org.apache.lucene.search.TermQuery) BooleanQuery(org.apache.lucene.search.BooleanQuery) MultiReader(org.apache.lucene.index.MultiReader) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) NestedQueryBuilder(org.elasticsearch.index.query.NestedQueryBuilder) TermQueryBuilder(org.elasticsearch.index.query.TermQueryBuilder) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder) Term(org.apache.lucene.index.Term) TermQueryBuilder(org.elasticsearch.index.query.TermQueryBuilder) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) NestedQueryBuilder(org.elasticsearch.index.query.NestedQueryBuilder) QueryShardContext(org.elasticsearch.index.query.QueryShardContext) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder)

Example 4 with MatchAllQueryBuilder

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

the class FunctionScoreIT method testMinScoreFunctionScoreBasic.

public void testMinScoreFunctionScoreBasic() throws IOException {
    index(INDEX, TYPE, jsonBuilder().startObject().field("num", 2).endObject());
    refresh();
    float score = randomFloat();
    float minScore = randomFloat();
    index(INDEX, TYPE, jsonBuilder().startObject().field("num", 2).field("random_score", // Pass the random score as a document field so that it can be extracted in the script
    score).endObject());
    refresh();
    ensureYellow();
    Script script = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "doc['random_score']", Collections.emptyMap());
    SearchResponse searchResponse = client().search(searchRequest().source(searchSource().query(functionScoreQuery(scriptFunction(script)).setMinScore(minScore)))).actionGet();
    if (score < minScore) {
        assertThat(searchResponse.getHits().getTotalHits(), is(0L));
    } else {
        assertThat(searchResponse.getHits().getTotalHits(), is(1L));
    }
    searchResponse = client().search(searchRequest().source(searchSource().query(functionScoreQuery(new MatchAllQueryBuilder(), new FilterFunctionBuilder[] { new FilterFunctionBuilder(scriptFunction(script)), new FilterFunctionBuilder(scriptFunction(script)) }).scoreMode(FiltersFunctionScoreQuery.ScoreMode.AVG).setMinScore(minScore)))).actionGet();
    if (score < minScore) {
        assertThat(searchResponse.getHits().getTotalHits(), is(0L));
    } else {
        assertThat(searchResponse.getHits().getTotalHits(), is(1L));
    }
}
Also used : Script(org.elasticsearch.script.Script) FilterFunctionBuilder(org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder.FilterFunctionBuilder) SearchResponse(org.elasticsearch.action.search.SearchResponse) ElasticsearchAssertions.assertSearchResponse(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder)

Example 5 with MatchAllQueryBuilder

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

the class HighlightBuilderTests method setRandomCommonOptions.

@SuppressWarnings({ "rawtypes" })
private static void setRandomCommonOptions(AbstractHighlighterBuilder highlightBuilder) {
    if (randomBoolean()) {
        // need to set this together, otherwise parsing will complain
        highlightBuilder.preTags(randomStringArray(0, 3));
        highlightBuilder.postTags(randomStringArray(0, 3));
    }
    if (randomBoolean()) {
        highlightBuilder.fragmentSize(randomIntBetween(0, 100));
    }
    if (randomBoolean()) {
        highlightBuilder.numOfFragments(randomIntBetween(0, 10));
    }
    if (randomBoolean()) {
        highlightBuilder.highlighterType(randomAsciiOfLengthBetween(1, 10));
    }
    if (randomBoolean()) {
        highlightBuilder.fragmenter(randomAsciiOfLengthBetween(1, 10));
    }
    if (randomBoolean()) {
        QueryBuilder highlightQuery;
        switch(randomInt(2)) {
            case 0:
                highlightQuery = new MatchAllQueryBuilder();
                break;
            case 1:
                highlightQuery = new IdsQueryBuilder();
                break;
            default:
            case 2:
                highlightQuery = new TermQueryBuilder(randomAsciiOfLengthBetween(1, 10), randomAsciiOfLengthBetween(1, 10));
                break;
        }
        highlightQuery.boost((float) randomDoubleBetween(0, 10, false));
        highlightBuilder.highlightQuery(highlightQuery);
    }
    if (randomBoolean()) {
        if (randomBoolean()) {
            highlightBuilder.order(randomFrom(Order.values()));
        } else {
            // also test the string setter
            highlightBuilder.order(randomFrom(Order.values()).toString());
        }
    }
    if (randomBoolean()) {
        highlightBuilder.highlightFilter(randomBoolean());
    }
    if (randomBoolean()) {
        highlightBuilder.forceSource(randomBoolean());
    }
    if (randomBoolean()) {
        if (randomBoolean()) {
            highlightBuilder.boundaryScannerType(randomFrom(BoundaryScannerType.values()));
        } else {
            // also test the string setter
            highlightBuilder.boundaryScannerType(randomFrom(BoundaryScannerType.values()).toString());
        }
    }
    if (randomBoolean()) {
        highlightBuilder.boundaryMaxScan(randomIntBetween(0, 10));
    }
    if (randomBoolean()) {
        highlightBuilder.boundaryChars(randomAsciiOfLengthBetween(1, 10).toCharArray());
    }
    if (randomBoolean()) {
        highlightBuilder.boundaryScannerLocale(randomLocale(random()).toLanguageTag());
    }
    if (randomBoolean()) {
        highlightBuilder.noMatchSize(randomIntBetween(0, 10));
    }
    if (randomBoolean()) {
        highlightBuilder.phraseLimit(randomIntBetween(0, 10));
    }
    if (randomBoolean()) {
        int items = randomIntBetween(0, 5);
        Map<String, Object> options = new HashMap<>(items);
        for (int i = 0; i < items; i++) {
            Object value = null;
            switch(randomInt(2)) {
                case 0:
                    value = randomAsciiOfLengthBetween(1, 10);
                    break;
                case 1:
                    value = new Integer(randomInt(1000));
                    break;
                case 2:
                    value = new Boolean(randomBoolean());
                    break;
            }
            options.put(randomAsciiOfLengthBetween(1, 10), value);
        }
    }
    if (randomBoolean()) {
        highlightBuilder.requireFieldMatch(randomBoolean());
    }
}
Also used : IdsQueryBuilder(org.elasticsearch.index.query.IdsQueryBuilder) HashMap(java.util.HashMap) IdsQueryBuilder(org.elasticsearch.index.query.IdsQueryBuilder) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) TermQueryBuilder(org.elasticsearch.index.query.TermQueryBuilder) TermQueryBuilder(org.elasticsearch.index.query.TermQueryBuilder) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder)

Aggregations

MatchAllQueryBuilder (org.elasticsearch.index.query.MatchAllQueryBuilder)18 QueryBuilder (org.elasticsearch.index.query.QueryBuilder)7 BoolQueryBuilder (org.elasticsearch.index.query.BoolQueryBuilder)6 ArrayList (java.util.ArrayList)4 TermQueryBuilder (org.elasticsearch.index.query.TermQueryBuilder)4 Script (org.elasticsearch.script.Script)4 HashMap (java.util.HashMap)3 SearchResponse (org.elasticsearch.action.search.SearchResponse)3 MatchQueryBuilder (org.elasticsearch.index.query.MatchQueryBuilder)3 Matchers.containsString (org.hamcrest.Matchers.containsString)3 Map (java.util.Map)2 ParsingException (org.elasticsearch.common.ParsingException)2 XContentParser (org.elasticsearch.common.xcontent.XContentParser)2 AbstractQueryBuilder (org.elasticsearch.index.query.AbstractQueryBuilder)2 HasChildQueryBuilder (org.elasticsearch.index.query.HasChildQueryBuilder)2 HasParentQueryBuilder (org.elasticsearch.index.query.HasParentQueryBuilder)2 RangeQueryBuilder (org.elasticsearch.index.query.RangeQueryBuilder)2 TermsQueryBuilder (org.elasticsearch.index.query.TermsQueryBuilder)2 FilterFunctionBuilder (org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder.FilterFunctionBuilder)2 ElasticsearchAssertions.assertSearchResponse (org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)2