@Override protected ScoreFunction doToFunction(QueryShardContext context) { final int salt = (context.index().getName().hashCode() << 10) | context.getShardId(); if (seed == null) { return new RandomScoreFunction(hash(context.nowInMillis()), salt, null); } else { final MappedFieldType fieldType; if (field != null) { fieldType = context.getMapperService().fullName(field); } else { DEPRECATION_LOGGER.deprecated( "As of version 7.0 Elasticsearch will require that a [field] parameter is provided when a [seed] is set"); if (context.getIndexSettings().isSingleType()) { fieldType = context.getMapperService().fullName(IdFieldMapper.NAME); } else { fieldType = context.getMapperService().fullName(UidFieldMapper.NAME); if (context.getMapperService().types().isEmpty()) { return new RandomScoreFunction(hash(context.nowInMillis()), salt, null); throw new IllegalArgumentException("Field [" + field + "] is not mapped on [" + context.index() + "] and cannot be used as a source of random numbers."); seed = this.seed; } else { seed = hash(context.nowInMillis()); return new RandomScoreFunction(seed, salt, context.getForField(fieldType));
@Override protected Query doToQuery(QueryShardContext context) throws QueryShardException, IOException { final int maxAllowedRegexLength = context.getIndexSettings().getMaxRegexLength(); if (value.length() > maxAllowedRegexLength) { throw new IllegalArgumentException( "The length of regex [" + value.length() + "] used in the Regexp Query request has exceeded " + "the allowed maximum of [" + maxAllowedRegexLength + "]. " + "This maximum can be set by changing the [" + IndexSettings.MAX_REGEX_LENGTH_SETTING.getKey() + "] index level setting."); } MultiTermQuery.RewriteMethod method = QueryParsers.parseRewriteMethod(rewrite, null, LoggingDeprecationHandler.INSTANCE); Query query = null; MappedFieldType fieldType = context.fieldMapper(fieldName); if (fieldType != null) { query = fieldType.regexpQuery(value, flagsValue, maxDeterminizedStates, method, context); } if (query == null) { RegexpQuery regexpQuery = new RegexpQuery(new Term(fieldName, BytesRefs.toBytesRef(value)), flagsValue, maxDeterminizedStates); if (method != null) { regexpQuery.setRewriteMethod(method); } query = regexpQuery; } return query; }
/** * Returns the narrowed down explicit types, or, if not set, all types. */ public Collection<String> queryTypes() { String[] types = getTypes(); if (types == null || types.length == 0) { return getMapperService().types(); } if (types.length == 1 && types[0].equals("_all")) { return getMapperService().types(); } return Arrays.asList(types); }
public QueryShardContext(QueryShardContext source) { this(source.shardId, source.indexSettings, source.bitsetFilterCache, source.indexFieldDataService, source.mapperService, source.similarityService, source.scriptService, source.getXContentRegistry(), source.getWriteableRegistry(), source.client, source.reader, source.nowInMillis, source.clusterAlias); this.types = source.getTypes(); }
@Override protected ScoreFunction doToFunction(QueryShardContext context) { MappedFieldType fieldType = context.getMapperService().fullName(field); IndexNumericFieldData fieldData = null; if (fieldType == null) { if(missing == null) { throw new ElasticsearchException("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); }
private Query parentFieldDoToQuery(QueryShardContext context) throws IOException { Query innerQuery; String[] previousTypes = context.getTypes(); context.setTypes(type); try { innerQuery = query.toQuery(context); } finally { context.setTypes(previousTypes); DocumentMapper parentDocMapper = context.documentMapper(type); if (parentDocMapper == null) { if (ignoreUnmapped) { for (DocumentMapper documentMapper : context.getMapperService().docMappers(false)) { ParentFieldMapper parentFieldMapper = documentMapper.parentFieldMapper(); if (parentFieldMapper.active() && type.equals(parentFieldMapper.type())) { DocumentMapper documentMapper = context.getMapperService().documentMapper(childTypes.iterator().next()); childrenQuery = documentMapper.typeFilter(context); } else { BooleanQuery.Builder childrenFilter = new BooleanQuery.Builder(); for (String childrenTypeStr : childTypes) { DocumentMapper documentMapper = context.getMapperService().documentMapper(childrenTypeStr); childrenFilter.add(documentMapper.typeFilter(context), BooleanClause.Occur.SHOULD); final SortedSetDVOrdinalsIndexFieldData fieldData = context.getForField(parentType); return new HasChildQueryBuilder.LateParsingQuery(childrenQuery, innerQuery, score ? ScoreMode.Max : ScoreMode.None,
private Query joinFieldDoToQuery(QueryShardContext context) throws IOException { ParentJoinFieldMapper joinFieldMapper = ParentJoinFieldMapper.getMapper(context.getMapperService()); if (joinFieldMapper == null) { if (ignoreUnmapped) { return new MatchNoDocsQuery(); } else { throw new QueryShardException(context, "[" + NAME + "] no join field has been configured"); } } ParentIdFieldMapper parentIdFieldMapper = joinFieldMapper.getParentIdFieldMapper(type, true); if (parentIdFieldMapper != null) { Query parentFilter = parentIdFieldMapper.getParentFilter(); Query innerQuery = Queries.filtered(query.toQuery(context), parentFilter); Query childFilter = parentIdFieldMapper.getChildrenFilter(); MappedFieldType fieldType = parentIdFieldMapper.fieldType(); final SortedSetDVOrdinalsIndexFieldData fieldData = context.getForField(fieldType); return new HasChildQueryBuilder.LateParsingQuery(childFilter, innerQuery, HasChildQueryBuilder.DEFAULT_MIN_CHILDREN, HasChildQueryBuilder.DEFAULT_MAX_CHILDREN, fieldType.name(), score ? ScoreMode.Max : ScoreMode.None, fieldData, context.getSearchSimilarity()); } else { if (ignoreUnmapped) { return new MatchNoDocsQuery(); } else { throw new QueryShardException(context, "[" + NAME + "] join field [" + joinFieldMapper.name() + "] doesn't hold [" + type + "] as a parent"); } } }
MappedFieldType fieldType = context.fieldMapper(fieldName); if (fieldType == null) { if (unmappedType != null) { fieldType = context.getMapperService().unmappedFieldType(unmappedType); } else { throw new QueryShardException(context, "No mapping found for [" + fieldName + "] in order to sort on"); if (context.indexVersionCreated().before(Version.V_6_5_0) && nestedSort.getMaxChildren() != Integer.MAX_VALUE) { throw new QueryShardException(context, "max_children is only supported on v6.5.0 or higher"); IndexFieldData<?> fieldData = context.getForField(fieldType); if (fieldData instanceof IndexNumericFieldData == false && (sortMode == SortMode.SUM || sortMode == SortMode.AVG || sortMode == SortMode.MEDIAN)) {
mltQuery.setSimilarity(context.getSearchSimilarity()); Analyzer analyzerObj = context.getIndexAnalyzers().get(analyzer); if (analyzerObj == null) { analyzerObj = context.getMapperService().searchAnalyzer(); List<String> moreLikeFields = new ArrayList<>(); if (useDefaultField) { moreLikeFields = context.defaultFields(); } else { for (String field : fields) { MappedFieldType fieldType = context.fieldMapper(field); if (fieldType != null && SUPPORTED_FIELD_TYPES.contains(fieldType.getClass()) == false) { if (failOnUnsupportedField) {
@Override public Query termsQuery(List<?> values, QueryShardContext context) { if (context.getIndexSettings().isSingleType()) { Collection<String> indexTypes = context.getMapperService().types(); if (indexTypes.isEmpty()) { return new MatchNoDocsQuery("No types"); .map(this::indexedValueForSearch) .anyMatch(indexType::equals)) { if (context.getMapperService().hasNested()) { return Queries.newNonNestedFilter(context.indexVersionCreated()); } else { return new MatchAllDocsQuery();
boolean isLenient = lenient == null ? context.queryStringLenient() : lenient; if (defaultField != null) { if (Regex.isMatchAllPattern(defaultField)) { queryParser = new QueryStringQueryParser(context, resolvedFields, isLenient); } else { List<String> defaultFields = context.defaultFields(); if (context.getMapperService().allEnabled() == false && defaultFields.size() == 1 && AllFieldMapper.NAME.equals(defaultFields.get(0))) { NamedAnalyzer namedAnalyzer = context.getIndexAnalyzers().get(analyzer); if (namedAnalyzer == null) { throw new QueryShardException(context, "[query_string] analyzer [" + analyzer + "] not found"); NamedAnalyzer forceQuoteAnalyzer = context.getIndexAnalyzers().get(quoteAnalyzer); if (forceQuoteAnalyzer == null) { throw new QueryShardException(context, "[query_string] quote_analyzer [" + quoteAnalyzer + "] not found"); queryParser.setQuoteFieldSuffix(quoteFieldSuffix); queryParser.setAllowLeadingWildcard(allowLeadingWildcard == null ? context.queryStringAllowLeadingWildcard() : allowLeadingWildcard); queryParser.setAnalyzeWildcard(analyzeWildcard == null ? context.queryStringAnalyzeWildcard() : analyzeWildcard); queryParser.setEnablePositionIncrements(enablePositionIncrements); queryParser.setFuzziness(fuzziness);
/** * @param context The query shard context. * @param defaultField The default field for query terms. */ public QueryStringQueryParser(QueryShardContext context, String defaultField) { this(context, defaultField, Collections.emptyMap(), false, context.getMapperService().searchAnalyzer()); }
private LongValuesSource createValuesSource(QueryShardContext context) { LongValuesSource longValuesSource; if (minimumShouldMatchField != null) { MappedFieldType msmFieldType = context.fieldMapper(minimumShouldMatchField); if (msmFieldType == null) { throw new QueryShardException(context, "failed to find minimum_should_match field [" + minimumShouldMatchField + "]"); } IndexNumericFieldData fieldData = context.getForField(msmFieldType); longValuesSource = new FieldValuesSource(fieldData); } else if (minimumShouldMatchScript != null) { TermsSetQueryScript.Factory factory = context.getScriptService().compile(minimumShouldMatchScript, TermsSetQueryScript.CONTEXT); Map<String, Object> params = new HashMap<>(); params.putAll(minimumShouldMatchScript.getParams()); params.put("num_terms", values.size()); longValuesSource = new ScriptLongValueSource(minimumShouldMatchScript, factory.newFactory(params, context.lookup())); } else { throw new IllegalStateException("No minimum should match has been specified"); } return longValuesSource; }
final MappedFieldType type = context.fieldMapper(field); if (type == null) { throw new IllegalArgumentException("field " + field + " not found"); int numShards = context.getIndexSettings().getNumberOfShards(); if (minNodeVersion.onOrAfter(Version.V_6_4_0) && (request.preference() != null || request.indexRoutings().length > 0)) { boolean useTermQuery = false; if (UidFieldMapper.NAME.equals(field)) { if (context.getIndexSettings().isSingleType()) { if (context.getIndexSettings().isSingleType() == 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);
@Override public SuggestionContext build(QueryShardContext context) throws IOException { CompletionSuggestionContext suggestionContext = new CompletionSuggestionContext(context); // copy over common settings to each suggestion builder final MapperService mapperService = context.getMapperService(); populateCommonFields(mapperService, suggestionContext); suggestionContext.setSkipDuplicates(skipDuplicates); suggestionContext.setFuzzyOptions(fuzzyOptions); suggestionContext.setRegexOptions(regexOptions); if (shardSize != null) { suggestionContext.setShardSize(shardSize); } MappedFieldType mappedFieldType = mapperService.fullName(suggestionContext.getField()); if (mappedFieldType == null || mappedFieldType instanceof CompletionFieldMapper.CompletionFieldType == false) { throw new IllegalArgumentException("Field [" + suggestionContext.getField() + "] is not a completion suggest field"); } if (mappedFieldType instanceof CompletionFieldMapper.CompletionFieldType) { CompletionFieldMapper.CompletionFieldType type = (CompletionFieldMapper.CompletionFieldType) mappedFieldType; suggestionContext.setFieldType(type); if (type.hasContextMappings() && contextBytes != null) { Map<String, List<ContextMapping.InternalQueryContext>> queryContexts = parseContextBytes(contextBytes, context.getXContentRegistry(), type.getContextMappings()); suggestionContext.setQueryContexts(queryContexts); } else if (contextBytes != null) { throw new IllegalArgumentException("suggester [" + type.name() + "] doesn't expect any context"); } } assert suggestionContext.getFieldType() != null : "no completion field type set"; return suggestionContext; }
Query parseGroup(Type type, String field, Float boostValue, Object value, String minimumShouldMatch) throws IOException { if (context.fieldMapper(field) == null) { return null; // indicates to the caller that this field is unmapped and should be disregarded } return parseAndApply(type, field, value, minimumShouldMatch, boostValue); }
@Override @SuppressWarnings("unchecked") public <IFD extends IndexFieldData<?>> IFD getForField(MappedFieldType fieldType) { IndexFieldData.Builder builder = fieldType.fielddataBuilder(shardContext.getFullyQualifiedIndex().getName()); IndexFieldDataCache cache = new IndexFieldDataCache.None(); CircuitBreakerService circuitBreaker = new NoneCircuitBreakerService(); return (IFD) builder.build(shardContext.getIndexSettings(), fieldType, cache, circuitBreaker, shardContext.getMapperService()); } };
@Override public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, QueryShardContext context) { if (context.getIndexSettings().isSingleType() == false) { return new TermRangeQuery(name(), lowerTerm == null ? null : indexedValueForSearch(lowerTerm), upperTerm == null ? null : indexedValueForSearch(upperTerm), includeLower, includeUpper); "Running [range] query on [_type] field for an index with a single type. As types are deprecated," + " this functionality will be removed in future releases."); Collection<String> types = context.getMapperService().types(); String type = types.iterator().hasNext() ? types.iterator().next() : null; if (type != null) {
resolvedFieldsAndWeights = QueryParserHelper.resolveMappingFields(context, fieldsAndWeights); } else { List<String> defaultFields = context.defaultFields(); if (context.getMapperService().allEnabled() == false && defaultFields.size() == 1 && AllFieldMapper.NAME.equals(defaultFields.get(0))) { sqp = new SimpleQueryStringQueryParser(resolvedFieldsAndWeights, flags, newSettings, context); } else { Analyzer luceneAnalyzer = context.getIndexAnalyzers().get(analyzer); if (luceneAnalyzer == null) { throw new QueryShardException(context, "[" + SimpleQueryStringBuilder.NAME + "] analyzer [" + analyzer
static PercolateQuery.QueryStore createStore(MappedFieldType queryBuilderFieldType, QueryShardContext context, boolean mapUnmappedFieldsAsString) { Version indexVersion = context.indexVersionCreated(); NamedWriteableRegistry registry = context.getWriteableRegistry(); return ctx -> { LeafReader leafReader = ctx.reader(); XContent xContent = PercolatorFieldMapper.QUERY_BUILDER_CONTENT_TYPE.xContent(); try (XContentParser sourceParser = xContent .createParser(context.getXContentRegistry(), LoggingDeprecationHandler.INSTANCE, qbSource.bytes, qbSource.offset, qbSource.length)) { return parseQuery(context, mapUnmappedFieldsAsString, sourceParser);