Java Code Examples for org.elasticsearch.common.xcontent.XContentParser#getTokenLocation()

The following examples show how to use org.elasticsearch.common.xcontent.XContentParser#getTokenLocation() . 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: ValidatingLtrQueryBuilder.java    From elasticsearch-learning-to-rank with Apache License 2.0 6 votes vote down vote up
public static ValidatingLtrQueryBuilder fromXContent(XContentParser parser,
                                                     LtrRankerParserFactory factory) throws IOException {
    try {
        ValidatingLtrQueryBuilder builder = new ValidatingLtrQueryBuilder(factory);
        PARSER.parse(parser, builder, null);
        if (builder.element == null) {
            throw new ParsingException(parser.getTokenLocation(), "Element of type [" + SUPPORTED_TYPES.stream().collect(joining(",")) +
                    "] is mandatory.");
        }
        if (builder.validation == null) {
            throw new ParsingException(parser.getTokenLocation(), "Expected field [" + VALIDATION.getPreferredName() + "]");
        }

        return builder;
    } catch (IllegalArgumentException iae) {
        throw new ParsingException(parser.getTokenLocation(), iae.getMessage(), iae);
    }
}
 
Example 2
Source File: StoredLtrQueryBuilder.java    From elasticsearch-learning-to-rank with Apache License 2.0 6 votes vote down vote up
public static StoredLtrQueryBuilder fromXContent(FeatureStoreLoader storeLoader,
                                                 XContentParser parser) throws IOException {
    storeLoader = Objects.requireNonNull(storeLoader);
    final StoredLtrQueryBuilder builder = new StoredLtrQueryBuilder(storeLoader);
    try {
        PARSER.parse(parser, builder, null);
    } catch (IllegalArgumentException iae) {
        throw new ParsingException(parser.getTokenLocation(), iae.getMessage(), iae);
    }
    if (builder.modelName() == null && builder.featureSetName() == null) {
        throw new ParsingException(parser.getTokenLocation(), "Either [" + MODEL_NAME + "] or [" + FEATURESET_NAME + "] must be set.");
    }
    if (builder.params() == null) {
        throw new ParsingException(parser.getTokenLocation(), "Field [" + PARAMS + "] is mandatory.");
    }
    return builder;
}
 
Example 3
Source File: StoredLtrModel.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
public static LtrModelDefinition parse(XContentParser parser, Void ctx) throws IOException {
    LtrModelDefinition def = PARSER.parse(parser, ctx);
    if (def.type == null) {
        throw new ParsingException(parser.getTokenLocation(), "Field [model.type] is mandatory");
    }
    if (def.definition == null) {
        throw new ParsingException(parser.getTokenLocation(), "Field [model.definition] is mandatory");
    }
    return def;
}
 
Example 4
Source File: TermsParametersParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void parseSpecial(String aggregationName, XContentParser parser, SearchContext context, XContentParser.Token token, String currentFieldName) throws IOException {
    if (token == XContentParser.Token.START_OBJECT) {
        if ("order".equals(currentFieldName)) {
            this.orderElements = Collections.singletonList(parseOrderParam(aggregationName, parser, context));
        } else {
            throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: ["
                    + currentFieldName + "].", parser.getTokenLocation());
        }
    } else if (token == XContentParser.Token.START_ARRAY) {
        if ("order".equals(currentFieldName)) {
            orderElements = new ArrayList<>();
            while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                if (token == XContentParser.Token.START_OBJECT) {
                    OrderElement orderParam = parseOrderParam(aggregationName, parser, context);
                    orderElements.add(orderParam);
                } else {
                    throw new SearchParseException(context, "Order elements must be of type object in [" + aggregationName + "].",
                            parser.getTokenLocation());
                }
            }
        } else {
            throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: ["
                    + currentFieldName + "].", parser.getTokenLocation());
        }
    } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
        if (context.parseFieldMatcher().match(currentFieldName, SHOW_TERM_DOC_COUNT_ERROR)) {
            showTermDocCountError = parser.booleanValue();
        }
    } else {
        throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName
                + "].", parser.getTokenLocation());
    }
}
 
Example 5
Source File: Settings.java    From crate with Apache License 2.0 5 votes vote down vote up
private static Settings fromXContent(XContentParser parser, boolean allowNullValues, boolean validateEndOfStream) throws IOException {
    if (parser.currentToken() == null) {
        parser.nextToken();
    }
    XContentParserUtils.ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser::getTokenLocation);
    Builder innerBuilder = Settings.builder();
    StringBuilder currentKeyBuilder = new StringBuilder();
    fromXContent(parser, currentKeyBuilder, innerBuilder, allowNullValues);
    if (validateEndOfStream) {
        // ensure we reached the end of the stream
        XContentParser.Token lastToken = null;
        try {
            while (!parser.isClosed() && (lastToken = parser.nextToken()) == null) ;
        } catch (Exception e) {
            throw new ElasticsearchParseException(
                "malformed, expected end of settings but encountered additional content starting at line number: [{}], "
                    + "column number: [{}]",
                e, parser.getTokenLocation().lineNumber, parser.getTokenLocation().columnNumber);
        }
        if (lastToken != null) {
            throw new ElasticsearchParseException(
                "malformed, expected end of settings but encountered additional content starting at line number: [{}], "
                    + "column number: [{}]",
                parser.getTokenLocation().lineNumber, parser.getTokenLocation().columnNumber);
        }
    }
    return innerBuilder.build();
}
 
Example 6
Source File: SizeParseElement.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void parse(XContentParser parser, SearchContext context) throws Exception {
    XContentParser.Token token = parser.currentToken();
    if (token.isValue()) {
        int size = parser.intValue();
        if (size < 0) {
            throw new SearchParseException(context, "size is set to [" + size + "] and is expected to be higher or equal to 0",
                    parser.getTokenLocation());
        }
        context.size(size);
    }
}
 
Example 7
Source File: LoggingSearchExtBuilder.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
public static LoggingSearchExtBuilder parse(XContentParser parser) throws IOException {
    try {
        LoggingSearchExtBuilder ext = PARSER.parse(parser, null);
        if (ext.logSpecs == null || ext.logSpecs.isEmpty()) {
            throw new ParsingException(parser.getTokenLocation(), "[" + NAME + "] should define at least one [" +
                LOG_SPECS + "]");
        }
        return ext;
    } catch(IllegalArgumentException iae) {
        throw new ParsingException(parser.getTokenLocation(), iae.getMessage(), iae);
    }
}
 
Example 8
Source File: StoredLtrModel.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
public static StoredLtrModel parse(XContentParser parser, String name) {
    try {
        ParsingState state = PARSER.apply(parser, null);
        state.resolveName(parser, name);
        if (state.featureSet == null) {
            throw new ParsingException(parser.getTokenLocation(), "Field [feature_set] is mandatory");
        }
        if (state.rankingModel == null) {
            throw new ParsingException(parser.getTokenLocation(), "Field [model] is mandatory");
        }
        return new StoredLtrModel(state.getName(), state.featureSet, state.rankingModel);
    } catch (IllegalArgumentException iae) {
        throw new ParsingException(parser.getTokenLocation(), iae.getMessage(), iae);
    }
}
 
Example 9
Source File: StorableElement.java    From elasticsearch-learning-to-rank with Apache License 2.0 5 votes vote down vote up
void resolveName(XContentParser parser, String name) {
    if (this.name == null && name != null) {
        this.name = name;
    } else if ( this.name == null /* && name == null */) {
        throw new ParsingException(parser.getTokenLocation(), "Field [name] is mandatory");
    } else if ( /* this.name != null && */ name != null && !this.name.equals(name)) {
        throw new ParsingException(parser.getTokenLocation(), "Invalid [name], expected ["+name+"] but got [" + this.name+"]");
    }
}
 
Example 10
Source File: ExtendedStatsParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException {

    ValuesSourceParser<ValuesSource.Numeric> vsParser = ValuesSourceParser.numeric(aggregationName, InternalExtendedStats.TYPE, context).formattable(true)
            .build();

    XContentParser.Token token;
    String currentFieldName = null;
    double sigma = 2.0;

    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (vsParser.token(currentFieldName, token, parser)) {
            continue;
        } else if (token == XContentParser.Token.VALUE_NUMBER) {
            if (context.parseFieldMatcher().match(currentFieldName, SIGMA)) {
                sigma = parser.doubleValue();
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else {
            throw new SearchParseException(context, "Unexpected token " + token + " in [" + aggregationName + "].",
                    parser.getTokenLocation());
        }
    }

    if (sigma < 0) {
        throw new SearchParseException(context, "[sigma] must not be negative. Value provided was" + sigma, parser.getTokenLocation());
    }

    return createFactory(aggregationName, vsParser.config(), sigma);
}
 
Example 11
Source File: CardinalityParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public AggregatorFactory parse(String name, XContentParser parser, SearchContext context) throws IOException {

    ValuesSourceParser<?> vsParser = ValuesSourceParser.any(name, InternalCardinality.TYPE, context).formattable(false).build();

    long precisionThreshold = -1;

    XContentParser.Token token;
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (vsParser.token(currentFieldName, token, parser)) {
            continue;
        } else if (token.isValue()) {
            if (context.parseFieldMatcher().match(currentFieldName, REHASH)) {
                // ignore
            } else if (context.parseFieldMatcher().match(currentFieldName, PRECISION_THRESHOLD)) {
                precisionThreshold = parser.longValue();
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + name + "]: [" + currentFieldName
                        + "].", parser.getTokenLocation());
            }
        } else {
            throw new SearchParseException(context, "Unexpected token " + token + " in [" + name + "].", parser.getTokenLocation());
        }
    }

    return new CardinalityAggregatorFactory(name, vsParser.config(), precisionThreshold);

}
 
Example 12
Source File: ExactPhraseQueryBuilder.java    From elasticsearch-plugin-bundle with GNU Affero General Public License v3.0 5 votes vote down vote up
public static ExactPhraseQueryBuilder fromXContent(XContentParser parser) throws IOException {
    float boost = AbstractQueryBuilder.DEFAULT_BOOST;
    String queryName = null;
    QueryBuilder query = 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 (token == XContentParser.Token.START_OBJECT) {
            if (currentFieldName != null) {
                if (QUERY_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
                    query = parseInnerQueryBuilder(parser);
                } else {
                    throw new ParsingException(parser.getTokenLocation(), "[nested] query does not support [" + currentFieldName + "]");
                }
            }
        } else if (token.isValue()) {
            if (currentFieldName != null) {
                if (AbstractQueryBuilder.BOOST_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
                    boost = parser.floatValue();
                } else if (AbstractQueryBuilder.NAME_FIELD.match(currentFieldName, parser.getDeprecationHandler())) {
                    queryName = parser.text();
                } else {
                    throw new ParsingException(parser.getTokenLocation(), "[nested] query does not support [" + currentFieldName + "]");
                }
            }
        }
    }
    return new ExactPhraseQueryBuilder(query).queryName(queryName).boost(boost);
}
 
Example 13
Source File: GeoBoundsParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException {
    ValuesSourceParser<GeoPoint> vsParser = ValuesSourceParser.geoPoint(aggregationName, InternalGeoBounds.TYPE, context)
            .targetValueType(ValueType.GEOPOINT)
            .formattable(true)
            .build();
    boolean wrapLongitude = true;
    XContentParser.Token token;
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (vsParser.token(currentFieldName, token, parser)) {
            continue;
            
        } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
            if ("wrap_longitude".equals(currentFieldName) || "wrapLongitude".equals(currentFieldName)) {
                wrapLongitude = parser.booleanValue();
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in aggregation [" + aggregationName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else {
            throw new SearchParseException(context, "Unknown key for a " + token + " in aggregation [" + aggregationName + "]: ["
                    + currentFieldName + "].", parser.getTokenLocation());
        }
    }
    return new GeoBoundsAggregator.Factory(aggregationName, vsParser.config(), wrapLongitude);
}
 
Example 14
Source File: RestCreateModelFromSet.java    From elasticsearch-learning-to-rank with Apache License 2.0 4 votes vote down vote up
public static void parse(XContentParser parser, Model value) throws IOException {
    MODEL_PARSER.parse(parser, value, null);
    if (value.name == null) {
        throw new ParsingException(parser.getTokenLocation(), "Missing required value [name]");
    }
}
 
Example 15
Source File: SerialDiffParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public PipelineAggregatorFactory parse(String reducerName, XContentParser parser, SearchContext context) throws IOException {
    XContentParser.Token token;
    String currentFieldName = null;
    String[] bucketsPaths = null;
    String format = null;
    GapPolicy gapPolicy = GapPolicy.SKIP;
    int lag = 1;

    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token == XContentParser.Token.VALUE_STRING) {
            if (context.parseFieldMatcher().match(currentFieldName, FORMAT)) {
                format = parser.text();
            } else if (context.parseFieldMatcher().match(currentFieldName, BUCKETS_PATH)) {
                bucketsPaths = new String[] { parser.text() };
            } else if (context.parseFieldMatcher().match(currentFieldName, GAP_POLICY)) {
                gapPolicy = GapPolicy.parse(context, parser.text(), parser.getTokenLocation());
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + reducerName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else if (token == XContentParser.Token.VALUE_NUMBER) {
            if (context.parseFieldMatcher().match(currentFieldName, LAG)) {
                lag = parser.intValue(true);
                if (lag <= 0) {
                    throw new SearchParseException(context, "Lag must be a positive, non-zero integer.  Value supplied was" +
                            lag + " in [" + reducerName + "]: ["
                            + currentFieldName + "].", parser.getTokenLocation());
                }
            }  else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + reducerName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else if (token == XContentParser.Token.START_ARRAY) {
            if (context.parseFieldMatcher().match(currentFieldName, BUCKETS_PATH)) {
                List<String> paths = new ArrayList<>();
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                    String path = parser.text();
                    paths.add(path);
                }
                bucketsPaths = paths.toArray(new String[paths.size()]);
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + reducerName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else {
            throw new SearchParseException(context, "Unexpected token " + token + " in [" + reducerName + "].",
                    parser.getTokenLocation());
        }
    }

    if (bucketsPaths == null) {
        throw new SearchParseException(context, "Missing required field [" + BUCKETS_PATH.getPreferredName()
                + "] for derivative aggregation [" + reducerName + "]", parser.getTokenLocation());
    }

    ValueFormatter formatter;
    if (format != null) {
        formatter = ValueFormat.Patternable.Number.format(format).formatter();
    }  else {
        formatter = ValueFormatter.RAW;
    }

    return new SerialDiffPipelineAggregator.Factory(reducerName, bucketsPaths, formatter, gapPolicy, lag);
}
 
Example 16
Source File: BucketMetricsParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public final PipelineAggregatorFactory parse(String pipelineAggregatorName, XContentParser parser, SearchContext context) throws IOException {
    XContentParser.Token token;
    String currentFieldName = null;
    String[] bucketsPaths = null;
    String format = null;
    GapPolicy gapPolicy = GapPolicy.SKIP;
    Map<String, Object> leftover = new HashMap<>(5);

    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token == XContentParser.Token.VALUE_STRING) {
            if (context.parseFieldMatcher().match(currentFieldName, FORMAT)) {
                format = parser.text();
            } else if (context.parseFieldMatcher().match(currentFieldName, BUCKETS_PATH)) {
                bucketsPaths = new String[] { parser.text() };
            } else if (context.parseFieldMatcher().match(currentFieldName, GAP_POLICY)) {
                gapPolicy = GapPolicy.parse(context, parser.text(), parser.getTokenLocation());
            } else {
                leftover.put(currentFieldName, parser.text());
            }
        } else if (token == XContentParser.Token.START_ARRAY) {
            if (context.parseFieldMatcher().match(currentFieldName, BUCKETS_PATH)) {
                List<String> paths = new ArrayList<>();
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                    String path = parser.text();
                    paths.add(path);
                }
                bucketsPaths = paths.toArray(new String[paths.size()]);
            } else {
                leftover.put(currentFieldName, parser.list());
            }
        } else {
            leftover.put(currentFieldName, parser.objectText());
        }
    }

    if (bucketsPaths == null) {
        throw new SearchParseException(context, "Missing required field [" + BUCKETS_PATH.getPreferredName()
                + "] for aggregation [" + pipelineAggregatorName + "]", parser.getTokenLocation());
    }

    ValueFormatter formatter = null;
    if (format != null) {
        formatter = ValueFormat.Patternable.Number.format(format).formatter();
    } else {
        formatter = ValueFormatter.RAW;
    }

    PipelineAggregatorFactory factory = null;
    try {
        factory = buildFactory(pipelineAggregatorName, bucketsPaths, gapPolicy, formatter, leftover);
    } catch (ParseException exception) {
        throw new SearchParseException(context, "Could not parse settings for aggregation ["
                + pipelineAggregatorName + "].", null, exception);
    }

    if (leftover.size() > 0) {
        throw new SearchParseException(context, "Unexpected tokens " + leftover.keySet() + " in [" + pipelineAggregatorName + "].", null);
    }
    assert(factory != null);

    return factory;
}
 
Example 17
Source File: SearchService.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
private void parseSource(SearchContext context, BytesReference source) throws SearchParseException {
    // nothing to parse...
    if (source == null || source.length() == 0) {
        return;
    }
    String abc = source.toUtf8();
    XContentParser parser = null;
    try {
        parser = XContentFactory.xContent(source).createParser(source);
        XContentParser.Token token;
        token = parser.nextToken();
        if (token != XContentParser.Token.START_OBJECT) {
            throw new ElasticsearchParseException("failed to parse search source. source must be an object, but found [{}] instead", token.name());
        }
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                String fieldName = parser.currentName();
                parser.nextToken();
                SearchParseElement element = elementParsers.get(fieldName);
                if (element == null) {
                    throw new SearchParseException(context, "failed to parse search source. unknown search element [" + fieldName + "]", parser.getTokenLocation());
                }
                element.parse(parser, context);
            } else {
                if (token == null) {
                    throw new ElasticsearchParseException("failed to parse search source. end of query source reached but query is not complete.");
                } else {
                    throw new ElasticsearchParseException("failed to parse search source. expected field name but got [{}]", token);
                }
            }
        }
    } catch (Throwable e) {
        String sSource = "_na_";
        try {
            sSource = XContentHelper.convertToJson(source, false);
        } catch (Throwable e1) {
            // ignore
        }
        XContentLocation location = parser != null ? parser.getTokenLocation() : null;
        throw new SearchParseException(context, "failed to parse search source [" + sSource + "]", location, e);
    } finally {
        if (parser != null) {
            parser.close();
        }
    }
}
 
Example 18
Source File: IpRangeParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException {

    ValuesSourceParser<ValuesSource.Numeric> vsParser = ValuesSourceParser.numeric(aggregationName, InternalIPv4Range.TYPE, context)
            .targetValueType(ValueType.IP)
            .formattable(false)
            .build();

    List<RangeAggregator.Range> ranges = null;
    boolean keyed = false;

    XContentParser.Token token;
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (vsParser.token(currentFieldName, token, parser)) {
            continue;
        } else if (token == XContentParser.Token.START_ARRAY) {
            if ("ranges".equals(currentFieldName)) {
                ranges = new ArrayList<>();
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                    double from = Double.NEGATIVE_INFINITY;
                    String fromAsStr = null;
                    double to = Double.POSITIVE_INFINITY;
                    String toAsStr = null;
                    String key = null;
                    String mask = null;
                    String toOrFromOrMaskOrKey = null;
                    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                        if (token == XContentParser.Token.FIELD_NAME) {
                            toOrFromOrMaskOrKey = parser.currentName();
                        } else if (token == XContentParser.Token.VALUE_NUMBER) {
                            if ("from".equals(toOrFromOrMaskOrKey)) {
                                from = parser.doubleValue();
                            } else if ("to".equals(toOrFromOrMaskOrKey)) {
                                to = parser.doubleValue();
                            }
                        } else if (token == XContentParser.Token.VALUE_STRING) {
                            if ("from".equals(toOrFromOrMaskOrKey)) {
                                fromAsStr = parser.text();
                            } else if ("to".equals(toOrFromOrMaskOrKey)) {
                                toAsStr = parser.text();
                            } else if ("key".equals(toOrFromOrMaskOrKey)) {
                                key = parser.text();
                            } else if ("mask".equals(toOrFromOrMaskOrKey)) {
                                mask = parser.text();
                            }
                        }
                    }
                    RangeAggregator.Range range = new RangeAggregator.Range(key, from, fromAsStr, to, toAsStr);
                    if (mask != null) {
                        parseMaskRange(mask, range, aggregationName, context);
                    }
                    ranges.add(range);
                }
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
            if ("keyed".equals(currentFieldName)) {
                keyed = parser.booleanValue();
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else {
            throw new SearchParseException(context, "Unexpected token " + token + " in [" + aggregationName + "].",
                    parser.getTokenLocation());
        }
    }

    if (ranges == null) {
        throw new SearchParseException(context, "Missing [ranges] in ranges aggregator [" + aggregationName + "]",
                parser.getTokenLocation());
    }

    return new RangeAggregator.Factory(aggregationName, vsParser.config(), InternalIPv4Range.FACTORY, ranges, keyed);
}
 
Example 19
Source File: RangeParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException {

    List<RangeAggregator.Range> ranges = null;
    boolean keyed = false;

    ValuesSourceParser<ValuesSource.Numeric> vsParser = ValuesSourceParser.numeric(aggregationName, InternalRange.TYPE, context)
            .formattable(true)
            .build();

    XContentParser.Token token;
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (vsParser.token(currentFieldName, token, parser)) {
            continue;
        } else if (token == XContentParser.Token.START_ARRAY) {
            if ("ranges".equals(currentFieldName)) {
                ranges = new ArrayList<>();
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                    double from = Double.NEGATIVE_INFINITY;
                    String fromAsStr = null;
                    double to = Double.POSITIVE_INFINITY;
                    String toAsStr = null;
                    String key = null;
                    String toOrFromOrKey = null;
                    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                        if (token == XContentParser.Token.FIELD_NAME) {
                            toOrFromOrKey = parser.currentName();
                        } else if (token == XContentParser.Token.VALUE_NUMBER) {
                            if ("from".equals(toOrFromOrKey)) {
                                from = parser.doubleValue();
                            } else if ("to".equals(toOrFromOrKey)) {
                                to = parser.doubleValue();
                            }
                        } else if (token == XContentParser.Token.VALUE_STRING) {
                            if ("from".equals(toOrFromOrKey)) {
                                fromAsStr = parser.text();
                            } else if ("to".equals(toOrFromOrKey)) {
                                toAsStr = parser.text();
                            } else if ("key".equals(toOrFromOrKey)) {
                                key = parser.text();
                            }
                        }
                    }
                    ranges.add(new RangeAggregator.Range(key, from, fromAsStr, to, toAsStr));
                }
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
            if ("keyed".equals(currentFieldName)) {
                keyed = parser.booleanValue();
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else {
            throw new SearchParseException(context, "Unexpected token " + token + " in [" + aggregationName + "].",
                    parser.getTokenLocation());
        }
    }

    if (ranges == null) {
        throw new SearchParseException(context, "Missing [ranges] in ranges aggregator [" + aggregationName + "]",
                parser.getTokenLocation());
    }

    return new RangeAggregator.Factory(aggregationName, vsParser.config(), InternalRange.FACTORY, ranges, keyed);
}
 
Example 20
Source File: ChildrenParser.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public AggregatorFactory parse(String aggregationName, XContentParser parser, SearchContext context) throws IOException {
    String childType = null;

    XContentParser.Token token;
    String currentFieldName = null;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token == XContentParser.Token.VALUE_STRING) {
            if ("type".equals(currentFieldName)) {
                childType = parser.text();
            } else {
                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: ["
                        + currentFieldName + "].", parser.getTokenLocation());
            }
        } else {
            throw new SearchParseException(context, "Unexpected token " + token + " in [" + aggregationName + "].",
                    parser.getTokenLocation());
        }
    }

    if (childType == null) {
        throw new SearchParseException(context, "Missing [child_type] field for children aggregation [" + aggregationName + "]",
                parser.getTokenLocation());
    }

    ValuesSourceConfig<ValuesSource.Bytes.WithOrdinals.ParentChild> config = new ValuesSourceConfig<>(ValuesSource.Bytes.WithOrdinals.ParentChild.class);
    DocumentMapper childDocMapper = context.mapperService().documentMapper(childType);

    String parentType = null;
    Query parentFilter = null;
    Query childFilter = null;
    if (childDocMapper != null) {
        ParentFieldMapper parentFieldMapper = childDocMapper.parentFieldMapper();
        if (!parentFieldMapper.active()) {
            throw new SearchParseException(context, "[children] no [_parent] field not configured that points to a parent type", parser.getTokenLocation());
        }
        parentType = parentFieldMapper.type();
        DocumentMapper parentDocMapper = context.mapperService().documentMapper(parentType);
        if (parentDocMapper != null) {
            // TODO: use the query API
            parentFilter = parentDocMapper.typeFilter();
            childFilter = childDocMapper.typeFilter();
            ParentChildIndexFieldData parentChildIndexFieldData = context.fieldData().getForField(parentFieldMapper.fieldType());
            config.fieldContext(new FieldContext(parentFieldMapper.fieldType().names().indexName(), parentChildIndexFieldData, parentFieldMapper.fieldType()));
        } else {
            config.unmapped(true);
        }
    } else {
        config.unmapped(true);
    }
    return new ParentToChildrenAggregator.Factory(aggregationName, config, parentType, parentFilter, childFilter);
}