Search in sources :

Example 31 with TermQuery

use of org.apache.lucene.search.TermQuery in project elasticsearch by elastic.

the class ExistsQueryBuilderTests method doAssertLuceneQuery.

@Override
protected void doAssertLuceneQuery(ExistsQueryBuilder queryBuilder, Query query, SearchContext context) throws IOException {
    String fieldPattern = queryBuilder.fieldName();
    Collection<String> fields = context.getQueryShardContext().simpleMatchToIndexNames(fieldPattern);
    if (getCurrentTypes().length == 0) {
        assertThat(query, instanceOf(MatchNoDocsQuery.class));
        MatchNoDocsQuery matchNoDocsQuery = (MatchNoDocsQuery) query;
        assertThat(matchNoDocsQuery.toString(null), containsString("Missing types in \"exists\" query."));
    } else if (fields.size() == 1) {
        assertThat(query, instanceOf(ConstantScoreQuery.class));
        ConstantScoreQuery constantScoreQuery = (ConstantScoreQuery) query;
        assertThat(constantScoreQuery.getQuery(), instanceOf(TermQuery.class));
        TermQuery termQuery = (TermQuery) constantScoreQuery.getQuery();
        assertEquals(fields.iterator().next(), termQuery.getTerm().text());
    } else {
        assertThat(query, instanceOf(ConstantScoreQuery.class));
        ConstantScoreQuery constantScoreQuery = (ConstantScoreQuery) query;
        assertThat(constantScoreQuery.getQuery(), instanceOf(BooleanQuery.class));
        BooleanQuery booleanQuery = (BooleanQuery) constantScoreQuery.getQuery();
        assertThat(booleanQuery.clauses().size(), equalTo(fields.size()));
        for (int i = 0; i < fields.size(); i++) {
            BooleanClause booleanClause = booleanQuery.clauses().get(i);
            assertThat(booleanClause.getOccur(), equalTo(BooleanClause.Occur.SHOULD));
        }
    }
}
Also used : BooleanClause(org.apache.lucene.search.BooleanClause) TermQuery(org.apache.lucene.search.TermQuery) BooleanQuery(org.apache.lucene.search.BooleanQuery) MatchNoDocsQuery(org.apache.lucene.search.MatchNoDocsQuery) ConstantScoreQuery(org.apache.lucene.search.ConstantScoreQuery) CoreMatchers.containsString(org.hamcrest.CoreMatchers.containsString)

Example 32 with TermQuery

use of org.apache.lucene.search.TermQuery in project elasticsearch by elastic.

the class TypeFieldTypeTests method testTermsQuery.

public void testTermsQuery() throws Exception {
    Directory dir = newDirectory();
    IndexWriter w = new IndexWriter(dir, newIndexWriterConfig());
    IndexReader reader = openReaderWithNewType("my_type", w);
    TypeFieldMapper.TypeFieldType ft = new TypeFieldMapper.TypeFieldType();
    ft.setName(TypeFieldMapper.NAME);
    Query query = ft.termQuery("my_type", null);
    assertEquals(new MatchAllDocsQuery(), query.rewrite(reader));
    // Make sure that Lucene actually simplifies the query when there is a single type
    Query userQuery = new PhraseQuery("body", "quick", "fox");
    Query filteredQuery = new BooleanQuery.Builder().add(userQuery, Occur.MUST).add(query, Occur.FILTER).build();
    Query rewritten = new IndexSearcher(reader).rewrite(filteredQuery);
    assertEquals(userQuery, rewritten);
    // ... and does not rewrite it if there is more than one type
    reader.close();
    reader = openReaderWithNewType("my_type2", w);
    Query expected = new ConstantScoreQuery(new BooleanQuery.Builder().add(new TermQuery(new Term(TypeFieldMapper.NAME, "my_type")), Occur.SHOULD).build());
    assertEquals(expected, query.rewrite(reader));
    BytesRef[] types = new BytesRef[] { new BytesRef("my_type"), new BytesRef("my_type2"), new BytesRef("my_type3") };
    // the query should match all documents
    query = new TypeFieldMapper.TypesQuery(types);
    assertEquals(new MatchAllDocsQuery(), query.rewrite(reader));
    reader.close();
    reader = openReaderWithNewType("unknown_type", w);
    // the query cannot rewrite to a match all docs sinc unknown_type is not queried.
    query = new TypeFieldMapper.TypesQuery(types);
    expected = new ConstantScoreQuery(new BooleanQuery.Builder().add(new TermQuery(new Term(TypeFieldMapper.CONTENT_TYPE, types[0])), Occur.SHOULD).add(new TermQuery(new Term(TypeFieldMapper.CONTENT_TYPE, types[1])), Occur.SHOULD).build());
    rewritten = query.rewrite(reader);
    assertEquals(expected, rewritten);
    // make sure that redundant types does not rewrite to MatchAllDocsQuery
    query = new TypeFieldMapper.TypesQuery(new BytesRef("my_type"), new BytesRef("my_type"), new BytesRef("my_type"));
    expected = new ConstantScoreQuery(new BooleanQuery.Builder().add(new TermQuery(new Term(TypeFieldMapper.CONTENT_TYPE, "my_type")), Occur.SHOULD).build());
    rewritten = query.rewrite(reader);
    assertEquals(expected, rewritten);
    IOUtils.close(reader, w, dir);
}
Also used : IndexSearcher(org.apache.lucene.search.IndexSearcher) BooleanQuery(org.apache.lucene.search.BooleanQuery) TermQuery(org.apache.lucene.search.TermQuery) Query(org.apache.lucene.search.Query) PhraseQuery(org.apache.lucene.search.PhraseQuery) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) TermQuery(org.apache.lucene.search.TermQuery) BooleanQuery(org.apache.lucene.search.BooleanQuery) ConstantScoreQuery(org.apache.lucene.search.ConstantScoreQuery) PhraseQuery(org.apache.lucene.search.PhraseQuery) Term(org.apache.lucene.index.Term) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) IndexWriter(org.apache.lucene.index.IndexWriter) IndexReader(org.apache.lucene.index.IndexReader) ConstantScoreQuery(org.apache.lucene.search.ConstantScoreQuery) BytesRef(org.apache.lucene.util.BytesRef) Directory(org.apache.lucene.store.Directory)

Example 33 with TermQuery

use of org.apache.lucene.search.TermQuery in project elasticsearch by elastic.

the class MatchQueryBuilderTests method doAssertLuceneQuery.

@Override
protected void doAssertLuceneQuery(MatchQueryBuilder queryBuilder, Query query, SearchContext searchContext) throws IOException {
    assertThat(query, notNullValue());
    if (query instanceof MatchAllDocsQuery) {
        assertThat(queryBuilder.zeroTermsQuery(), equalTo(ZeroTermsQuery.ALL));
        return;
    }
    switch(queryBuilder.type()) {
        case BOOLEAN:
            assertThat(query, either(instanceOf(BooleanQuery.class)).or(instanceOf(ExtendedCommonTermsQuery.class)).or(instanceOf(TermQuery.class)).or(instanceOf(FuzzyQuery.class)).or(instanceOf(MatchNoDocsQuery.class)).or(instanceOf(PointRangeQuery.class)).or(instanceOf(IndexOrDocValuesQuery.class)));
            break;
        case PHRASE:
            assertThat(query, either(instanceOf(BooleanQuery.class)).or(instanceOf(PhraseQuery.class)).or(instanceOf(TermQuery.class)).or(instanceOf(FuzzyQuery.class)).or(instanceOf(PointRangeQuery.class)).or(instanceOf(IndexOrDocValuesQuery.class)));
            break;
        case PHRASE_PREFIX:
            assertThat(query, either(instanceOf(BooleanQuery.class)).or(instanceOf(MultiPhrasePrefixQuery.class)).or(instanceOf(TermQuery.class)).or(instanceOf(FuzzyQuery.class)).or(instanceOf(PointRangeQuery.class)).or(instanceOf(IndexOrDocValuesQuery.class)));
            break;
    }
    QueryShardContext context = searchContext.getQueryShardContext();
    MappedFieldType fieldType = context.fieldMapper(queryBuilder.fieldName());
    if (query instanceof TermQuery && fieldType != null) {
        String queryValue = queryBuilder.value().toString();
        if (queryBuilder.analyzer() == null || queryBuilder.analyzer().equals("simple")) {
            queryValue = queryValue.toLowerCase(Locale.ROOT);
        }
        Query expectedTermQuery = fieldType.termQuery(queryValue, context);
        assertEquals(expectedTermQuery, query);
    }
    if (query instanceof BooleanQuery) {
        BooleanQuery bq = (BooleanQuery) query;
        if (queryBuilder.minimumShouldMatch() != null) {
            // calculate expected minimumShouldMatch value
            int optionalClauses = 0;
            for (BooleanClause c : bq.clauses()) {
                if (c.getOccur() == BooleanClause.Occur.SHOULD) {
                    optionalClauses++;
                }
            }
            int msm = Queries.calculateMinShouldMatch(optionalClauses, queryBuilder.minimumShouldMatch());
            assertThat(bq.getMinimumNumberShouldMatch(), equalTo(msm));
        }
        if (queryBuilder.analyzer() == null && queryBuilder.value().toString().length() > 0) {
            assertEquals(bq.clauses().size(), queryBuilder.value().toString().split(" ").length);
        }
    }
    if (query instanceof ExtendedCommonTermsQuery) {
        assertTrue(queryBuilder.cutoffFrequency() != null);
        ExtendedCommonTermsQuery ectq = (ExtendedCommonTermsQuery) query;
        assertEquals(queryBuilder.cutoffFrequency(), ectq.getMaxTermFrequency(), Float.MIN_VALUE);
    }
    if (query instanceof FuzzyQuery) {
        assertTrue(queryBuilder.fuzziness() != null);
        FuzzyQuery fuzzyQuery = (FuzzyQuery) query;
        // depending on analyzer being set or not we can have term lowercased along the way, so to simplify test we just
        // compare lowercased terms here
        String originalTermLc = queryBuilder.value().toString().toLowerCase(Locale.ROOT);
        String actualTermLc = fuzzyQuery.getTerm().text().toLowerCase(Locale.ROOT);
        Matcher<String> termLcMatcher = equalTo(originalTermLc);
        if ("false".equals(originalTermLc) || "true".equals(originalTermLc)) {
            // Booleans become t/f when querying a boolean field
            termLcMatcher = either(termLcMatcher).or(equalTo(originalTermLc.substring(0, 1)));
        }
        assertThat(actualTermLc, termLcMatcher);
        assertThat(queryBuilder.prefixLength(), equalTo(fuzzyQuery.getPrefixLength()));
        assertThat(queryBuilder.fuzzyTranspositions(), equalTo(fuzzyQuery.getTranspositions()));
    }
    if (query instanceof PointRangeQuery) {
    // TODO
    }
}
Also used : BooleanQuery(org.apache.lucene.search.BooleanQuery) TermQuery(org.apache.lucene.search.TermQuery) ExtendedCommonTermsQuery(org.apache.lucene.queries.ExtendedCommonTermsQuery) Query(org.apache.lucene.search.Query) ZeroTermsQuery(org.elasticsearch.index.search.MatchQuery.ZeroTermsQuery) MatchNoDocsQuery(org.apache.lucene.search.MatchNoDocsQuery) PhraseQuery(org.apache.lucene.search.PhraseQuery) MatchQuery(org.elasticsearch.index.search.MatchQuery) IndexOrDocValuesQuery(org.apache.lucene.search.IndexOrDocValuesQuery) MultiPhrasePrefixQuery(org.elasticsearch.common.lucene.search.MultiPhrasePrefixQuery) ExtendedCommonTermsQuery(org.apache.lucene.queries.ExtendedCommonTermsQuery) PointRangeQuery(org.apache.lucene.search.PointRangeQuery) FuzzyQuery(org.apache.lucene.search.FuzzyQuery) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) TermQuery(org.apache.lucene.search.TermQuery) BooleanQuery(org.apache.lucene.search.BooleanQuery) BoostQuery(org.apache.lucene.search.BoostQuery) Matchers.containsString(org.hamcrest.Matchers.containsString) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) BooleanClause(org.apache.lucene.search.BooleanClause) FuzzyQuery(org.apache.lucene.search.FuzzyQuery) PointRangeQuery(org.apache.lucene.search.PointRangeQuery) MappedFieldType(org.elasticsearch.index.mapper.MappedFieldType)

Example 34 with TermQuery

use of org.apache.lucene.search.TermQuery in project elasticsearch by elastic.

the class MultiMatchQueryBuilderTests method testToQueryMultipleFieldsDisMaxQuery.

public void testToQueryMultipleFieldsDisMaxQuery() throws Exception {
    assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
    Query query = multiMatchQuery("test").field(STRING_FIELD_NAME).field(STRING_FIELD_NAME_2).useDisMax(true).toQuery(createShardContext());
    assertThat(query, instanceOf(DisjunctionMaxQuery.class));
    DisjunctionMaxQuery disMaxQuery = (DisjunctionMaxQuery) query;
    List<Query> disjuncts = disMaxQuery.getDisjuncts();
    assertThat(disjuncts.get(0), instanceOf(TermQuery.class));
    assertThat(((TermQuery) disjuncts.get(0)).getTerm(), equalTo(new Term(STRING_FIELD_NAME, "test")));
    assertThat(disjuncts.get(1), instanceOf(TermQuery.class));
    assertThat(((TermQuery) disjuncts.get(1)).getTerm(), equalTo(new Term(STRING_FIELD_NAME_2, "test")));
}
Also used : AllTermQuery(org.elasticsearch.common.lucene.all.AllTermQuery) TermQuery(org.apache.lucene.search.TermQuery) Query(org.apache.lucene.search.Query) MatchNoDocsQuery(org.apache.lucene.search.MatchNoDocsQuery) PhraseQuery(org.apache.lucene.search.PhraseQuery) MatchQuery(org.elasticsearch.index.search.MatchQuery) IndexOrDocValuesQuery(org.apache.lucene.search.IndexOrDocValuesQuery) AllTermQuery(org.elasticsearch.common.lucene.all.AllTermQuery) MultiPhrasePrefixQuery(org.elasticsearch.common.lucene.search.MultiPhrasePrefixQuery) ExtendedCommonTermsQuery(org.apache.lucene.queries.ExtendedCommonTermsQuery) LegacyNumericRangeQuery(org.apache.lucene.search.LegacyNumericRangeQuery) PointRangeQuery(org.apache.lucene.search.PointRangeQuery) FuzzyQuery(org.apache.lucene.search.FuzzyQuery) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) ElasticsearchAssertions.assertBooleanSubQuery(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertBooleanSubQuery) DisjunctionMaxQuery(org.apache.lucene.search.DisjunctionMaxQuery) TermQuery(org.apache.lucene.search.TermQuery) BooleanQuery(org.apache.lucene.search.BooleanQuery) BoostQuery(org.apache.lucene.search.BoostQuery) QueryBuilders.multiMatchQuery(org.elasticsearch.index.query.QueryBuilders.multiMatchQuery) DisjunctionMaxQuery(org.apache.lucene.search.DisjunctionMaxQuery) Term(org.apache.lucene.index.Term)

Example 35 with TermQuery

use of org.apache.lucene.search.TermQuery in project elasticsearch by elastic.

the class QueryStringQueryBuilderTests method testToQueryTermQuery.

public void testToQueryTermQuery() throws IOException {
    assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
    Query query = queryStringQuery("test").defaultField(STRING_FIELD_NAME).toQuery(createShardContext());
    assertThat(query, instanceOf(TermQuery.class));
    TermQuery termQuery = (TermQuery) query;
    assertThat(termQuery.getTerm(), equalTo(new Term(STRING_FIELD_NAME, "test")));
}
Also used : MultiTermQuery(org.apache.lucene.search.MultiTermQuery) AllTermQuery(org.elasticsearch.common.lucene.all.AllTermQuery) SpanTermQuery(org.apache.lucene.search.spans.SpanTermQuery) TermQuery(org.apache.lucene.search.TermQuery) Query(org.apache.lucene.search.Query) MatchNoDocsQuery(org.apache.lucene.search.MatchNoDocsQuery) PhraseQuery(org.apache.lucene.search.PhraseQuery) RegexpQuery(org.apache.lucene.search.RegexpQuery) MultiTermQuery(org.apache.lucene.search.MultiTermQuery) AllTermQuery(org.elasticsearch.common.lucene.all.AllTermQuery) PrefixQuery(org.apache.lucene.search.PrefixQuery) FuzzyQuery(org.apache.lucene.search.FuzzyQuery) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) WildcardQuery(org.apache.lucene.search.WildcardQuery) ElasticsearchAssertions.assertBooleanSubQuery(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertBooleanSubQuery) DisjunctionMaxQuery(org.apache.lucene.search.DisjunctionMaxQuery) SpanTermQuery(org.apache.lucene.search.spans.SpanTermQuery) ConstantScoreQuery(org.apache.lucene.search.ConstantScoreQuery) SpanNearQuery(org.apache.lucene.search.spans.SpanNearQuery) TermQuery(org.apache.lucene.search.TermQuery) SynonymQuery(org.apache.lucene.search.SynonymQuery) BooleanQuery(org.apache.lucene.search.BooleanQuery) QueryBuilders.queryStringQuery(org.elasticsearch.index.query.QueryBuilders.queryStringQuery) BoostQuery(org.apache.lucene.search.BoostQuery) TermRangeQuery(org.apache.lucene.search.TermRangeQuery) SpanOrQuery(org.apache.lucene.search.spans.SpanOrQuery) Term(org.apache.lucene.index.Term)

Aggregations

TermQuery (org.apache.lucene.search.TermQuery)826 Term (org.apache.lucene.index.Term)707 BooleanQuery (org.apache.lucene.search.BooleanQuery)412 Query (org.apache.lucene.search.Query)318 IndexSearcher (org.apache.lucene.search.IndexSearcher)280 Document (org.apache.lucene.document.Document)229 TopDocs (org.apache.lucene.search.TopDocs)195 Directory (org.apache.lucene.store.Directory)171 MatchAllDocsQuery (org.apache.lucene.search.MatchAllDocsQuery)139 PhraseQuery (org.apache.lucene.search.PhraseQuery)135 IndexReader (org.apache.lucene.index.IndexReader)132 Test (org.junit.Test)117 RandomIndexWriter (org.apache.lucene.index.RandomIndexWriter)116 MockAnalyzer (org.apache.lucene.analysis.MockAnalyzer)114 SpanTermQuery (org.apache.lucene.search.spans.SpanTermQuery)106 ArrayList (java.util.ArrayList)101 BoostQuery (org.apache.lucene.search.BoostQuery)95 Field (org.apache.lucene.document.Field)84 PrefixQuery (org.apache.lucene.search.PrefixQuery)80 IOException (java.io.IOException)69