org.elasticsearch.index.query.QueryParseContext Java Examples

The following examples show how to use org.elasticsearch.index.query.QueryParseContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DecayFunctionParser.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
private AbstractDistanceScoreFunction parseVariable(String fieldName, XContentParser parser, QueryParseContext parseContext, MultiValueMode mode) throws IOException {

        // now, the field must exist, else we cannot read the value for
        // the doc later
        MappedFieldType fieldType = parseContext.fieldMapper(fieldName);
        if (fieldType == null) {
            throw new QueryParsingException(parseContext, "unknown field [{}]", fieldName);
        }

        // dates and time need special handling
        parser.nextToken();
        if (fieldType instanceof DateFieldMapper.DateFieldType) {
            return parseDateVariable(fieldName, parser, parseContext, (DateFieldMapper.DateFieldType) fieldType, mode);
        } else if (fieldType instanceof GeoPointFieldMapper.GeoPointFieldType) {
            return parseGeoVariable(fieldName, parser, parseContext, (GeoPointFieldMapper.GeoPointFieldType) fieldType, mode);
        } else if (fieldType instanceof NumberFieldMapper.NumberFieldType) {
            return parseNumberVariable(fieldName, parser, parseContext, (NumberFieldMapper.NumberFieldType) fieldType, mode);
        } else {
            throw new QueryParsingException(parseContext, "field [{}] is of type [{}], but only numeric types are supported.", fieldName, fieldType);
        }
    }
 
Example #2
Source File: IpFieldMapper.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public Query termQuery(Object value, @Nullable QueryParseContext context) {
    if (value != null) {
        long[] fromTo;
        if (value instanceof BytesRef) {
            fromTo = cidrMaskToMinMax(((BytesRef) value).utf8ToString());
        } else {
            fromTo = cidrMaskToMinMax(value.toString());
        }
        if (fromTo != null) {
            return rangeQuery(fromTo[0] < 0 ? null : fromTo[0],
                    fromTo[1] < 0 ? null : fromTo[1], true, false);
        }
    }
    return super.termQuery(value, context);
}
 
Example #3
Source File: InnerHitsQueryParserHelper.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public InnerHitsSubSearchContext parse(QueryParseContext parserContext) throws IOException, QueryParsingException {
    String fieldName = null;
    XContentParser.Token token;
    String innerHitName = null;
    SubSearchContext subSearchContext = new SubSearchContext(SearchContext.current());
    try {
        XContentParser parser = parserContext.parser();
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                fieldName = parser.currentName();
            } else if (token.isValue()) {
                if ("name".equals(fieldName)) {
                    innerHitName = parser.textOrNull();
                } else {
                    parseCommonInnerHitOptions(parser, token, fieldName, subSearchContext, sortParseElement, sourceParseElement, highlighterParseElement, scriptFieldsParseElement, fieldDataFieldsParseElement);
                }
            } else {
                parseCommonInnerHitOptions(parser, token, fieldName, subSearchContext, sortParseElement, sourceParseElement, highlighterParseElement, scriptFieldsParseElement, fieldDataFieldsParseElement);
            }
        }
    } catch (Exception e) {
        throw new QueryParsingException(parserContext, "Failed to parse [_inner_hits]", e);
    }
    return new InnerHitsSubSearchContext(innerHitName, subSearchContext);
}
 
Example #4
Source File: FunctionScoreQueryParser.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
private FiltersFunctionScoreQuery.ScoreMode parseScoreMode(QueryParseContext parseContext, XContentParser parser) throws IOException {
    String scoreMode = parser.text();
    if ("avg".equals(scoreMode)) {
        return FiltersFunctionScoreQuery.ScoreMode.Avg;
    } else if ("max".equals(scoreMode)) {
        return FiltersFunctionScoreQuery.ScoreMode.Max;
    } else if ("min".equals(scoreMode)) {
        return FiltersFunctionScoreQuery.ScoreMode.Min;
    } else if ("sum".equals(scoreMode)) {
        return FiltersFunctionScoreQuery.ScoreMode.Sum;
    } else if ("multiply".equals(scoreMode)) {
        return FiltersFunctionScoreQuery.ScoreMode.Multiply;
    } else if ("first".equals(scoreMode)) {
        return FiltersFunctionScoreQuery.ScoreMode.First;
    } else {
        throw new QueryParsingException(parseContext, "failed to parse [{}] query. illegal score_mode [{}]", NAME, scoreMode);
    }
}
 
Example #5
Source File: InnerHitsParseElement.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
private Map<String, InnerHitsContext.BaseInnerHits> parseInnerHits(XContentParser parser, QueryParseContext parseContext, SearchContext searchContext) throws Exception {
    XContentParser.Token token;
    Map<String, InnerHitsContext.BaseInnerHits> innerHitsMap = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token != XContentParser.Token.FIELD_NAME) {
            throw new IllegalArgumentException("Unexpected token " + token + " in [inner_hits]: inner_hit definitions must start with the name of the inner_hit.");
        }
        final String innerHitName = parser.currentName();
        token = parser.nextToken();
        if (token != XContentParser.Token.START_OBJECT) {
            throw new IllegalArgumentException("Inner hit definition for [" + innerHitName + " starts with a [" + token + "], expected a [" + XContentParser.Token.START_OBJECT + "].");
        }
        InnerHitsContext.BaseInnerHits innerHits = parseInnerHit(parser, parseContext, searchContext, innerHitName);
        if (innerHitsMap == null) {
            innerHitsMap = new HashMap<>();
        }
        innerHitsMap.put(innerHitName, innerHits);
    }
    return innerHitsMap;
}
 
Example #6
Source File: DecayFunctionParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Parses bodies of the kind
 *
 * <pre>
 * <code>
 * {
 *      "fieldname1" : {
 *          "origin" = "someValue",
 *          "scale" = "someValue"
 *      }
 *
 * }
 * </code>
 * </pre>
 *
 * */
@Override
public ScoreFunction parse(QueryParseContext parseContext, XContentParser parser) throws IOException, QueryParsingException {
    String currentFieldName;
    XContentParser.Token token;
    AbstractDistanceScoreFunction scoreFunction;
    String multiValueMode = "MIN";
    XContentBuilder variableContent = XContentFactory.jsonBuilder();
    String fieldName = null;
    while ((token = parser.nextToken()) == XContentParser.Token.FIELD_NAME) {
        currentFieldName = parser.currentName();
        token = parser.nextToken();
        if (token == XContentParser.Token.START_OBJECT) {
            variableContent.copyCurrentStructure(parser);
            fieldName = currentFieldName;
        } else if (parseContext.parseFieldMatcher().match(currentFieldName, MULTI_VALUE_MODE)) {
            multiValueMode = parser.text();
        } else {
            throw new ElasticsearchParseException("malformed score function score parameters.");
        }
    }
    if (fieldName == null) {
        throw new ElasticsearchParseException("malformed score function score parameters.");
    }
    XContentParser variableParser = XContentFactory.xContent(variableContent.string()).createParser(variableContent.string());
    scoreFunction = parseVariable(fieldName, variableParser, parseContext, MultiValueMode.fromString(multiValueMode.toUpperCase(Locale.ROOT)));
    return scoreFunction;
}
 
Example #7
Source File: IdFieldMapper.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public Query termsQuery(List values, @Nullable QueryParseContext context) {
    if (indexOptions() != IndexOptions.NONE || context == null) {
        return super.termsQuery(values, context);
    }
    return new TermsQuery(UidFieldMapper.NAME, Uid.createUidsForTypesAndIds(context.queryTypes(), values));
}
 
Example #8
Source File: TypeFieldMapper.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public Query termQuery(Object value, @Nullable QueryParseContext context) {
    if (indexOptions() == IndexOptions.NONE) {
        return new ConstantScoreQuery(new PrefixQuery(new Term(UidFieldMapper.NAME, Uid.typePrefixAsBytes(BytesRefs.toBytesRef(value)))));
    }
    return new ConstantScoreQuery(new TermQuery(createTerm(value)));
}
 
Example #9
Source File: ScoreFunctionParserMapper.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public ScoreFunctionParser get(QueryParseContext parseContext, String parserName) {
    ScoreFunctionParser functionParser = get(parserName);
    if (functionParser == null) {
        throw new QueryParsingException(parseContext, "No function with the name [" + parserName + "] is registered.", null);
    }
    return functionParser;
}
 
Example #10
Source File: IdFieldMapper.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public Query termQuery(Object value, @Nullable QueryParseContext context) {
    if (indexOptions() != IndexOptions.NONE || context == null) {
        return super.termQuery(value, context);
    }
    final BytesRef[] uids = Uid.createUidsForTypesAndId(context.queryTypes(), value);
    return new TermsQuery(UidFieldMapper.NAME, uids);
}
 
Example #11
Source File: FunctionScoreQueryParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private CombineFunction parseBoostMode(QueryParseContext parseContext, XContentParser parser) throws IOException {
    String boostMode = parser.text();
    CombineFunction cf = combineFunctionsMap.get(boostMode);
    if (cf == null) {
        throw new QueryParsingException(parseContext, "failed to parse [{}] query. illegal boost_mode [{}]", NAME, boostMode);
    }
    return cf;
}
 
Example #12
Source File: XContentStructure.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public InnerQuery(QueryParseContext parseContext1, @Nullable String... types) throws IOException {
    super(parseContext1);
    if (types != null) {
        String[] origTypes = QueryParseContext.setTypesWithPrevious(types);
        try {
            query = parseContext1.parseInnerQuery();
            queryParsed = true;
        } finally {
            QueryParseContext.setTypes(origTypes);
        }
    } else {
        BytesReference innerBytes = XContentFactory.smileBuilder().copyCurrentStructure(parseContext1.parser()).bytes();
        super.bytes(innerBytes);
    }
}
 
Example #13
Source File: DecayFunctionParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private AbstractDistanceScoreFunction parseDateVariable(String fieldName, XContentParser parser, QueryParseContext parseContext,
        DateFieldMapper.DateFieldType dateFieldType, MultiValueMode mode) throws IOException {
    XContentParser.Token token;
    String parameterName = null;
    String scaleString = null;
    String originString = null;
    String offsetString = "0d";
    double decay = 0.5;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            parameterName = parser.currentName();
        } else if (parameterName.equals(DecayFunctionBuilder.SCALE)) {
            scaleString = parser.text();
        } else if (parameterName.equals(DecayFunctionBuilder.ORIGIN)) {
            originString = parser.text();
        } else if (parameterName.equals(DecayFunctionBuilder.DECAY)) {
            decay = parser.doubleValue();
        } else if (parameterName.equals(DecayFunctionBuilder.OFFSET)) {
            offsetString = parser.text();
        } else {
            throw new ElasticsearchParseException("parameter [{}] not supported!", parameterName);
        }
    }
    long origin = SearchContext.current().nowInMillis();
    if (originString != null) {
        origin = dateFieldType.parseToMilliseconds(originString, false, null, null);
    }

    if (scaleString == null) {
        throw new ElasticsearchParseException("[{}] must be set for date fields.", DecayFunctionBuilder.SCALE);
    }
    TimeValue val = TimeValue.parseTimeValue(scaleString, TimeValue.timeValueHours(24), getClass().getSimpleName() + ".scale");
    double scale = val.getMillis();
    val = TimeValue.parseTimeValue(offsetString, TimeValue.timeValueHours(24), getClass().getSimpleName() + ".offset");
    double offset = val.getMillis();
    IndexNumericFieldData numericFieldData = parseContext.getForField(dateFieldType);
    return new NumericFieldDataScoreFunction(origin, scale, decay, offset, getDecayFunction(), numericFieldData, mode);
}
 
Example #14
Source File: DecayFunctionParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private AbstractDistanceScoreFunction parseGeoVariable(String fieldName, XContentParser parser, QueryParseContext parseContext,
        GeoPointFieldMapper.GeoPointFieldType fieldType, MultiValueMode mode) throws IOException {
    XContentParser.Token token;
    String parameterName = null;
    GeoPoint origin = new GeoPoint();
    String scaleString = null;
    String offsetString = "0km";
    double decay = 0.5;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            parameterName = parser.currentName();
        } else if (parameterName.equals(DecayFunctionBuilder.SCALE)) {
            scaleString = parser.text();
        } else if (parameterName.equals(DecayFunctionBuilder.ORIGIN)) {
            origin = GeoUtils.parseGeoPoint(parser);
        } else if (parameterName.equals(DecayFunctionBuilder.DECAY)) {
            decay = parser.doubleValue();
        } else if (parameterName.equals(DecayFunctionBuilder.OFFSET)) {
            offsetString = parser.text();
        } else {
            throw new ElasticsearchParseException("parameter [{}] not supported!", parameterName);
        }
    }
    if (origin == null || scaleString == null) {
        throw new ElasticsearchParseException("[{}] and [{}] must be set for geo fields.", DecayFunctionBuilder.ORIGIN, DecayFunctionBuilder.SCALE);
    }
    double scale = DistanceUnit.DEFAULT.parse(scaleString, DistanceUnit.DEFAULT);
    double offset = DistanceUnit.DEFAULT.parse(offsetString, DistanceUnit.DEFAULT);
    IndexGeoPointFieldData indexFieldData = parseContext.getForField(fieldType);
    return new GeoFieldDataScoreFunction(origin, scale, decay, offset, getDecayFunction(), indexFieldData, mode);

}
 
Example #15
Source File: DecayFunctionParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private AbstractDistanceScoreFunction parseNumberVariable(String fieldName, XContentParser parser, QueryParseContext parseContext,
        NumberFieldMapper.NumberFieldType fieldType, MultiValueMode mode) throws IOException {
    XContentParser.Token token;
    String parameterName = null;
    double scale = 0;
    double origin = 0;
    double decay = 0.5;
    double offset = 0.0d;
    boolean scaleFound = false;
    boolean refFound = false;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            parameterName = parser.currentName();
        } else if (parameterName.equals(DecayFunctionBuilder.SCALE)) {
            scale = parser.doubleValue();
            scaleFound = true;
        } else if (parameterName.equals(DecayFunctionBuilder.DECAY)) {
            decay = parser.doubleValue();
        } else if (parameterName.equals(DecayFunctionBuilder.ORIGIN)) {
            origin = parser.doubleValue();
            refFound = true;
        } else if (parameterName.equals(DecayFunctionBuilder.OFFSET)) {
            offset = parser.doubleValue();
        } else {
            throw new ElasticsearchParseException("parameter [{}] not supported!", parameterName);
        }
    }
    if (!scaleFound || !refFound) {
        throw new ElasticsearchParseException("both [{}] and [{}] must be set for numeric fields.", DecayFunctionBuilder.SCALE, DecayFunctionBuilder.ORIGIN);
    }
    IndexNumericFieldData numericFieldData = parseContext.getForField(fieldType);
    return new NumericFieldDataScoreFunction(origin, scale, decay, offset, getDecayFunction(), numericFieldData, mode);
}
 
Example #16
Source File: IndexFieldMapper.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public Query termsQuery(List values, QueryParseContext context) {
    if (context == null) {
        return super.termsQuery(values, context);
    }
    for (Object value : values) {
        if (isSameIndex(value, context.index().getName())) {
            // No need to OR these clauses - we can only logically be
            // running in the context of just one of these index names.
            return Queries.newMatchAllQuery();
        }
    }
    // None of the listed index names are this one
    return Queries.newMatchNoDocsQuery();
}
 
Example #17
Source File: MappedFieldType.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public Query termsQuery(List values, @Nullable QueryParseContext context) {
    BytesRef[] bytesRefs = new BytesRef[values.size()];
    for (int i = 0; i < bytesRefs.length; i++) {
        bytesRefs[i] = indexedValueForSearch(values.get(i));
    }
    return new TermsQuery(names.indexName(), bytesRefs);
}
 
Example #18
Source File: MappedFieldType.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public Query prefixQuery(String value, @Nullable MultiTermQuery.RewriteMethod method, @Nullable QueryParseContext context) {
    PrefixQuery query = new PrefixQuery(createTerm(value));
    if (method != null) {
        query.setRewriteMethod(method);
    }
    return query;
}
 
Example #19
Source File: InnerHitsParseElement.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private InnerHitsContext.NestedInnerHits parseNested(XContentParser parser, QueryParseContext parseContext, SearchContext searchContext, String nestedPath) throws Exception {
    ObjectMapper objectMapper = searchContext.getObjectMapper(nestedPath);
    if (objectMapper == null) {
        throw new IllegalArgumentException("path [" + nestedPath +"] doesn't exist");
    }
    if (objectMapper.nested().isNested() == false) {
        throw new IllegalArgumentException("path [" + nestedPath +"] isn't nested");
    }
    ObjectMapper parentObjectMapper = parseContext.nestedScope().nextLevel(objectMapper);
    ParseResult parseResult = parseSubSearchContext(searchContext, parseContext, parser);
    parseContext.nestedScope().previousLevel();

    return new InnerHitsContext.NestedInnerHits(parseResult.context(), parseResult.query(), parseResult.childInnerHits(), parentObjectMapper, objectMapper);
}
 
Example #20
Source File: InnerHitsParseElement.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private InnerHitsContext.ParentChildInnerHits parseParentChild(XContentParser parser, QueryParseContext parseContext, SearchContext searchContext, String type) throws Exception {
    ParseResult parseResult = parseSubSearchContext(searchContext, parseContext, parser);
    DocumentMapper documentMapper = searchContext.mapperService().documentMapper(type);
    if (documentMapper == null) {
        throw new IllegalArgumentException("type [" + type + "] doesn't exist");
    }
    return new InnerHitsContext.ParentChildInnerHits(parseResult.context(), parseResult.query(), parseResult.childInnerHits(), parseContext.mapperService(), documentMapper);
}
 
Example #21
Source File: MappedFieldType.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public Query regexpQuery(String value, int flags, int maxDeterminizedStates, @Nullable MultiTermQuery.RewriteMethod method, @Nullable QueryParseContext context) {
    if (numericType() != null) {
        throw new IllegalArgumentException("Cannot use regular expression to filter numeric field [" + names.fullName + "]");
    }

    RegexpQuery query = new RegexpQuery(createTerm(value), flags, maxDeterminizedStates);
    if (method != null) {
        query.setRewriteMethod(method);
    }
    return query;
}
 
Example #22
Source File: PercolatorQueriesRegistry.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private Query parseQuery(String type, XContentParser parser) {
    String[] previousTypes = null;
    if (type != null) {
        QueryParseContext.setTypesWithPrevious(new String[]{type});
    }
    QueryParseContext context = queryParserService.getParseContext();
    try {
        context.reset(parser);
        // This means that fields in the query need to exist in the mapping prior to registering this query
        // The reason that this is required, is that if a field doesn't exist then the query assumes defaults, which may be undesired.
        //
        // Even worse when fields mentioned in percolator queries do go added to map after the queries have been registered
        // then the percolator queries don't work as expected any more.
        //
        // Query parsing can't introduce new fields in mappings (which happens when registering a percolator query),
        // because field type can't be inferred from queries (like document do) so the best option here is to disallow
        // the usage of unmapped fields in percolator queries to avoid unexpected behaviour
        //
        // if index.percolator.map_unmapped_fields_as_string is set to true, query can contain unmapped fields which will be mapped
        // as an analyzed string.
        context.setAllowUnmappedFields(false);
        context.setMapUnmappedFieldAsString(mapUnmappedFieldsAsString ? true : false);
        return queryParserService.parseInnerQuery(context);
    } catch (IOException e) {
        throw new QueryParsingException(context, "Failed to parse", e);
    } finally {
        if (type != null) {
            QueryParseContext.setTypes(previousTypes);
        }
        context.reset(null);
    }
}
 
Example #23
Source File: InnerHitsParseElement.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void parse(XContentParser parser, SearchContext searchContext) throws Exception {
    QueryParseContext context = searchContext.queryParserService().getParseContext();
    context.reset(parser);
    Map<String, InnerHitsContext.BaseInnerHits> topLevelInnerHits = parseInnerHits(parser, context, searchContext);
    if (topLevelInnerHits != null) {
        InnerHitsContext innerHitsContext = searchContext.innerHits();
        innerHitsContext.addInnerHitDefinitions(topLevelInnerHits);
    }
}
 
Example #24
Source File: AliasValidator.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private void validateAliasFilter(XContentParser parser, IndexQueryParserService indexQueryParserService) throws IOException {
    QueryParseContext context = indexQueryParserService.getParseContext();
    try {
        context.reset(parser);
        context.parseInnerFilter();
    } finally {
        context.reset(null);
        parser.close();
    }
}
 
Example #25
Source File: TermsLookup.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public TermsLookup(String index, String type, String id, String routing, String path, @Nullable QueryParseContext queryParseContext) {
    this.index = index;
    this.type = type;
    this.id = id;
    this.routing = routing;
    this.path = path;
    this.queryParseContext = queryParseContext;
}
 
Example #26
Source File: IndexFieldMapper.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * This termQuery impl looks at the context to determine the index that
 * is being queried and then returns a MATCH_ALL_QUERY or MATCH_NO_QUERY
 * if the value matches this index. This can be useful if aliases or
 * wildcards are used but the aim is to restrict the query to specific
 * indices
 */
@Override
public Query termQuery(Object value, @Nullable QueryParseContext context) {
    if (context == null) {
        return super.termQuery(value, context);
    }
    if (isSameIndex(value, context.index().getName())) {
        return Queries.newMatchAllQuery();
    } else {
        return Queries.newMatchNoDocsQuery();
    }
}
 
Example #27
Source File: PhraseCountQueryBuilder.java    From pyramid with Apache License 2.0 4 votes vote down vote up
public static Optional<PhraseCountQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException {
    XContentParser parser = parseContext.parser();
    String fieldName = null;
    Object value = null;
    float boost = AbstractQueryBuilder.DEFAULT_BOOST;
    String analyzer = null;
    int slop = MatchQuery.DEFAULT_PHRASE_SLOP;
    boolean inOrder = false;
    boolean weightedCount = false;
    String queryName = null;
    String currentFieldName = null;
    XContentParser.Token token;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (parseContext.isDeprecatedSetting(currentFieldName)) {
            // skip
        } else if (token == XContentParser.Token.START_OBJECT) {
            throwParsingExceptionOnMultipleFields(NAME, parser.getTokenLocation(), fieldName, currentFieldName);
            fieldName = currentFieldName;
            while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                if (token == XContentParser.Token.FIELD_NAME) {
                    currentFieldName = parser.currentName();
                } else if (token.isValue()) {
                    if (PhraseCountQueryBuilder.QUERY_FIELD.match(currentFieldName)) {
                        value = parser.objectText();
                    } else if (ANALYZER_FIELD.match(currentFieldName)) {
                        analyzer = parser.text();
                    } else if(IN_ORDER_FIELD.match(currentFieldName)) {
                        inOrder = parser.booleanValue();
                    } else if (WEIGHTED_COUNT_FIELD.match(currentFieldName)) {
                        weightedCount = parser.booleanValue();
                    } else if (BOOST_FIELD.match(currentFieldName)) {
                        boost = parser.floatValue();
                    } else if (SLOP_FIELD.match(currentFieldName)) {
                        slop = parser.intValue();
                    } else if (AbstractQueryBuilder.NAME_FIELD.match(currentFieldName)) {
                        queryName = parser.text();
                    } else {
                        throw new ParsingException(parser.getTokenLocation(),
                            "[" + NAME + "] query does not support [" + currentFieldName + "]");
                    }
                } else {
                    throw new ParsingException(parser.getTokenLocation(),
                        "[" + NAME + "] unknown token [" + token + "] after [" + currentFieldName + "]");
                }
            }
        } else {
            throwParsingExceptionOnMultipleFields(NAME, parser.getTokenLocation(), fieldName, parser.currentName());
            fieldName = parser.currentName();
            value = parser.objectText();
        }
    }

    PhraseCountQueryBuilder phraseCountQuery = new PhraseCountQueryBuilder(fieldName, value);
    phraseCountQuery.analyzer(analyzer);
    phraseCountQuery.slop(slop);
    phraseCountQuery.inOrder(inOrder);
    phraseCountQuery.weightedCount(weightedCount);
    phraseCountQuery.queryName(queryName);
    phraseCountQuery.boost(boost);
    return Optional.of(phraseCountQuery);
}
 
Example #28
Source File: TransportTermsByQueryAction.java    From siren-join with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * The operation that executes the query and generates a {@link TermsByQueryShardResponse} for each shard.
 */
@Override
protected TermsByQueryShardResponse shardOperation(TermsByQueryShardRequest shardRequest) throws ElasticsearchException {
  IndexService indexService = indicesService.indexServiceSafe(shardRequest.shardId().getIndex());
  IndexShard indexShard = indexService.shardSafe(shardRequest.shardId().id());
  TermsByQueryRequest request = shardRequest.request();
  OrderByShardOperation orderByOperation = OrderByShardOperation.get(request.getOrderBy(), request.maxTermsPerShard());

  SearchShardTarget shardTarget = new SearchShardTarget(clusterService.localNode().id(),
                                                        shardRequest.shardId().getIndex(),
                                                        shardRequest.shardId().id());

  ShardSearchRequest shardSearchRequest = new ShardSearchLocalRequest(request.types(), request.nowInMillis(),
                                                                      shardRequest.filteringAliases());

  SearchContext context = new DefaultSearchContext(0, shardSearchRequest, shardTarget,
    indexShard.acquireSearcher("termsByQuery"), indexService, indexShard, scriptService,
    pageCacheRecycler, bigArrays, threadPool.estimatedTimeInMillisCounter(), parseFieldMatcher,
    SearchService.NO_TIMEOUT);
  SearchContext.setCurrent(context);

  try {
    MappedFieldType fieldType = context.smartNameFieldType(request.field());
    if (fieldType == null) {
      throw new SearchContextException(context, "[termsByQuery] field '" + request.field() +
              "' not found for types " + Arrays.toString(request.types()));
    }

    IndexFieldData indexFieldData = context.fieldData().getForField(fieldType);

    BytesReference querySource = request.querySource();
    if (querySource != null && querySource.length() > 0) {
      XContentParser queryParser = null;
      try {
        queryParser = XContentFactory.xContent(querySource).createParser(querySource);
        QueryParseContext.setTypes(request.types());
        ParsedQuery parsedQuery = orderByOperation.getParsedQuery(queryParser, indexService);
        if (parsedQuery != null) {
          context.parsedQuery(parsedQuery);
        }
      }
      finally {
        QueryParseContext.removeTypes();
        if (queryParser != null) {
          queryParser.close();
        }
      }
    }

    context.preProcess();

    // execute the search only gathering the hit count and bitset for each segment
    logger.debug("{}: Executes search for collecting terms {}", Thread.currentThread().getName(),
      shardRequest.shardId());

    TermsCollector termsCollector = this.getTermsCollector(request.termsEncoding(), indexFieldData, context);
    if (request.expectedTerms() != null) termsCollector.setExpectedTerms(request.expectedTerms());
    if (request.maxTermsPerShard() != null) termsCollector.setMaxTerms(request.maxTermsPerShard());
    HitStream hitStream = orderByOperation.getHitStream(context);
    TermsSet terms = termsCollector.collect(hitStream);

    logger.debug("{}: Returns terms response with {} terms for shard {}", Thread.currentThread().getName(),
      terms.size(), shardRequest.shardId());

    return new TermsByQueryShardResponse(shardRequest.shardId(), terms);
  }
  catch (Throwable e) {
    logger.error("[termsByQuery] Error executing shard operation", e);
    throw new QueryPhaseExecutionException(context, "[termsByQuery] Failed to execute query", e);
  }
  finally {
    // this will also release the index searcher
    context.close();
    SearchContext.removeCurrent();
  }
}
 
Example #29
Source File: VertexiumQueryStringQueryBuilder.java    From vertexium with Apache License 2.0 4 votes vote down vote up
public static Optional<QueryStringQueryBuilder> fromXContent(QueryParseContext parseContext) {
    throw new RuntimeException("not implemented");
}
 
Example #30
Source File: ParentFieldMapper.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public Query termQuery(Object value, @Nullable QueryParseContext context) {
    return termsQuery(Collections.singletonList(value), context);
}