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

The following examples show how to use org.elasticsearch.common.xcontent.XContentParser#doubleValue() . 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: GeoJsonParser.java    From crate with Apache License 2.0 6 votes vote down vote up
private static Coordinate parseCoordinate(XContentParser parser, boolean ignoreZValue) throws IOException {
    if (parser.currentToken() != XContentParser.Token.VALUE_NUMBER) {
        throw new ElasticsearchParseException("geo coordinates must be numbers");
    }
    final double lon = parser.doubleValue();
    if (parser.nextToken() != XContentParser.Token.VALUE_NUMBER) {
        throw new ElasticsearchParseException("geo coordinates must be numbers");
    }
    final double lat = parser.doubleValue();
    XContentParser.Token token = parser.nextToken();
    // alt (for storing purposes only - future use includes 3d shapes)
    double alt = Double.NaN;
    if (token == XContentParser.Token.VALUE_NUMBER) {
        alt = GeoPoint.assertZValue(ignoreZValue, parser.doubleValue());
        parser.nextToken();
    }
    // do not support > 3 dimensions
    if (parser.currentToken() == XContentParser.Token.VALUE_NUMBER) {
        throw new ElasticsearchParseException("geo coordinates greater than 3 dimensions are not supported");
    }
    return new Coordinate(lon, lat, alt);
}
 
Example 2
Source File: FeatureData.java    From anomaly-detection with Apache License 2.0 6 votes vote down vote up
public static FeatureData parse(XContentParser parser) throws IOException {
    String featureId = null;
    Double data = null;
    String parsedFeatureName = null;

    ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser::getTokenLocation);
    while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
        String fieldName = parser.currentName();
        parser.nextToken();

        switch (fieldName) {
            case FEATURE_ID_FIELD:
                featureId = parser.text();
                break;
            case FEATURE_NAME_FIELD:
                parsedFeatureName = parser.text();
                break;
            case DATA_FIELD:
                data = parser.doubleValue();
                break;
            default:
                break;
        }
    }
    return new FeatureData(featureId, parsedFeatureName, data);
}
 
Example 3
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 4
Source File: AbstractXContentParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
static Object readValue(XContentParser parser, MapFactory mapFactory, XContentParser.Token token) throws IOException {
    if (token == XContentParser.Token.VALUE_NULL) {
        return null;
    } else if (token == XContentParser.Token.VALUE_STRING) {
        return parser.text();
    } else if (token == XContentParser.Token.VALUE_NUMBER) {
        XContentParser.NumberType numberType = parser.numberType();
        if (numberType == XContentParser.NumberType.INT) {
            return parser.intValue();
        } else if (numberType == XContentParser.NumberType.LONG) {
            return parser.longValue();
        } else if (numberType == XContentParser.NumberType.FLOAT) {
            return parser.floatValue();
        } else if (numberType == XContentParser.NumberType.DOUBLE) {
            return parser.doubleValue();
        }
    } else if (token == XContentParser.Token.VALUE_BOOLEAN) {
        return parser.booleanValue();
    } else if (token == XContentParser.Token.START_OBJECT) {
        return readMap(parser, mapFactory);
    } else if (token == XContentParser.Token.START_ARRAY) {
        return readList(parser, mapFactory);
    } else if (token == XContentParser.Token.VALUE_EMBEDDED_OBJECT) {
        return parser.binaryValue();
    }
    return null;
}
 
Example 5
Source File: ShapeBuilder.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Recursive method which parses the arrays of coordinates used to define
 * Shapes
 * 
 * @param parser
 *            Parser that will be read from
 * @return CoordinateNode representing the start of the coordinate tree
 * @throws IOException
 *             Thrown if an error occurs while reading from the
 *             XContentParser
 */
private static CoordinateNode parseCoordinates(XContentParser parser) throws IOException {
    XContentParser.Token token = parser.nextToken();

    // Base cases
    if (token != XContentParser.Token.START_ARRAY && 
            token != XContentParser.Token.END_ARRAY && 
            token != XContentParser.Token.VALUE_NULL) {
        double lon = parser.doubleValue();
        token = parser.nextToken();
        double lat = parser.doubleValue();
        token = parser.nextToken();
        while (token == XContentParser.Token.VALUE_NUMBER) {
            token = parser.nextToken();
        }
        return new CoordinateNode(new Coordinate(lon, lat));
    } else if (token == XContentParser.Token.VALUE_NULL) {
        throw new IllegalArgumentException("coordinates cannot contain NULL values)");
    }

    List<CoordinateNode> nodes = new ArrayList<>();
    while (token != XContentParser.Token.END_ARRAY) {
        nodes.add(parseCoordinates(parser));
        token = parser.nextToken();
    }

    return new CoordinateNode(nodes);
}
 
Example 6
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 7
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 8
Source File: GeolocationContextMapping.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
protected static Collection<String> parseSinglePointOrList(XContentParser parser) throws IOException {
    Token token = parser.currentToken();
    if(token == Token.START_ARRAY) {
        token = parser.nextToken();
        // Test if value is a single point in <code>[lon, lat]</code> format
        if(token == Token.VALUE_NUMBER) {
            double lon = parser.doubleValue();
            if(parser.nextToken() == Token.VALUE_NUMBER) {
                double lat = parser.doubleValue();
                if(parser.nextToken() == Token.END_ARRAY) {
                    return Collections.singleton(GeoHashUtils.stringEncode(lon, lat));
                } else {
                    throw new ElasticsearchParseException("only two values expected");
                }
            } else {
                throw new ElasticsearchParseException("latitue must be a numeric value");
            }
        } else {
            // otherwise it's a list of locations
            ArrayList<String> result = new ArrayList<>();
            while (token != Token.END_ARRAY) {
                result.add(GeoUtils.parseGeoPoint(parser).geohash());
                token = parser.nextToken(); //infinite loop without this line
            }
            return result;
        }
    } else {
        // or a single location
        return Collections.singleton(GeoUtils.parseGeoPoint(parser).geohash());
    }
}
 
Example 9
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 10
Source File: DateRangeParser.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, InternalDateRange.TYPE, context)
            .targetValueType(ValueType.DATE)
            .formattable(true)
            .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 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 {
                                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName
                                        + "]: [" + currentFieldName + "].", parser.getTokenLocation());
                            }
                        } 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();
                            } else {
                                throw new SearchParseException(context, "Unknown key for a " + token + " in [" + aggregationName + "]: [" + currentFieldName + "].", parser.getTokenLocation());
                            }
                        }
                    }
                    ranges.add(new RangeAggregator.Range(key, from, fromAsStr, to, toAsStr));
                }
            }
        } 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(), InternalDateRange.FACTORY, ranges, keyed);
}
 
Example 11
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 12
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 13
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 14
Source File: GeoUtils.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
/**
 * Parse a {@link GeoPoint} with a {@link XContentParser}. A geopoint has one of the following forms:
 * 
 * <ul>
 *     <li>Object: <pre>{&quot;lat&quot;: <i>&lt;latitude&gt;</i>, &quot;lon&quot;: <i>&lt;longitude&gt;</i>}</pre></li>
 *     <li>String: <pre>&quot;<i>&lt;latitude&gt;</i>,<i>&lt;longitude&gt;</i>&quot;</pre></li>
 *     <li>Geohash: <pre>&quot;<i>&lt;geohash&gt;</i>&quot;</pre></li>
 *     <li>Array: <pre>[<i>&lt;longitude&gt;</i>,<i>&lt;latitude&gt;</i>]</pre></li>
 * </ul>
 * 
 * @param parser {@link XContentParser} to parse the value from
 * @param point A {@link GeoPoint} that will be reset by the values parsed
 * @return new {@link GeoPoint} parsed from the parse
 */
public static GeoPoint parseGeoPoint(XContentParser parser, GeoPoint point) throws IOException, ElasticsearchParseException {
    double lat = Double.NaN;
    double lon = Double.NaN;
    String geohash = null;
    
    if(parser.currentToken() == Token.START_OBJECT) {
        while(parser.nextToken() != Token.END_OBJECT) {
            if(parser.currentToken() == Token.FIELD_NAME) {
                String field = parser.currentName();
                if(LATITUDE.equals(field)) {
                    parser.nextToken();
                    switch (parser.currentToken()) {
                        case VALUE_NUMBER:
                        case VALUE_STRING:
                            lat = parser.doubleValue(true);
                            break;
                        default:
                            throw new ElasticsearchParseException("latitude must be a number");
                    }
                } else if (LONGITUDE.equals(field)) {
                    parser.nextToken();
                    switch (parser.currentToken()) {
                        case VALUE_NUMBER:
                        case VALUE_STRING:
                            lon = parser.doubleValue(true);
                            break;
                        default:
                            throw new ElasticsearchParseException("longitude must be a number");
                    }
                } else if (GEOHASH.equals(field)) {
                    if(parser.nextToken() == Token.VALUE_STRING) {
                        geohash = parser.text();
                    } else {
                        throw new ElasticsearchParseException("geohash must be a string");
                    }
                } else {
                    throw new ElasticsearchParseException("field must be either [{}], [{}] or [{}]", LATITUDE, LONGITUDE, GEOHASH);
                }
            } else {
                throw new ElasticsearchParseException("token [{}] not allowed", parser.currentToken());
            }
        }

        if (geohash != null) {
            if(!Double.isNaN(lat) || !Double.isNaN(lon)) {
                throw new ElasticsearchParseException("field must be either lat/lon or geohash");
            } else {
                return point.resetFromGeoHash(geohash);
            }
        } else if (Double.isNaN(lat)) {
            throw new ElasticsearchParseException("field [{}] missing", LATITUDE);
        } else if (Double.isNaN(lon)) {
            throw new ElasticsearchParseException("field [{}] missing", LONGITUDE);
        } else {
            return point.reset(lat, lon);
        }
        
    } else if(parser.currentToken() == Token.START_ARRAY) {
        int element = 0;
        while(parser.nextToken() != Token.END_ARRAY) {
            if(parser.currentToken() == Token.VALUE_NUMBER) {
                element++;
                if(element == 1) {
                    lon = parser.doubleValue();
                } else if(element == 2) {
                    lat = parser.doubleValue();
                } else {
                    throw new ElasticsearchParseException("only two values allowed");
                }
            } else {
                throw new ElasticsearchParseException("numeric value expected");
            }
        }
        return point.reset(lat, lon);
    } else if(parser.currentToken() == Token.VALUE_STRING) {
        String data = parser.text();
        return parseGeoPoint(data, point);
    } else {
        throw new ElasticsearchParseException("geo_point expected");
    }
}
 
Example 15
Source File: GeoDistanceParser.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.GeoPoint> vsParser = ValuesSourceParser.geoPoint(aggregationName, InternalGeoDistance.TYPE, context).build();

    GeoPointParser geoPointParser = new GeoPointParser(aggregationName, InternalGeoDistance.TYPE, context, ORIGIN_FIELD);

    List<RangeAggregator.Range> ranges = null;
    DistanceUnit unit = DistanceUnit.DEFAULT;
    GeoDistance distanceType = GeoDistance.DEFAULT;
    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 (geoPointParser.token(currentFieldName, token, parser)) {
            continue;
        } else if (token == XContentParser.Token.VALUE_STRING) {
            if ("unit".equals(currentFieldName)) {
                unit = DistanceUnit.fromString(parser.text());
            } else if ("distance_type".equals(currentFieldName) || "distanceType".equals(currentFieldName)) {
                distanceType = GeoDistance.fromString(parser.text());
            } 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 if (token == XContentParser.Token.START_ARRAY) {
            if ("ranges".equals(currentFieldName)) {
                ranges = new ArrayList<>();
                while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
                    String fromAsStr = null;
                    String toAsStr = null;
                    double from = 0.0;
                    double to = Double.POSITIVE_INFINITY;
                    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 ("key".equals(toOrFromOrKey)) {
                                key = parser.text();
                            } else if ("from".equals(toOrFromOrKey)) {
                                fromAsStr = parser.text();
                            } else if ("to".equals(toOrFromOrKey)) {
                                toAsStr = parser.text();
                            }
                        }
                    }
                    ranges.add(new RangeAggregator.Range(key(key, from, to), from, fromAsStr, to, toAsStr));
                }
            } 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 + "]: ["
                    + currentFieldName + "].", parser.getTokenLocation());
        }
    }

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

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

    return new GeoDistanceFactory(aggregationName, vsParser.config(), InternalGeoDistance.FACTORY, origin, unit, distanceType, ranges, keyed);
}
 
Example 16
Source File: NumberFieldMapper.java    From crate with Apache License 2.0 4 votes vote down vote up
@Override
public Double parse(XContentParser parser, boolean coerce) throws IOException {
    return parser.doubleValue(coerce);
}
 
Example 17
Source File: AnomalyResult.java    From anomaly-detection with Apache License 2.0 4 votes vote down vote up
public static AnomalyResult parse(XContentParser parser) throws IOException {
    String detectorId = null;
    Double anomalyScore = null;
    Double anomalyGrade = null;
    Double confidence = null;
    List<FeatureData> featureData = new ArrayList<>();
    Instant dataStartTime = null;
    Instant dataEndTime = null;
    Instant executionStartTime = null;
    Instant executionEndTime = null;
    String error = null;

    ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.currentToken(), parser::getTokenLocation);
    while (parser.nextToken() != XContentParser.Token.END_OBJECT) {
        String fieldName = parser.currentName();
        parser.nextToken();

        switch (fieldName) {
            case DETECTOR_ID_FIELD:
                detectorId = parser.text();
                break;
            case ANOMALY_SCORE_FIELD:
                anomalyScore = parser.doubleValue();
                break;
            case ANOMALY_GRADE_FIELD:
                anomalyGrade = parser.doubleValue();
                break;
            case CONFIDENCE_FIELD:
                confidence = parser.doubleValue();
                break;
            case FEATURE_DATA_FIELD:
                ensureExpectedToken(XContentParser.Token.START_ARRAY, parser.currentToken(), parser::getTokenLocation);
                while (parser.nextToken() != XContentParser.Token.END_ARRAY) {
                    featureData.add(FeatureData.parse(parser));
                }
                break;
            case DATA_START_TIME_FIELD:
                dataStartTime = ParseUtils.toInstant(parser);
                break;
            case DATA_END_TIME_FIELD:
                dataEndTime = ParseUtils.toInstant(parser);
                break;
            case EXECUTION_START_TIME_FIELD:
                executionStartTime = ParseUtils.toInstant(parser);
                break;
            case EXECUTION_END_TIME_FIELD:
                executionEndTime = ParseUtils.toInstant(parser);
                break;
            case ERROR_FIELD:
                error = parser.text();
                break;
            default:
                parser.skipChildren();
                break;
        }
    }
    return new AnomalyResult(
        detectorId,
        anomalyScore,
        anomalyGrade,
        confidence,
        featureData,
        dataStartTime,
        dataEndTime,
        executionStartTime,
        executionEndTime,
        error
    );
}