Search in sources :

Example 1 with MappedFieldType

use of org.opensearch.index.mapper.MappedFieldType in project OpenSearch by opensearch-project.

the class CandidateQueryTests method testDuel2.

public void testDuel2() throws Exception {
    List<String> stringValues = new ArrayList<>();
    stringValues.add("value1");
    stringValues.add("value2");
    stringValues.add("value3");
    MappedFieldType intFieldType = mapperService.fieldType("int_field");
    List<int[]> ranges = new ArrayList<>();
    ranges.add(new int[] { -5, 5 });
    ranges.add(new int[] { 0, 10 });
    ranges.add(new int[] { 15, 50 });
    QueryShardContext context = createSearchContext(indexService).getQueryShardContext();
    List<ParseContext.Document> documents = new ArrayList<>();
    {
        addQuery(new TermQuery(new Term("string_field", randomFrom(stringValues))), documents);
    }
    {
        addQuery(new PhraseQuery(0, "string_field", stringValues.toArray(new String[0])), documents);
    }
    {
        int[] range = randomFrom(ranges);
        Query rangeQuery = intFieldType.rangeQuery(range[0], range[1], true, true, null, null, null, context);
        addQuery(rangeQuery, documents);
    }
    {
        int numBooleanQueries = randomIntBetween(1, 5);
        for (int i = 0; i < numBooleanQueries; i++) {
            Query randomBQ = randomBQ(1, stringValues, ranges, intFieldType, context);
            addQuery(randomBQ, documents);
        }
    }
    {
        addQuery(new MatchNoDocsQuery(), documents);
    }
    {
        addQuery(new MatchAllDocsQuery(), documents);
    }
    indexWriter.addDocuments(documents);
    indexWriter.close();
    directoryReader = DirectoryReader.open(directory);
    IndexSearcher shardSearcher = newSearcher(directoryReader);
    // Disable query cache, because ControlQuery cannot be cached...
    shardSearcher.setQueryCache(null);
    Document document = new Document();
    for (String value : stringValues) {
        document.add(new TextField("string_field", value, Field.Store.NO));
        logger.info("Test with document: {}" + document);
        MemoryIndex memoryIndex = MemoryIndex.fromDocument(document, new WhitespaceAnalyzer());
        duelRun(queryStore, memoryIndex, shardSearcher);
    }
    for (int[] range : ranges) {
        List<Field> numberFields = NumberFieldMapper.NumberType.INTEGER.createFields("int_field", between(range[0], range[1]), true, true, false);
        for (Field numberField : numberFields) {
            document.add(numberField);
        }
        logger.info("Test with document: {}" + document);
        MemoryIndex memoryIndex = MemoryIndex.fromDocument(document, new WhitespaceAnalyzer());
        duelRun(queryStore, memoryIndex, shardSearcher);
    }
}
Also used : IndexSearcher(org.apache.lucene.search.IndexSearcher) WhitespaceAnalyzer(org.apache.lucene.analysis.core.WhitespaceAnalyzer) BlendedTermQuery(org.apache.lucene.queries.BlendedTermQuery) SpanTermQuery(org.apache.lucene.search.spans.SpanTermQuery) TermQuery(org.apache.lucene.search.TermQuery) PhraseQuery(org.apache.lucene.search.PhraseQuery) Query(org.apache.lucene.search.Query) PhraseQuery(org.apache.lucene.search.PhraseQuery) BlendedTermQuery(org.apache.lucene.queries.BlendedTermQuery) CoveringQuery(org.apache.lucene.search.CoveringQuery) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) WildcardQuery(org.apache.lucene.search.WildcardQuery) SpanNotQuery(org.apache.lucene.search.spans.SpanNotQuery) ConstantScoreQuery(org.apache.lucene.search.ConstantScoreQuery) SpanNearQuery(org.apache.lucene.search.spans.SpanNearQuery) SpanOrQuery(org.apache.lucene.search.spans.SpanOrQuery) MatchNoDocsQuery(org.apache.lucene.search.MatchNoDocsQuery) CommonTermsQuery(org.apache.lucene.queries.CommonTermsQuery) FunctionScoreQuery(org.opensearch.common.lucene.search.function.FunctionScoreQuery) TermInSetQuery(org.apache.lucene.search.TermInSetQuery) PrefixQuery(org.apache.lucene.search.PrefixQuery) DisjunctionMaxQuery(org.apache.lucene.search.DisjunctionMaxQuery) SpanTermQuery(org.apache.lucene.search.spans.SpanTermQuery) TermQuery(org.apache.lucene.search.TermQuery) BooleanQuery(org.apache.lucene.search.BooleanQuery) MatchNoDocsQuery(org.apache.lucene.search.MatchNoDocsQuery) ArrayList(java.util.ArrayList) InetAddresses.forString(org.opensearch.common.network.InetAddresses.forString) Term(org.apache.lucene.index.Term) Document(org.apache.lucene.document.Document) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) SortField(org.apache.lucene.search.SortField) TextField(org.apache.lucene.document.TextField) IndexableField(org.apache.lucene.index.IndexableField) StoredField(org.apache.lucene.document.StoredField) StringField(org.apache.lucene.document.StringField) Field(org.apache.lucene.document.Field) MemoryIndex(org.apache.lucene.index.memory.MemoryIndex) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) QueryShardContext(org.opensearch.index.query.QueryShardContext) TextField(org.apache.lucene.document.TextField)

Example 2 with MappedFieldType

use of org.opensearch.index.mapper.MappedFieldType in project OpenSearch by opensearch-project.

the class PercolateQueryBuilder method createStore.

static PercolateQuery.QueryStore createStore(MappedFieldType queryBuilderFieldType, QueryShardContext context) {
    Version indexVersion = context.indexVersionCreated();
    NamedWriteableRegistry registry = context.getWriteableRegistry();
    return ctx -> {
        LeafReader leafReader = ctx.reader();
        BinaryDocValues binaryDocValues = leafReader.getBinaryDocValues(queryBuilderFieldType.name());
        if (binaryDocValues == null) {
            return docId -> null;
        }
        return docId -> {
            if (binaryDocValues.advanceExact(docId)) {
                BytesRef qbSource = binaryDocValues.binaryValue();
                try (InputStream in = new ByteArrayInputStream(qbSource.bytes, qbSource.offset, qbSource.length)) {
                    try (StreamInput input = new NamedWriteableAwareStreamInput(new InputStreamStreamInput(in, qbSource.length), registry)) {
                        input.setVersion(indexVersion);
                        // Query builder's content is stored via BinaryFieldMapper, which has a custom encoding
                        // to encode multiple binary values into a single binary doc values field.
                        // This is the reason we need to first need to read the number of values and
                        // then the length of the field value in bytes.
                        int numValues = input.readVInt();
                        assert numValues == 1;
                        int valueLength = input.readVInt();
                        assert valueLength > 0;
                        QueryBuilder queryBuilder = input.readNamedWriteable(QueryBuilder.class);
                        assert in.read() == -1;
                        queryBuilder = Rewriteable.rewrite(queryBuilder, context);
                        return queryBuilder.toQuery(context);
                    }
                }
            } else {
                return null;
            }
        };
    };
}
Also used : NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) Query(org.apache.lucene.search.Query) ConstructingObjectParser(org.opensearch.common.xcontent.ConstructingObjectParser) FieldNameAnalyzer(org.opensearch.index.analysis.FieldNameAnalyzer) NoneCircuitBreakerService(org.opensearch.indices.breaker.NoneCircuitBreakerService) Version(org.opensearch.Version) InputStreamStreamInput(org.opensearch.common.io.stream.InputStreamStreamInput) BitSet(org.apache.lucene.util.BitSet) OpenSearchException(org.opensearch.OpenSearchException) XContentParser(org.opensearch.common.xcontent.XContentParser) MapperService(org.opensearch.index.mapper.MapperService) ByteArrayInputStream(java.io.ByteArrayInputStream) IndexFieldDataCache(org.opensearch.index.fielddata.IndexFieldDataCache) Directory(org.apache.lucene.store.Directory) XContentFactory(org.opensearch.common.xcontent.XContentFactory) ActionListener(org.opensearch.action.ActionListener) BitDocIdSet(org.apache.lucene.util.BitDocIdSet) Scorer(org.apache.lucene.search.Scorer) BytesRef(org.apache.lucene.util.BytesRef) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) DirectoryReader(org.apache.lucene.index.DirectoryReader) Collection(java.util.Collection) LoggingDeprecationHandler(org.opensearch.common.xcontent.LoggingDeprecationHandler) QueryShardException(org.opensearch.index.query.QueryShardException) Objects(java.util.Objects) IndexWriter(org.apache.lucene.index.IndexWriter) List(java.util.List) QueryBuilder(org.opensearch.index.query.QueryBuilder) LeafReader(org.apache.lucene.index.LeafReader) QueryShardContext(org.opensearch.index.query.QueryShardContext) XContentType(org.opensearch.common.xcontent.XContentType) AbstractQueryBuilder(org.opensearch.index.query.AbstractQueryBuilder) BinaryDocValues(org.apache.lucene.index.BinaryDocValues) IndexWriterConfig(org.apache.lucene.index.IndexWriterConfig) IndexReader(org.apache.lucene.index.IndexReader) IndexSearcher(org.apache.lucene.search.IndexSearcher) ReaderUtil(org.apache.lucene.index.ReaderUtil) BytesReference(org.opensearch.common.bytes.BytesReference) MemoryIndex(org.apache.lucene.index.memory.MemoryIndex) Weight(org.apache.lucene.search.Weight) StreamOutput(org.opensearch.common.io.stream.StreamOutput) ResourceNotFoundException(org.opensearch.ResourceNotFoundException) ParseField(org.opensearch.common.ParseField) Supplier(java.util.function.Supplier) ConstructingObjectParser.constructorArg(org.opensearch.common.xcontent.ConstructingObjectParser.constructorArg) NamedWriteableRegistry(org.opensearch.common.io.stream.NamedWriteableRegistry) ArrayList(java.util.ArrayList) DeprecationLogger(org.opensearch.common.logging.DeprecationLogger) BitSetProducer(org.apache.lucene.search.join.BitSetProducer) IndexFieldData(org.opensearch.index.fielddata.IndexFieldData) SourceToParse(org.opensearch.index.mapper.SourceToParse) ByteBuffersDirectory(org.apache.lucene.store.ByteBuffersDirectory) DelegatingAnalyzerWrapper(org.apache.lucene.analysis.DelegatingAnalyzerWrapper) ParsedDocument(org.opensearch.index.mapper.ParsedDocument) ConstructingObjectParser.optionalConstructorArg(org.opensearch.common.xcontent.ConstructingObjectParser.optionalConstructorArg) NamedWriteableAwareStreamInput(org.opensearch.common.io.stream.NamedWriteableAwareStreamInput) StreamInput(org.opensearch.common.io.stream.StreamInput) ParseContext(org.opensearch.index.mapper.ParseContext) SetOnce(org.apache.lucene.util.SetOnce) Analyzer(org.apache.lucene.analysis.Analyzer) GetRequest(org.opensearch.action.get.GetRequest) Rewriteable(org.opensearch.index.query.Rewriteable) IOException(java.io.IOException) DocumentMapper(org.opensearch.index.mapper.DocumentMapper) ScoreMode(org.apache.lucene.search.ScoreMode) XContentBuilder(org.opensearch.common.xcontent.XContentBuilder) XContentHelper(org.opensearch.common.xcontent.XContentHelper) QueryRewriteContext(org.opensearch.index.query.QueryRewriteContext) CircuitBreakerService(org.opensearch.indices.breaker.CircuitBreakerService) NamedXContentRegistry(org.opensearch.common.xcontent.NamedXContentRegistry) ALLOW_EXPENSIVE_QUERIES(org.opensearch.search.SearchService.ALLOW_EXPENSIVE_QUERIES) Collections(java.util.Collections) IndexReaderContext(org.apache.lucene.index.IndexReaderContext) InputStream(java.io.InputStream) LeafReader(org.apache.lucene.index.LeafReader) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) QueryBuilder(org.opensearch.index.query.QueryBuilder) AbstractQueryBuilder(org.opensearch.index.query.AbstractQueryBuilder) BinaryDocValues(org.apache.lucene.index.BinaryDocValues) Version(org.opensearch.Version) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStreamStreamInput(org.opensearch.common.io.stream.InputStreamStreamInput) NamedWriteableAwareStreamInput(org.opensearch.common.io.stream.NamedWriteableAwareStreamInput) StreamInput(org.opensearch.common.io.stream.StreamInput) NamedWriteableAwareStreamInput(org.opensearch.common.io.stream.NamedWriteableAwareStreamInput) BytesRef(org.apache.lucene.util.BytesRef) InputStreamStreamInput(org.opensearch.common.io.stream.InputStreamStreamInput)

Example 3 with MappedFieldType

use of org.opensearch.index.mapper.MappedFieldType in project OpenSearch by opensearch-project.

the class PercolateQueryBuilder method doToQuery.

@Override
protected Query doToQuery(QueryShardContext context) throws IOException {
    if (context.allowExpensiveQueries() == false) {
        throw new OpenSearchException("[percolate] queries cannot be executed when '" + ALLOW_EXPENSIVE_QUERIES.getKey() + "' is set to false.");
    }
    // Call nowInMillis() so that this query becomes un-cacheable since we
    // can't be sure that it doesn't use now or scripts
    context.nowInMillis();
    if (indexedDocumentIndex != null || indexedDocumentId != null || documentSupplier != null) {
        throw new IllegalStateException("query builder must be rewritten first");
    }
    if (documents.isEmpty()) {
        throw new IllegalStateException("no document to percolate");
    }
    MappedFieldType fieldType = context.fieldMapper(field);
    if (fieldType == null) {
        throw new QueryShardException(context, "field [" + field + "] does not exist");
    }
    if (!(fieldType instanceof PercolatorFieldMapper.PercolatorFieldType)) {
        throw new QueryShardException(context, "expected field [" + field + "] to be of type [percolator], but is of type [" + fieldType.typeName() + "]");
    }
    final List<ParsedDocument> docs = new ArrayList<>();
    final DocumentMapper docMapper;
    final MapperService mapperService = context.getMapperService();
    String type = mapperService.documentMapper().type();
    if (documentType != null) {
        deprecationLogger.deprecate("percolate_with_document_type", DOCUMENT_TYPE_DEPRECATION_MESSAGE);
        if (documentType.equals(type) == false) {
            throw new IllegalArgumentException("specified document_type [" + documentType + "] is not equal to the actual type [" + type + "]");
        }
    }
    docMapper = mapperService.documentMapper(type);
    for (BytesReference document : documents) {
        docs.add(docMapper.parse(new SourceToParse(context.index().getName(), type, "_temp_id", document, documentXContentType)));
    }
    FieldNameAnalyzer fieldNameAnalyzer = (FieldNameAnalyzer) docMapper.mappers().indexAnalyzer();
    // Need to this custom impl because FieldNameAnalyzer is strict and the percolator sometimes isn't when
    // 'index.percolator.map_unmapped_fields_as_string' is enabled:
    Analyzer analyzer = new DelegatingAnalyzerWrapper(Analyzer.PER_FIELD_REUSE_STRATEGY) {

        @Override
        protected Analyzer getWrappedAnalyzer(String fieldName) {
            Analyzer analyzer = fieldNameAnalyzer.analyzers().get(fieldName);
            if (analyzer != null) {
                return analyzer;
            } else {
                return context.getIndexAnalyzers().getDefaultIndexAnalyzer();
            }
        }
    };
    final IndexSearcher docSearcher;
    final boolean excludeNestedDocuments;
    if (docs.size() > 1 || docs.get(0).docs().size() > 1) {
        assert docs.size() != 1 || docMapper.hasNestedObjects();
        docSearcher = createMultiDocumentSearcher(analyzer, docs);
        excludeNestedDocuments = docMapper.hasNestedObjects() && docs.stream().map(ParsedDocument::docs).mapToInt(List::size).anyMatch(size -> size > 1);
    } else {
        MemoryIndex memoryIndex = MemoryIndex.fromDocument(docs.get(0).rootDoc(), analyzer, true, false);
        docSearcher = memoryIndex.createSearcher();
        docSearcher.setQueryCache(null);
        excludeNestedDocuments = false;
    }
    PercolatorFieldMapper.PercolatorFieldType pft = (PercolatorFieldMapper.PercolatorFieldType) fieldType;
    String name = this.name != null ? this.name : pft.name();
    QueryShardContext percolateShardContext = wrap(context);
    PercolatorFieldMapper.configureContext(percolateShardContext, pft.mapUnmappedFieldsAsText);
    ;
    PercolateQuery.QueryStore queryStore = createStore(pft.queryBuilderField, percolateShardContext);
    return pft.percolateQuery(name, queryStore, documents, docSearcher, excludeNestedDocuments, context.indexVersionCreated());
}
Also used : IndexSearcher(org.apache.lucene.search.IndexSearcher) ArrayList(java.util.ArrayList) FieldNameAnalyzer(org.opensearch.index.analysis.FieldNameAnalyzer) Analyzer(org.apache.lucene.analysis.Analyzer) ParsedDocument(org.opensearch.index.mapper.ParsedDocument) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) QueryShardException(org.opensearch.index.query.QueryShardException) QueryShardContext(org.opensearch.index.query.QueryShardContext) BytesReference(org.opensearch.common.bytes.BytesReference) FieldNameAnalyzer(org.opensearch.index.analysis.FieldNameAnalyzer) DocumentMapper(org.opensearch.index.mapper.DocumentMapper) SourceToParse(org.opensearch.index.mapper.SourceToParse) MemoryIndex(org.apache.lucene.index.memory.MemoryIndex) DelegatingAnalyzerWrapper(org.apache.lucene.analysis.DelegatingAnalyzerWrapper) OpenSearchException(org.opensearch.OpenSearchException) MapperService(org.opensearch.index.mapper.MapperService)

Example 4 with MappedFieldType

use of org.opensearch.index.mapper.MappedFieldType in project OpenSearch by opensearch-project.

the class ChildrenAggregationBuilder method resolveConfig.

@Override
protected ValuesSourceConfig resolveConfig(QueryShardContext queryShardContext) {
    ValuesSourceConfig config;
    ParentJoinFieldMapper parentJoinFieldMapper = ParentJoinFieldMapper.getMapper(queryShardContext.getMapperService());
    if (parentJoinFieldMapper == null) {
        // Unmapped field case
        config = ValuesSourceConfig.resolveUnmapped(defaultValueSourceType(), queryShardContext);
        return config;
    }
    ParentIdFieldMapper parentIdFieldMapper = parentJoinFieldMapper.getParentIdFieldMapper(childType, false);
    if (parentIdFieldMapper == null) {
        // Unmapped field case
        config = ValuesSourceConfig.resolveUnmapped(defaultValueSourceType(), queryShardContext);
        return config;
    }
    parentFilter = parentIdFieldMapper.getParentFilter();
    childFilter = parentIdFieldMapper.getChildFilter(childType);
    MappedFieldType fieldType = parentIdFieldMapper.fieldType();
    config = ValuesSourceConfig.resolveFieldOnly(fieldType, queryShardContext);
    return config;
}
Also used : ParentIdFieldMapper(org.opensearch.join.mapper.ParentIdFieldMapper) ParentJoinFieldMapper(org.opensearch.join.mapper.ParentJoinFieldMapper) ValuesSourceConfig(org.opensearch.search.aggregations.support.ValuesSourceConfig) MappedFieldType(org.opensearch.index.mapper.MappedFieldType)

Example 5 with MappedFieldType

use of org.opensearch.index.mapper.MappedFieldType in project OpenSearch by opensearch-project.

the class ParentAggregationBuilder method resolveConfig.

@Override
protected ValuesSourceConfig resolveConfig(QueryShardContext queryShardContext) {
    ValuesSourceConfig config;
    ParentJoinFieldMapper parentJoinFieldMapper = ParentJoinFieldMapper.getMapper(queryShardContext.getMapperService());
    ParentIdFieldMapper parentIdFieldMapper = parentJoinFieldMapper.getParentIdFieldMapper(childType, false);
    if (parentIdFieldMapper != null) {
        parentFilter = parentIdFieldMapper.getParentFilter();
        childFilter = parentIdFieldMapper.getChildFilter(childType);
        MappedFieldType fieldType = parentIdFieldMapper.fieldType();
        config = ValuesSourceConfig.resolveFieldOnly(fieldType, queryShardContext);
    } else {
        // unmapped case
        config = ValuesSourceConfig.resolveUnmapped(defaultValueSourceType(), queryShardContext);
    }
    return config;
}
Also used : ParentIdFieldMapper(org.opensearch.join.mapper.ParentIdFieldMapper) ParentJoinFieldMapper(org.opensearch.join.mapper.ParentJoinFieldMapper) ValuesSourceConfig(org.opensearch.search.aggregations.support.ValuesSourceConfig) MappedFieldType(org.opensearch.index.mapper.MappedFieldType)

Aggregations

MappedFieldType (org.opensearch.index.mapper.MappedFieldType)316 MatchAllDocsQuery (org.apache.lucene.search.MatchAllDocsQuery)147 IndexReader (org.apache.lucene.index.IndexReader)143 Directory (org.apache.lucene.store.Directory)133 SortedNumericDocValuesField (org.apache.lucene.document.SortedNumericDocValuesField)127 RandomIndexWriter (org.apache.lucene.index.RandomIndexWriter)127 IndexSearcher (org.apache.lucene.search.IndexSearcher)121 Document (org.apache.lucene.document.Document)93 NumericDocValuesField (org.apache.lucene.document.NumericDocValuesField)80 ArrayList (java.util.ArrayList)73 BytesRef (org.apache.lucene.util.BytesRef)63 Query (org.apache.lucene.search.Query)58 Script (org.opensearch.script.Script)51 IntPoint (org.apache.lucene.document.IntPoint)49 IOException (java.io.IOException)48 SortedSetDocValuesField (org.apache.lucene.document.SortedSetDocValuesField)48 List (java.util.List)47 LongPoint (org.apache.lucene.document.LongPoint)47 NumberFieldMapper (org.opensearch.index.mapper.NumberFieldMapper)46 KeywordFieldMapper (org.opensearch.index.mapper.KeywordFieldMapper)43