Search in sources :

Example 6 with MappedFieldType

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

the class SimpleQueryStringQueryParser method newPrefixQuery.

@Override
public Query newPrefixQuery(String text) {
    List<Query> disjuncts = new ArrayList<>();
    for (Map.Entry<String, Float> entry : weights.entrySet()) {
        final String fieldName = entry.getKey();
        final MappedFieldType ft = context.fieldMapper(fieldName);
        if (ft == null) {
            disjuncts.add(newUnmappedFieldQuery(fieldName));
            continue;
        }
        try {
            if (settings.analyzeWildcard()) {
                Query analyzedQuery = newPossiblyAnalyzedQuery(fieldName, text, getAnalyzer(ft));
                if (analyzedQuery != null) {
                    disjuncts.add(wrapWithBoost(analyzedQuery, entry.getValue()));
                }
            } else {
                BytesRef term = getAnalyzer(ft).normalize(fieldName, text);
                Query query = ft.prefixQuery(term.utf8ToString(), null, context);
                disjuncts.add(wrapWithBoost(query, entry.getValue()));
            }
        } catch (RuntimeException e) {
            disjuncts.add(rethrowUnlessLenient(e));
        }
    }
    if (disjuncts.size() == 1) {
        return disjuncts.get(0);
    }
    return new DisjunctionMaxQuery(disjuncts, 1.0f);
}
Also used : Query(org.apache.lucene.search.Query) MatchNoDocsQuery(org.apache.lucene.search.MatchNoDocsQuery) Queries.newUnmappedFieldQuery(org.opensearch.common.lucene.search.Queries.newUnmappedFieldQuery) PrefixQuery(org.apache.lucene.search.PrefixQuery) DisjunctionMaxQuery(org.apache.lucene.search.DisjunctionMaxQuery) SynonymQuery(org.apache.lucene.search.SynonymQuery) BooleanQuery(org.apache.lucene.search.BooleanQuery) BoostQuery(org.apache.lucene.search.BoostQuery) DisjunctionMaxQuery(org.apache.lucene.search.DisjunctionMaxQuery) ArrayList(java.util.ArrayList) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) Map(java.util.Map) BytesRef(org.apache.lucene.util.BytesRef)

Example 7 with MappedFieldType

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

the class FieldValueFactorFunctionBuilder method doToFunction.

@Override
protected ScoreFunction doToFunction(QueryShardContext context) {
    MappedFieldType fieldType = context.getMapperService().fieldType(field);
    IndexNumericFieldData fieldData = null;
    if (fieldType == null) {
        if (missing == null) {
            throw new OpenSearchException("Unable to find a field mapper for field [" + field + "]. No 'missing' value defined.");
        }
    } else {
        fieldData = context.getForField(fieldType);
    }
    return new FieldValueFactorFunction(field, factor, modifier, missing, fieldData, getFunctionName());
}
Also used : FieldValueFactorFunction(org.opensearch.common.lucene.search.function.FieldValueFactorFunction) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) IndexNumericFieldData(org.opensearch.index.fielddata.IndexNumericFieldData) OpenSearchException(org.opensearch.OpenSearchException)

Example 8 with MappedFieldType

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

the class RandomScoreFunctionBuilder method doToFunction.

@Override
protected ScoreFunction doToFunction(QueryShardContext context) {
    final int salt = (context.index().getName().hashCode() << 10) | context.getShardId();
    if (seed == null) {
        // DocID-based random score generation
        return new RandomScoreFunction(hash(context.nowInMillis()), salt, null, getFunctionName());
    } else {
        final MappedFieldType fieldType;
        if (field != null) {
            fieldType = context.getMapperService().fieldType(field);
        } else {
            deprecationLogger.deprecate("seed_requires_field", "OpenSearch requires that a [field] parameter is provided when a [seed] is set");
            fieldType = context.getMapperService().fieldType(IdFieldMapper.NAME);
        }
        if (fieldType == null) {
            if (context.getMapperService().documentMapper() == null) {
                // no mappings: the index is empty anyway
                return new RandomScoreFunction(hash(context.nowInMillis()), salt, null, getFunctionName());
            }
            throw new IllegalArgumentException("Field [" + field + "] is not mapped on [" + context.index() + "] and cannot be used as a source of random numbers.");
        }
        int seed;
        if (this.seed != null) {
            seed = this.seed;
        } else {
            seed = hash(context.nowInMillis());
        }
        return new RandomScoreFunction(seed, salt, context.getForField(fieldType), getFunctionName());
    }
}
Also used : MappedFieldType(org.opensearch.index.mapper.MappedFieldType) RandomScoreFunction(org.opensearch.common.lucene.search.function.RandomScoreFunction)

Example 9 with MappedFieldType

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

the class SliceBuilder method toFilter.

/**
 * Converts this QueryBuilder to a lucene {@link Query}.
 *
 * @param context Additional information needed to build the query
 */
public Query toFilter(ClusterService clusterService, ShardSearchRequest request, QueryShardContext context, Version minNodeVersion) {
    final MappedFieldType type = context.fieldMapper(field);
    if (type == null) {
        throw new IllegalArgumentException("field " + field + " not found");
    }
    int shardId = request.shardId().id();
    int numShards = context.getIndexSettings().getNumberOfShards();
    if ((request.preference() != null || request.indexRoutings().length > 0)) {
        GroupShardsIterator<ShardIterator> group = buildShardIterator(clusterService, request);
        assert group.size() <= numShards : "index routing shards: " + group.size() + " cannot be greater than total number of shards: " + numShards;
        if (group.size() < numShards) {
            /*
                 * The routing of this request targets a subset of the shards of this index so we need to we retrieve
                 * the original {@link GroupShardsIterator} and compute the request shard id and number of
                 * shards from it.
                 */
            numShards = group.size();
            int ord = 0;
            shardId = -1;
            // remap the original shard id with its index (position) in the sorted shard iterator.
            for (ShardIterator it : group) {
                assert it.shardId().getIndex().equals(request.shardId().getIndex());
                if (request.shardId().equals(it.shardId())) {
                    shardId = ord;
                    break;
                }
                ++ord;
            }
            assert shardId != -1 : "shard id: " + request.shardId().getId() + " not found in index shard routing";
        }
    }
    String field = this.field;
    boolean useTermQuery = false;
    if ("_uid".equals(field)) {
        // on new indices, the _id acts as a _uid
        field = IdFieldMapper.NAME;
        if (context.getIndexSettings().getIndexVersionCreated().onOrAfter(LegacyESVersion.V_7_0_0)) {
            throw new IllegalArgumentException("Computing slices on the [_uid] field is illegal for 7.x indices, use [_id] instead");
        }
        DEPRECATION_LOG.deprecate("slice_on_uid", "Computing slices on the [_uid] field is deprecated for 6.x indices, use [_id] instead");
        useTermQuery = true;
    } else if (IdFieldMapper.NAME.equals(field)) {
        useTermQuery = true;
    } else if (type.hasDocValues() == false) {
        throw new IllegalArgumentException("cannot load numeric doc values on " + field);
    } else {
        IndexFieldData ifm = context.getForField(type);
        if (ifm instanceof IndexNumericFieldData == false) {
            throw new IllegalArgumentException("cannot load numeric doc values on " + field);
        }
    }
    if (numShards == 1) {
        return useTermQuery ? new TermsSliceQuery(field, id, max) : new DocValuesSliceQuery(field, id, max);
    }
    if (max >= numShards) {
        // the number of slices is greater than the number of shards
        // in such case we can reduce the number of requested shards by slice
        // first we check if the slice is responsible of this shard
        int targetShard = id % numShards;
        if (targetShard != shardId) {
            // the shard is not part of this slice, we can skip it.
            return new MatchNoDocsQuery("this shard is not part of the slice");
        }
        // compute the number of slices where this shard appears
        int numSlicesInShard = max / numShards;
        int rest = max % numShards;
        if (rest > targetShard) {
            numSlicesInShard++;
        }
        if (numSlicesInShard == 1) {
            // this shard has only one slice so we must check all the documents
            return new MatchAllDocsQuery();
        }
        // get the new slice id for this shard
        int shardSlice = id / numShards;
        return useTermQuery ? new TermsSliceQuery(field, shardSlice, numSlicesInShard) : new DocValuesSliceQuery(field, shardSlice, numSlicesInShard);
    }
    // the number of shards is greater than the number of slices
    // check if the shard is assigned to the slice
    int targetSlice = shardId % max;
    if (id != targetSlice) {
        // the shard is not part of this slice, we can skip it.
        return new MatchNoDocsQuery("this shard is not part of the slice");
    }
    return new MatchAllDocsQuery();
}
Also used : MatchNoDocsQuery(org.apache.lucene.search.MatchNoDocsQuery) IndexNumericFieldData(org.opensearch.index.fielddata.IndexNumericFieldData) MatchAllDocsQuery(org.apache.lucene.search.MatchAllDocsQuery) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) ShardIterator(org.opensearch.cluster.routing.ShardIterator) IndexFieldData(org.opensearch.index.fielddata.IndexFieldData)

Example 10 with MappedFieldType

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

the class FieldSortBuilder method buildBucketedSort.

@Override
public BucketedSort buildBucketedSort(QueryShardContext context, int bucketSize, BucketedSort.ExtraData extra) throws IOException {
    if (DOC_FIELD_NAME.equals(fieldName)) {
        throw new IllegalArgumentException("sorting by _doc is not supported");
    }
    MappedFieldType fieldType = context.fieldMapper(fieldName);
    Nested nested = nested(context, fieldType);
    if (fieldType == null) {
        fieldType = resolveUnmappedType(context);
    }
    IndexFieldData<?> fieldData = context.getForField(fieldType);
    if (fieldData instanceof IndexNumericFieldData == false && (sortMode == SortMode.SUM || sortMode == SortMode.AVG || sortMode == SortMode.MEDIAN)) {
        throw new QueryShardException(context, "we only support AVG, MEDIAN and SUM on number based fields");
    }
    if (numericType != null) {
        if (fieldData instanceof IndexNumericFieldData == false) {
            throw new QueryShardException(context, "[numeric_type] option cannot be set on a non-numeric field, got " + fieldType.typeName());
        }
        IndexNumericFieldData numericFieldData = (IndexNumericFieldData) fieldData;
        NumericType resolvedType = resolveNumericType(numericType);
        return numericFieldData.newBucketedSort(resolvedType, context.bigArrays(), missing, localSortMode(), nested, order, fieldType.docValueFormat(null, null), bucketSize, extra);
    }
    try {
        return fieldData.newBucketedSort(context.bigArrays(), missing, localSortMode(), nested, order, fieldType.docValueFormat(null, null), bucketSize, extra);
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException("error building sort for field [" + fieldName + "] of type [" + fieldType.typeName() + "] in index [" + context.index().getName() + "]: " + e.getMessage(), e);
    }
}
Also used : NumericType(org.opensearch.index.fielddata.IndexNumericFieldData.NumericType) MappedFieldType(org.opensearch.index.mapper.MappedFieldType) Nested(org.opensearch.index.fielddata.IndexFieldData.XFieldComparatorSource.Nested) IndexNumericFieldData(org.opensearch.index.fielddata.IndexNumericFieldData) QueryShardException(org.opensearch.index.query.QueryShardException)

Aggregations

MappedFieldType (org.opensearch.index.mapper.MappedFieldType)321 MatchAllDocsQuery (org.apache.lucene.search.MatchAllDocsQuery)150 IndexReader (org.apache.lucene.index.IndexReader)146 Directory (org.apache.lucene.store.Directory)136 SortedNumericDocValuesField (org.apache.lucene.document.SortedNumericDocValuesField)130 RandomIndexWriter (org.apache.lucene.tests.index.RandomIndexWriter)127 IndexSearcher (org.apache.lucene.search.IndexSearcher)124 Document (org.apache.lucene.document.Document)96 NumericDocValuesField (org.apache.lucene.document.NumericDocValuesField)83 ArrayList (java.util.ArrayList)76 BytesRef (org.apache.lucene.util.BytesRef)64 Query (org.apache.lucene.search.Query)57 Script (org.opensearch.script.Script)51 IntPoint (org.apache.lucene.document.IntPoint)49 IOException (java.io.IOException)48 List (java.util.List)48 SortedSetDocValuesField (org.apache.lucene.document.SortedSetDocValuesField)48 LongPoint (org.apache.lucene.document.LongPoint)47 NumberFieldMapper (org.opensearch.index.mapper.NumberFieldMapper)46 KeywordFieldMapper (org.opensearch.index.mapper.KeywordFieldMapper)42