Search in sources :

Example 6 with ParsedQuery

use of org.opensearch.index.query.ParsedQuery in project OpenSearch by opensearch-project.

the class QueryPhaseTests method testEnhanceSortOnNumeric.

public void testEnhanceSortOnNumeric() throws Exception {
    final String fieldNameLong = "long-field";
    final String fieldNameDate = "date-field";
    MappedFieldType fieldTypeLong = new NumberFieldMapper.NumberFieldType(fieldNameLong, NumberFieldMapper.NumberType.LONG);
    MappedFieldType fieldTypeDate = new DateFieldMapper.DateFieldType(fieldNameDate);
    MapperService mapperService = mock(MapperService.class);
    when(mapperService.fieldType(fieldNameLong)).thenReturn(fieldTypeLong);
    when(mapperService.fieldType(fieldNameDate)).thenReturn(fieldTypeDate);
    // enough docs to have a tree with several leaf nodes
    final int numDocs = 3500 * 5;
    Directory dir = newDirectory();
    IndexWriter writer = new IndexWriter(dir, new IndexWriterConfig(null));
    long firstValue = randomLongBetween(-10000000L, 10000000L);
    long longValue = firstValue;
    long dateValue = randomLongBetween(0, 3000000000000L);
    for (int i = 1; i <= numDocs; ++i) {
        Document doc = new Document();
        doc.add(new LongPoint(fieldNameLong, longValue));
        doc.add(new NumericDocValuesField(fieldNameLong, longValue));
        doc.add(new LongPoint(fieldNameDate, dateValue));
        doc.add(new NumericDocValuesField(fieldNameDate, dateValue));
        writer.addDocument(doc);
        longValue++;
        dateValue++;
        if (i % 3500 == 0)
            writer.commit();
    }
    writer.close();
    final IndexReader reader = DirectoryReader.open(dir);
    final SortField sortFieldLong = new SortField(fieldNameLong, SortField.Type.LONG);
    sortFieldLong.setMissingValue(Long.MAX_VALUE);
    final SortField sortFieldDate = new SortField(fieldNameDate, SortField.Type.LONG);
    sortFieldDate.setMissingValue(Long.MAX_VALUE);
    DocValueFormat dateFormat = fieldTypeDate.docValueFormat(null, null);
    final Sort longSort = new Sort(sortFieldLong);
    final Sort longDateSort = new Sort(sortFieldLong, sortFieldDate);
    final Sort dateSort = new Sort(sortFieldDate);
    final Sort dateLongSort = new Sort(sortFieldDate, sortFieldLong);
    SortAndFormats longSortAndFormats = new SortAndFormats(longSort, new DocValueFormat[] { DocValueFormat.RAW });
    SortAndFormats longDateSortAndFormats = new SortAndFormats(longDateSort, new DocValueFormat[] { DocValueFormat.RAW, dateFormat });
    SortAndFormats dateSortAndFormats = new SortAndFormats(dateSort, new DocValueFormat[] { dateFormat });
    SortAndFormats dateLongSortAndFormats = new SortAndFormats(dateLongSort, new DocValueFormat[] { dateFormat, DocValueFormat.RAW });
    ParsedQuery query = new ParsedQuery(new MatchAllDocsQuery());
    SearchShardTask task = new SearchShardTask(123L, "", "", "", null, Collections.emptyMap());
    // 1. Test a sort on long field
    {
        TestSearchContext searchContext = spy(new TestSearchContext(null, indexShard, newContextSearcher(reader)));
        when(searchContext.mapperService()).thenReturn(mapperService);
        searchContext.sort(longSortAndFormats);
        searchContext.parsedQuery(query);
        searchContext.setTask(task);
        searchContext.setSize(10);
        QueryPhase.executeInternal(searchContext);
        assertTrue(searchContext.sort().sort.getSort()[0].getCanUsePoints());
        assertSortResults(searchContext.queryResult().topDocs().topDocs, (long) numDocs, false);
    }
    // 2. Test a sort on long field + date field
    {
        TestSearchContext searchContext = spy(new TestSearchContext(null, indexShard, newContextSearcher(reader)));
        when(searchContext.mapperService()).thenReturn(mapperService);
        searchContext.sort(longDateSortAndFormats);
        searchContext.parsedQuery(query);
        searchContext.setTask(task);
        searchContext.setSize(10);
        QueryPhase.executeInternal(searchContext);
        assertTrue(searchContext.sort().sort.getSort()[0].getCanUsePoints());
        assertSortResults(searchContext.queryResult().topDocs().topDocs, (long) numDocs, true);
    }
    // 3. Test a sort on date field
    {
        TestSearchContext searchContext = spy(new TestSearchContext(null, indexShard, newContextSearcher(reader)));
        when(searchContext.mapperService()).thenReturn(mapperService);
        searchContext.sort(dateSortAndFormats);
        searchContext.parsedQuery(query);
        searchContext.setTask(task);
        searchContext.setSize(10);
        QueryPhase.executeInternal(searchContext);
        assertTrue(searchContext.sort().sort.getSort()[0].getCanUsePoints());
        assertSortResults(searchContext.queryResult().topDocs().topDocs, (long) numDocs, false);
    }
    // 4. Test a sort on date field + long field
    {
        TestSearchContext searchContext = spy(new TestSearchContext(null, indexShard, newContextSearcher(reader)));
        when(searchContext.mapperService()).thenReturn(mapperService);
        searchContext.sort(dateLongSortAndFormats);
        searchContext.parsedQuery(query);
        searchContext.setTask(task);
        searchContext.setSize(10);
        QueryPhase.executeInternal(searchContext);
        assertTrue(searchContext.sort().sort.getSort()[0].getCanUsePoints());
        assertSortResults(searchContext.queryResult().topDocs().topDocs, (long) numDocs, true);
    }
    // 5. Test that sort optimization is run when from > 0 and size = 0
    {
        TestSearchContext searchContext = spy(new TestSearchContext(null, indexShard, newContextSearcher(reader)));
        when(searchContext.mapperService()).thenReturn(mapperService);
        searchContext.sort(longSortAndFormats);
        searchContext.parsedQuery(query);
        searchContext.setTask(task);
        searchContext.from(5);
        searchContext.setSize(0);
        QueryPhase.executeInternal(searchContext);
        assertTrue(searchContext.sort().sort.getSort()[0].getCanUsePoints());
        assertSortResults(searchContext.queryResult().topDocs().topDocs, (long) numDocs, false);
    }
    // 6. Test that sort optimization works with from = 0 and size= 0
    {
        TestSearchContext searchContext = spy(new TestSearchContext(null, indexShard, newContextSearcher(reader)));
        when(searchContext.mapperService()).thenReturn(mapperService);
        searchContext.sort(longSortAndFormats);
        searchContext.parsedQuery(query);
        searchContext.setTask(task);
        searchContext.setSize(0);
        QueryPhase.executeInternal(searchContext);
    }
    // 7. Test that sort optimization works with search after
    {
        TestSearchContext searchContext = spy(new TestSearchContext(null, indexShard, newContextSearcher(reader)));
        when(searchContext.mapperService()).thenReturn(mapperService);
        int afterDocument = (int) randomLongBetween(0, 50);
        long afterValue = firstValue + afterDocument;
        FieldDoc after = new FieldDoc(afterDocument, Float.NaN, new Long[] { afterValue });
        searchContext.searchAfter(after);
        searchContext.sort(longSortAndFormats);
        searchContext.parsedQuery(query);
        searchContext.setTask(task);
        searchContext.setSize(10);
        QueryPhase.executeInternal(searchContext);
        assertTrue(searchContext.sort().sort.getSort()[0].getCanUsePoints());
        final TopDocs topDocs = searchContext.queryResult().topDocs().topDocs;
        long topValue = (long) ((FieldDoc) topDocs.scoreDocs[0]).fields[0];
        assertThat(topValue, greaterThan(afterValue));
        assertSortResults(topDocs, (long) numDocs, false);
    }
    reader.close();
    dir.close();
}
Also used : FieldDoc(org.apache.lucene.search.FieldDoc) ParsedQuery(org.opensearch.index.query.ParsedQuery) SortField(org.apache.lucene.search.SortField) Document(org.apache.lucene.document.Document) TopDocs(org.apache.lucene.search.TopDocs) NumericDocValuesField(org.apache.lucene.document.NumericDocValuesField) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) Sort(org.apache.lucene.search.Sort) Directory(org.apache.lucene.store.Directory) SearchShardTask(org.opensearch.action.search.SearchShardTask) DocValueFormat(org.opensearch.search.DocValueFormat) LongPoint(org.apache.lucene.document.LongPoint) SortAndFormats(org.opensearch.search.sort.SortAndFormats) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) LatLonPoint(org.apache.lucene.document.LatLonPoint) LongPoint(org.apache.lucene.document.LongPoint) TestSearchContext(org.opensearch.test.TestSearchContext) IndexWriter(org.apache.lucene.index.IndexWriter) RandomIndexWriter(org.apache.lucene.index.RandomIndexWriter) IndexReader(org.apache.lucene.index.IndexReader) MapperService(org.opensearch.index.mapper.MapperService) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig)

Example 7 with ParsedQuery

use of org.opensearch.index.query.ParsedQuery in project OpenSearch by opensearch-project.

the class QueryPhaseTests method testTerminateAfterWithFilter.

public void testTerminateAfterWithFilter() throws Exception {
    Directory dir = newDirectory();
    final Sort sort = new Sort(new SortField("rank", SortField.Type.INT));
    IndexWriterConfig iwc = newIndexWriterConfig().setIndexSort(sort);
    RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);
    Document doc = new Document();
    for (int i = 0; i < 10; i++) {
        doc.add(new StringField("foo", Integer.toString(i), Store.NO));
    }
    w.addDocument(doc);
    w.close();
    IndexReader reader = DirectoryReader.open(dir);
    TestSearchContext context = new TestSearchContext(null, indexShard, newContextSearcher(reader));
    context.setTask(new SearchShardTask(123L, "", "", "", null, Collections.emptyMap()));
    context.parsedQuery(new ParsedQuery(new MatchAllDocsQuery()));
    context.terminateAfter(1);
    context.setSize(10);
    for (int i = 0; i < 10; i++) {
        context.parsedPostFilter(new ParsedQuery(new TermQuery(new Term("foo", Integer.toString(i)))));
        QueryPhase.executeInternal(context);
        assertEquals(1, context.queryResult().topDocs().topDocs.totalHits.value);
        assertThat(context.queryResult().topDocs().topDocs.scoreDocs.length, equalTo(1));
    }
    reader.close();
    dir.close();
}
Also used : MultiTermQuery(org.apache.lucene.search.MultiTermQuery) SpanTermQuery(org.apache.lucene.search.spans.SpanTermQuery) TermQuery(org.apache.lucene.search.TermQuery) ParsedQuery(org.opensearch.index.query.ParsedQuery) SortField(org.apache.lucene.search.SortField) Term(org.apache.lucene.index.Term) Document(org.apache.lucene.document.Document) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) LatLonPoint(org.apache.lucene.document.LatLonPoint) LongPoint(org.apache.lucene.document.LongPoint) TestSearchContext(org.opensearch.test.TestSearchContext) StringField(org.apache.lucene.document.StringField) IndexReader(org.apache.lucene.index.IndexReader) Sort(org.apache.lucene.search.Sort) RandomIndexWriter(org.apache.lucene.index.RandomIndexWriter) Directory(org.apache.lucene.store.Directory) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig) SearchShardTask(org.opensearch.action.search.SearchShardTask)

Example 8 with ParsedQuery

use of org.opensearch.index.query.ParsedQuery in project OpenSearch by opensearch-project.

the class QueryPhaseTests method testDisableTopScoreCollection.

public void testDisableTopScoreCollection() throws Exception {
    Directory dir = newDirectory();
    IndexWriterConfig iwc = newIndexWriterConfig(new StandardAnalyzer());
    RandomIndexWriter w = new RandomIndexWriter(random(), dir, iwc);
    Document doc = new Document();
    for (int i = 0; i < 10; i++) {
        doc.clear();
        if (i % 2 == 0) {
            doc.add(new TextField("title", "foo bar", Store.NO));
        } else {
            doc.add(new TextField("title", "foo", Store.NO));
        }
        w.addDocument(doc);
    }
    w.close();
    IndexReader reader = DirectoryReader.open(dir);
    TestSearchContext context = new TestSearchContext(null, indexShard, newContextSearcher(reader));
    context.setTask(new SearchShardTask(123L, "", "", "", null, Collections.emptyMap()));
    Query q = new SpanNearQuery.Builder("title", true).addClause(new SpanTermQuery(new Term("title", "foo"))).addClause(new SpanTermQuery(new Term("title", "bar"))).build();
    context.parsedQuery(new ParsedQuery(q));
    context.setSize(3);
    context.trackTotalHitsUpTo(3);
    TopDocsCollectorContext topDocsContext = TopDocsCollectorContext.createTopDocsCollectorContext(context, false);
    assertEquals(topDocsContext.create(null).scoreMode(), org.apache.lucene.search.ScoreMode.COMPLETE);
    QueryPhase.executeInternal(context);
    assertEquals(5, context.queryResult().topDocs().topDocs.totalHits.value);
    assertEquals(context.queryResult().topDocs().topDocs.totalHits.relation, TotalHits.Relation.EQUAL_TO);
    assertThat(context.queryResult().topDocs().topDocs.scoreDocs.length, equalTo(3));
    context.sort(new SortAndFormats(new Sort(new SortField("other", SortField.Type.INT)), new DocValueFormat[] { DocValueFormat.RAW }));
    topDocsContext = TopDocsCollectorContext.createTopDocsCollectorContext(context, false);
    assertEquals(topDocsContext.create(null).scoreMode(), org.apache.lucene.search.ScoreMode.TOP_DOCS);
    QueryPhase.executeInternal(context);
    assertEquals(5, context.queryResult().topDocs().topDocs.totalHits.value);
    assertThat(context.queryResult().topDocs().topDocs.scoreDocs.length, equalTo(3));
    assertEquals(context.queryResult().topDocs().topDocs.totalHits.relation, TotalHits.Relation.GREATER_THAN_OR_EQUAL_TO);
    reader.close();
    dir.close();
}
Also used : Query(org.apache.lucene.search.Query) MatchNoDocsQuery(org.apache.lucene.search.MatchNoDocsQuery) MultiTermQuery(org.apache.lucene.search.MultiTermQuery) PrefixQuery(org.apache.lucene.search.PrefixQuery) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) MinDocQuery(org.apache.lucene.queries.MinDocQuery) SpanTermQuery(org.apache.lucene.search.spans.SpanTermQuery) ConstantScoreQuery(org.apache.lucene.search.ConstantScoreQuery) SpanNearQuery(org.apache.lucene.search.spans.SpanNearQuery) DocValuesFieldExistsQuery(org.apache.lucene.search.DocValuesFieldExistsQuery) TermQuery(org.apache.lucene.search.TermQuery) BooleanQuery(org.apache.lucene.search.BooleanQuery) ParsedQuery(org.opensearch.index.query.ParsedQuery) OpenSearchToParentBlockJoinQuery(org.opensearch.index.search.OpenSearchToParentBlockJoinQuery) ParsedQuery(org.opensearch.index.query.ParsedQuery) DocValueFormat(org.opensearch.search.DocValueFormat) SortField(org.apache.lucene.search.SortField) Term(org.apache.lucene.index.Term) Document(org.apache.lucene.document.Document) SortAndFormats(org.opensearch.search.sort.SortAndFormats) LatLonPoint(org.apache.lucene.document.LatLonPoint) LongPoint(org.apache.lucene.document.LongPoint) TestSearchContext(org.opensearch.test.TestSearchContext) SpanTermQuery(org.apache.lucene.search.spans.SpanTermQuery) StandardAnalyzer(org.apache.lucene.analysis.standard.StandardAnalyzer) IndexReader(org.apache.lucene.index.IndexReader) TextField(org.apache.lucene.document.TextField) Sort(org.apache.lucene.search.Sort) SpanNearQuery(org.apache.lucene.search.spans.SpanNearQuery) RandomIndexWriter(org.apache.lucene.index.RandomIndexWriter) Directory(org.apache.lucene.store.Directory) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig) SearchShardTask(org.opensearch.action.search.SearchShardTask)

Example 9 with ParsedQuery

use of org.opensearch.index.query.ParsedQuery in project security by opensearch-project.

the class DlsQueryParser method parse.

static ParsedQuery parse(final Set<String> unparsedDlsQueries, ParsedQuery originalQuery, final QueryShardContext queryShardContext, final NamedXContentRegistry namedXContentRegistry) throws IOException {
    if (unparsedDlsQueries == null || unparsedDlsQueries.isEmpty()) {
        return null;
    }
    final boolean hasNestedMapping = queryShardContext.getMapperService().hasNested();
    BooleanQuery.Builder dlsQueryBuilder = new BooleanQuery.Builder();
    dlsQueryBuilder.setMinimumNumberShouldMatch(1);
    for (final String unparsedDlsQuery : unparsedDlsQueries) {
        try {
            final QueryBuilder qb = queries.get(unparsedDlsQuery, new Callable<QueryBuilder>() {

                @Override
                public QueryBuilder call() throws Exception {
                    final XContentParser parser = JsonXContent.jsonXContent.createParser(namedXContentRegistry, THROW_UNSUPPORTED_OPERATION, unparsedDlsQuery);
                    final QueryBuilder qb = AbstractQueryBuilder.parseInnerQueryBuilder(parser);
                    return qb;
                }
            });
            final ParsedQuery parsedQuery = queryShardContext.toQuery(qb);
            // no need for scoring here, so its possible to wrap this in a
            // ConstantScoreQuery
            final Query dlsQuery = new ConstantScoreQuery(parsedQuery.query());
            dlsQueryBuilder.add(dlsQuery, Occur.SHOULD);
            if (hasNestedMapping) {
                handleNested(queryShardContext, dlsQueryBuilder, dlsQuery);
            }
        } catch (ExecutionException e) {
            throw new IOException(e);
        }
    }
    dlsQueryBuilder.add(originalQuery.query(), Occur.MUST);
    return new ParsedQuery(dlsQueryBuilder.build());
}
Also used : BooleanQuery(org.apache.lucene.search.BooleanQuery) Query(org.apache.lucene.search.Query) PrefixQuery(org.apache.lucene.search.PrefixQuery) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) BooleanQuery(org.apache.lucene.search.BooleanQuery) ToChildBlockJoinQuery(org.apache.lucene.search.join.ToChildBlockJoinQuery) ConstantScoreQuery(org.apache.lucene.search.ConstantScoreQuery) ParsedQuery(org.opensearch.index.query.ParsedQuery) ParsedQuery(org.opensearch.index.query.ParsedQuery) QueryBuilder(org.opensearch.index.query.QueryBuilder) CacheBuilder(com.google.common.cache.CacheBuilder) AbstractQueryBuilder(org.opensearch.index.query.AbstractQueryBuilder) QueryBuilder(org.opensearch.index.query.QueryBuilder) AbstractQueryBuilder(org.opensearch.index.query.AbstractQueryBuilder) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ConstantScoreQuery(org.apache.lucene.search.ConstantScoreQuery) ExecutionException(java.util.concurrent.ExecutionException) XContentParser(org.opensearch.common.xcontent.XContentParser)

Example 10 with ParsedQuery

use of org.opensearch.index.query.ParsedQuery in project security by opensearch-project.

the class DlsQueryParser method parse.

static Query parse(final Set<String> unparsedDlsQueries, final QueryShardContext queryShardContext, final NamedXContentRegistry namedXContentRegistry) throws IOException {
    if (unparsedDlsQueries == null || unparsedDlsQueries.isEmpty()) {
        return null;
    }
    final boolean hasNestedMapping = queryShardContext.getMapperService().hasNested();
    BooleanQuery.Builder dlsQueryBuilder = new BooleanQuery.Builder();
    dlsQueryBuilder.setMinimumNumberShouldMatch(1);
    for (final String unparsedDlsQuery : unparsedDlsQueries) {
        try {
            final QueryBuilder qb = queries.get(unparsedDlsQuery, new Callable<QueryBuilder>() {

                @Override
                public QueryBuilder call() throws Exception {
                    final XContentParser parser = JsonXContent.jsonXContent.createParser(namedXContentRegistry, THROW_UNSUPPORTED_OPERATION, unparsedDlsQuery);
                    final QueryBuilder qb = AbstractQueryBuilder.parseInnerQueryBuilder(parser);
                    return qb;
                }
            });
            final ParsedQuery parsedQuery = queryShardContext.toQuery(qb);
            final Query dlsQuery = parsedQuery.query();
            dlsQueryBuilder.add(dlsQuery, Occur.SHOULD);
            if (hasNestedMapping) {
                handleNested(queryShardContext, dlsQueryBuilder, dlsQuery);
            }
        } catch (ExecutionException e) {
            throw new IOException(e);
        }
    }
    // ConstantScoreQuery
    return new ConstantScoreQuery(dlsQueryBuilder.build());
}
Also used : BooleanQuery(org.apache.lucene.search.BooleanQuery) Query(org.apache.lucene.search.Query) PrefixQuery(org.apache.lucene.search.PrefixQuery) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) BooleanQuery(org.apache.lucene.search.BooleanQuery) ToChildBlockJoinQuery(org.apache.lucene.search.join.ToChildBlockJoinQuery) ConstantScoreQuery(org.apache.lucene.search.ConstantScoreQuery) ParsedQuery(org.opensearch.index.query.ParsedQuery) ParsedQuery(org.opensearch.index.query.ParsedQuery) QueryBuilder(org.opensearch.index.query.QueryBuilder) CacheBuilder(com.google.common.cache.CacheBuilder) AbstractQueryBuilder(org.opensearch.index.query.AbstractQueryBuilder) QueryBuilder(org.opensearch.index.query.QueryBuilder) AbstractQueryBuilder(org.opensearch.index.query.AbstractQueryBuilder) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ConstantScoreQuery(org.apache.lucene.search.ConstantScoreQuery) ExecutionException(java.util.concurrent.ExecutionException) XContentParser(org.opensearch.common.xcontent.XContentParser)

Aggregations

ParsedQuery (org.opensearch.index.query.ParsedQuery)20 IndexReader (org.apache.lucene.index.IndexReader)14 RandomIndexWriter (org.apache.lucene.index.RandomIndexWriter)13 Directory (org.apache.lucene.store.Directory)13 SearchShardTask (org.opensearch.action.search.SearchShardTask)13 TestSearchContext (org.opensearch.test.TestSearchContext)13 Document (org.apache.lucene.document.Document)12 MatchAllDocsQuery (org.apache.lucene.search.MatchAllDocsQuery)12 IndexWriterConfig (org.apache.lucene.index.IndexWriterConfig)11 LatLonPoint (org.apache.lucene.document.LatLonPoint)10 LongPoint (org.apache.lucene.document.LongPoint)10 Sort (org.apache.lucene.search.Sort)9 SortField (org.apache.lucene.search.SortField)8 StringField (org.apache.lucene.document.StringField)5 Term (org.apache.lucene.index.Term)5 BooleanQuery (org.apache.lucene.search.BooleanQuery)5 IOException (java.io.IOException)4 NumericDocValuesField (org.apache.lucene.document.NumericDocValuesField)4 MultiTermQuery (org.apache.lucene.search.MultiTermQuery)4 PrefixQuery (org.apache.lucene.search.PrefixQuery)4