org.elasticsearch.index.query.QueryParsingException Java Examples

The following examples show how to use org.elasticsearch.index.query.QueryParsingException. 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: GND.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher, SearchContext context)
        throws IOException, QueryParsingException {
    String givenName = parser.currentName();
    boolean backgroundIsSuperset = true;
    XContentParser.Token token = parser.nextToken();
    while (!token.equals(XContentParser.Token.END_OBJECT)) {
        if (parseFieldMatcher.match(parser.currentName(), BACKGROUND_IS_SUPERSET)) {
            parser.nextToken();
            backgroundIsSuperset = parser.booleanValue();
        } else {
            throw new ElasticsearchParseException("failed to parse [{}] significance heuristic. unknown field [{}]", givenName, parser.currentName());
        }
        token = parser.nextToken();
    }
    return newHeuristic(true, backgroundIsSuperset);
}
 
Example #2
Source File: NestedInnerQueryParseSupport.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
public Query getInnerFilter() throws IOException {
    if (filterParsed) {
        return innerFilter;
    } else {
        if (path == null) {
            throw new QueryParsingException(parseContext, "[nested] requires 'path' field");
        }
        if (!filterFound) {
            throw new QueryParsingException(parseContext, "[nested] requires either 'query' or 'filter' field");
        }

        setPathLevel();
        XContentParser old = parseContext.parser();
        try {
            XContentParser innerParser = XContentHelper.createParser(source);
            parseContext.parser(innerParser);
            innerFilter = parseContext.parseInnerFilter();
            filterParsed = true;
            return innerFilter;
        } finally {
            resetPathLevel();
            parseContext.parser(old);
        }
    }
}
 
Example #3
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 #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: 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 #6
Source File: NXYSignificanceHeuristic.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher, SearchContext context)
        throws IOException, QueryParsingException {
    String givenName = parser.currentName();
    boolean includeNegatives = false;
    boolean backgroundIsSuperset = true;
    XContentParser.Token token = parser.nextToken();
    while (!token.equals(XContentParser.Token.END_OBJECT)) {
        if (parseFieldMatcher.match(parser.currentName(), INCLUDE_NEGATIVES_FIELD)) {
            parser.nextToken();
            includeNegatives = parser.booleanValue();
        } else if (parseFieldMatcher.match(parser.currentName(), BACKGROUND_IS_SUPERSET)) {
            parser.nextToken();
            backgroundIsSuperset = parser.booleanValue();
        } else {
            throw new ElasticsearchParseException("failed to parse [{}] significance heuristic. unknown field [{}]", givenName, parser.currentName());
        }
        token = parser.nextToken();
    }
    return newHeuristic(includeNegatives, backgroundIsSuperset);
}
 
Example #7
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 #8
Source File: TranslogRecoveryPerformer.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private static Engine.DeleteByQuery prepareDeleteByQuery(IndexQueryParserService queryParserService, MapperService mapperService, IndexAliasesService indexAliasesService, IndexCache indexCache, BytesReference source, @Nullable String[] filteringAliases, Engine.Operation.Origin origin, String... types) {
    long startTime = System.nanoTime();
    if (types == null) {
        types = Strings.EMPTY_ARRAY;
    }
    Query query;
    try {
        query = queryParserService.parseQuery(source).query();
    } catch (QueryParsingException ex) {
        // for BWC we try to parse directly the query since pre 1.0.0.Beta2 we didn't require a top level query field
        if (queryParserService.getIndexCreatedVersion().onOrBefore(Version.V_1_0_0_Beta2)) {
            try {
                XContentParser parser = XContentHelper.createParser(source);
                ParsedQuery parse = queryParserService.parse(parser);
                query = parse.query();
            } catch (Throwable t) {
                ex.addSuppressed(t);
                throw ex;
            }
        } else {
            throw ex;
        }
    }
    Query searchFilter = mapperService.searchFilter(types);
    if (searchFilter != null) {
        query = Queries.filtered(query, searchFilter);
    }

    Query aliasFilter = indexAliasesService.aliasFilter(filteringAliases);
    BitSetProducer parentFilter = mapperService.hasNested() ? indexCache.bitsetFilterCache().getBitSetProducer(Queries.newNonNestedFilter()) : null;
    return new Engine.DeleteByQuery(query, source, filteringAliases, aliasFilter, parentFilter, origin, startTime, types);
}
 
Example #9
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 #10
Source File: NestedInnerQueryParseSupport.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public void setPath(String path) {
    this.path = path;
    nestedObjectMapper = parseContext.getObjectMapper(path);
    if (nestedObjectMapper == null) {
        throw new QueryParsingException(parseContext, "[nested] failed to find nested object under path [" + path + "]");
    }
    if (!nestedObjectMapper.nested().isNested()) {
        throw new QueryParsingException(parseContext, "[nested] nested object under path [" + path + "] is not of nested type");
    }
}
 
Example #11
Source File: NestedInnerQueryParseSupport.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public Query getInnerQuery() throws IOException {
    if (queryParsed) {
        return innerQuery;
    } else {
        if (path == null) {
            throw new QueryParsingException(parseContext, "[nested] requires 'path' field");
        }
        if (!queryFound) {
            throw new QueryParsingException(parseContext, "[nested] requires either 'query' or 'filter' field");
        }

        XContentParser old = parseContext.parser();
        try {
            XContentParser innerParser = XContentHelper.createParser(source);
            parseContext.parser(innerParser);
            setPathLevel();
            try {
                innerQuery = parseContext.parseInnerQuery();
            } finally {
                resetPathLevel();
            }
            queryParsed = true;
            return innerQuery;
        } finally {
            parseContext.parser(old);
        }
    }
}
 
Example #12
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 #13
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 #14
Source File: PercentageScore.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher, SearchContext context)
        throws IOException, QueryParsingException {
    // move to the closing bracket
    if (!parser.nextToken().equals(XContentParser.Token.END_OBJECT)) {
        throw new ElasticsearchParseException("failed to parse [percentage] significance heuristic. expected an empty object, but got [{}] instead", parser.currentToken());
    }
    return new PercentageScore();
}
 
Example #15
Source File: JLHScore.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher, SearchContext context)
        throws IOException, QueryParsingException {
    // move to the closing bracket
    if (!parser.nextToken().equals(XContentParser.Token.END_OBJECT)) {
        throw new ElasticsearchParseException("failed to parse [jhl] significance heuristic. expected an empty object, but found [{}] instead", parser.currentToken());
    }
    return new JLHScore();
}
 
Example #16
Source File: FactorParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public ScoreFunction parse(QueryParseContext parseContext, XContentParser parser) throws IOException, QueryParsingException {
    float boostFactor = parser.floatValue();
    return new BoostScoreFunction(boostFactor);
}
 
Example #17
Source File: RandomScoreFunctionParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public ScoreFunction parse(QueryParseContext parseContext, XContentParser parser) throws IOException, QueryParsingException {

    int seed = -1;

    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 (token.isValue()) {
            if ("seed".equals(currentFieldName)) {
                if (token == XContentParser.Token.VALUE_NUMBER) {
                    if (parser.numberType() == XContentParser.NumberType.INT) {
                        seed = parser.intValue();
                    } else if (parser.numberType() == XContentParser.NumberType.LONG) {
                        seed = Longs.hashCode(parser.longValue());
                    } else {
                        throw new QueryParsingException(parseContext, "random_score seed must be an int, long or string, not '"
                                + token.toString() + "'");
                    }
                } else if (token == XContentParser.Token.VALUE_STRING) {
                    seed = parser.text().hashCode();
                } else {
                    throw new QueryParsingException(parseContext, "random_score seed must be an int/long or string, not '"
                            + token.toString() + "'");
                }
            } else {
                throw new QueryParsingException(parseContext, NAMES[0] + " query does not support [" + currentFieldName + "]");
            }
        }
    }

    final MappedFieldType fieldType = SearchContext.current().mapperService().smartNameFieldType("_uid");
    if (fieldType == null) {
        // mapper could be null if we are on a shard with no docs yet, so this won't actually be used
        return new RandomScoreFunction();
    }

    if (seed == -1) {
        seed = Longs.hashCode(parseContext.nowInMillis());
    }
    final ShardId shardId = SearchContext.current().indexShard().shardId();
    final int salt = (shardId.index().name().hashCode() << 10) | shardId.id();
    final IndexFieldData<?> uidFieldData = SearchContext.current().fieldData().getForField(fieldType);

    return new RandomScoreFunction(seed, salt, uidFieldData);
}
 
Example #18
Source File: FieldValueFactorFunctionParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public ScoreFunction parse(QueryParseContext parseContext, XContentParser parser) throws IOException, QueryParsingException {

    String currentFieldName = null;
    String field = null;
    float boostFactor = 1;
    FieldValueFactorFunction.Modifier modifier = FieldValueFactorFunction.Modifier.NONE;
    Double missing = null;
    XContentParser.Token token;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token.isValue()) {
            if ("field".equals(currentFieldName)) {
                field = parser.text();
            } else if ("factor".equals(currentFieldName)) {
                boostFactor = parser.floatValue();
            } else if ("modifier".equals(currentFieldName)) {
                modifier = FieldValueFactorFunction.Modifier.valueOf(parser.text().toUpperCase(Locale.ROOT));
            } else if ("missing".equals(currentFieldName)) {
                missing = parser.doubleValue();
            } else {
                throw new QueryParsingException(parseContext, NAMES[0] + " query does not support [" + currentFieldName + "]");
            }
        } else if("factor".equals(currentFieldName) && (token == XContentParser.Token.START_ARRAY || token == XContentParser.Token.START_OBJECT)) {
            throw new QueryParsingException(parseContext, "[" + NAMES[0] + "] field 'factor' does not support lists or objects");
        }
    }

    if (field == null) {
        throw new QueryParsingException(parseContext, "[" + NAMES[0] + "] required field 'field' missing");
    }

    SearchContext searchContext = SearchContext.current();
    MappedFieldType fieldType = searchContext.mapperService().smartNameFieldType(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 = searchContext.fieldData().getForField(fieldType);
    }
    return new FieldValueFactorFunction(field, boostFactor, modifier, missing, fieldData);
}
 
Example #19
Source File: FunctionScoreQueryParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
private String parseFiltersAndFunctions(QueryParseContext parseContext, XContentParser parser,
                                        ArrayList<FiltersFunctionScoreQuery.FilterFunction> filterFunctions, String currentFieldName) throws IOException {
    XContentParser.Token token;
    while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
        Query filter = null;
        ScoreFunction scoreFunction = null;
        Float functionWeight = null;
        if (token != XContentParser.Token.START_OBJECT) {
            throw new QueryParsingException(parseContext, "failed to parse [{}]. malformed query, expected a [{}] while parsing functions but got a [{}] instead", XContentParser.Token.START_OBJECT, token, NAME);
        } else {
            while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                if (token == XContentParser.Token.FIELD_NAME) {
                    currentFieldName = parser.currentName();
                } else if (parseContext.parseFieldMatcher().match(currentFieldName, WEIGHT_FIELD)) {
                    functionWeight = parser.floatValue();
                } else {
                    if ("filter".equals(currentFieldName)) {
                        filter = parseContext.parseInnerFilter();
                    } else {
                        // do not need to check null here,
                        // functionParserMapper throws exception if parser
                        // non-existent
                        ScoreFunctionParser functionParser = functionParserMapper.get(parseContext, currentFieldName);
                        scoreFunction = functionParser.parse(parseContext, parser);
                    }
                }
            }
            if (functionWeight != null) {
                scoreFunction = new WeightFactorFunction(functionWeight, scoreFunction);
            }
        }
        if (filter == null) {
            filter = Queries.newMatchAllQuery();
        }
        if (scoreFunction == null) {
            throw new ElasticsearchParseException("failed to parse [{}] query. an entry in functions list is missing a function.", NAME);
        }
        filterFunctions.add(new FiltersFunctionScoreQuery.FilterFunction(filter, scoreFunction));

    }
    return currentFieldName;
}
 
Example #20
Source File: SignificanceHeuristicParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher, SearchContext context) throws IOException,
QueryParsingException;
 
Example #21
Source File: FieldDataTermsQueryParser.java    From siren-join with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
  XContentParser parser = parseContext.parser();

  XContentParser.Token token = parser.nextToken();
  if (token != XContentParser.Token.FIELD_NAME) {
      throw new QueryParsingException(parseContext, "[fielddata_terms] a field name is required");
  }
  String fieldName = parser.currentName();

  String queryName = null;
  byte[] value = null;
  Long cacheKey = null;

  token = parser.nextToken();
  if (token == XContentParser.Token.START_OBJECT) {
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
      if (token == XContentParser.Token.FIELD_NAME) {
        currentFieldName = parser.currentName();
      } else {
        if ("value".equals(currentFieldName)) {
          value = parser.binaryValue();
        } else if ("_name".equals(currentFieldName)) {
          queryName = parser.text();
        } else if ("_cache_key".equals(currentFieldName) || "_cacheKey".equals(currentFieldName)) {
          cacheKey = parser.longValue();
        } else {
          throw new QueryParsingException(parseContext, "[fielddata_terms] filter does not support [" + currentFieldName + "]");
        }
      }
    }
    parser.nextToken();
  } else {
    value = parser.binaryValue();
    // move to the next token
    parser.nextToken();
  }

  if (value == null) {
    throw new QueryParsingException(parseContext, "[fielddata_terms] a binary value is required");
  }
  if (cacheKey == null) { // cache key is mandatory - see #170
    throw new QueryParsingException(parseContext, "[fielddata_terms] a cache key is required");
  }

  if (fieldName == null) {
    throw new QueryParsingException(parseContext, "[fielddata_terms] a field name is required");
  }

  MappedFieldType fieldType = parseContext.fieldMapper(fieldName);
  if (fieldType == null) {
    return new MatchNoDocsQuery();
  }

  IndexFieldData fieldData = parseContext.getForField(fieldType);
  Query query = this.toFieldDataTermsQuery(fieldType, fieldData, value, cacheKey);

  if (queryName != null) {
    parseContext.addNamedQuery(queryName, query);
  }

  return query;
}
 
Example #22
Source File: TermsEnumTermsQueryParser.java    From siren-join with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
  XContentParser parser = parseContext.parser();

  XContentParser.Token token = parser.nextToken();
  if (token != XContentParser.Token.FIELD_NAME) {
      throw new QueryParsingException(parseContext, "[termsenum_terms] a field name is required");
  }
  String fieldName = parser.currentName();

  String queryName = null;
  byte[] value = null;
  Long cacheKey = null;

  token = parser.nextToken();
  if (token == XContentParser.Token.START_OBJECT) {
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
      if (token == XContentParser.Token.FIELD_NAME) {
        currentFieldName = parser.currentName();
      } else {
        if ("value".equals(currentFieldName)) {
            value = parser.binaryValue();
        } else if ("_name".equals(currentFieldName)) {
            queryName = parser.text();
        } else if ("_cache_key".equals(currentFieldName) || "_cacheKey".equals(currentFieldName)) {
            cacheKey = parser.longValue();
        } else {
          throw new QueryParsingException(parseContext, "[termsenum_terms] filter does not support [" + currentFieldName + "]");
        }
      }
    }
    parser.nextToken();
  } else {
    value = parser.binaryValue();
    // move to the next token
    parser.nextToken();
  }

  if (value == null) {
    throw new QueryParsingException(parseContext, "[termsenum_terms] a binary value is required");
  }
  if (cacheKey == null) { // cache key is mandatory - see #170
    throw new QueryParsingException(parseContext, "[termsenum_terms] a cache key is required");
  }

  if (fieldName == null) {
    throw new QueryParsingException(parseContext, "[termsenum_terms] a field name is required");
  }

  MappedFieldType fieldType = parseContext.fieldMapper(fieldName);
  if (fieldType == null) {
    return new MatchNoDocsQuery();
  }

  Query query = new TermsEnumTermsQuery(value, fieldName, cacheKey);

  if (queryName != null) {
    parseContext.addNamedQuery(queryName, query);
  }

  return query;
}
 
Example #23
Source File: ScoreFunctionParser.java    From Elasticsearch with Apache License 2.0 votes vote down vote up
ScoreFunction parse(QueryParseContext parseContext, XContentParser parser) throws IOException, QueryParsingException;