Java Code Examples for org.elasticsearch.ElasticsearchParseException

The following examples show how to use org.elasticsearch.ElasticsearchParseException. These examples are extracted from open source projects. 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 Project: jetlinks-community   Author: jetlinks   File: DefaultAggregationService.java    License: Apache License 2.0 6 votes vote down vote up
private <T> ActionListener<T> translatorActionListener(MonoSink<T> sink) {
    return new ActionListener<T>() {
        @Override
        public void onResponse(T response) {
            sink.success(response);
        }

        @Override
        public void onFailure(Exception e) {
            if (e instanceof ElasticsearchException) {
                if (((ElasticsearchException) e).status().getStatus() == 404) {
                    sink.success();
                    return;
                } else if (((ElasticsearchException) e).status().getStatus() == 400) {
                    sink.error(new ElasticsearchParseException("查询参数格式错误", e));
                }
            }
            sink.error(e);
        }
    };
}
 
Example #2
Source Project: Elasticsearch   Author: baidu   File: ArrayMapper.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Mapper parse(ParseContext context) throws IOException {
    XContentParser parser = context.parser();
    XContentParser.Token token = parser.currentToken();
    if (token == XContentParser.Token.VALUE_NULL) {
        return parseInner(context);
    } else if  (token != XContentParser.Token.START_ARRAY) {
        throw new ElasticsearchParseException("invalid array");
    }
    token = parser.nextToken();
    Mapper newInnerMapper = innerMapper;
    while (token != XContentParser.Token.END_ARRAY) {
        // we only get here for non-empty arrays
        Mapper update = parseInner(context);
        if (update != null) {
            newInnerMapper = newInnerMapper.merge(update, true);
        }
        token = parser.nextToken();
    }
    if (newInnerMapper == innerMapper) {
        return null;
    }
    innerMapper = newInnerMapper;
    return this;
}
 
Example #3
Source Project: crate   Author: crate   File: GeoPoint.java    License: Apache License 2.0 6 votes vote down vote up
public GeoPoint resetFromString(String value, final boolean ignoreZValue) {
    if (value.contains(",")) {
        String[] vals = value.split(",");
        if (vals.length > 3) {
            throw new ElasticsearchParseException("failed to parse [{}], expected 2 or 3 coordinates "
                + "but found: [{}]", vals.length);
        }
        double lat = Double.parseDouble(vals[0].trim());
        double lon = Double.parseDouble(vals[1].trim());
        if (vals.length > 2) {
            GeoPoint.assertZValue(ignoreZValue, Double.parseDouble(vals[2].trim()));
        }
        return reset(lat, lon);
    }
    return resetFromGeoHash(value);
}
 
Example #4
Source Project: Elasticsearch   Author: baidu   File: MatchPredicate.java    License: Apache License 2.0 6 votes vote down vote up
public static String getMatchType(@Nullable  String matchType, DataType columnType) {
    if (matchType == null) {
        return defaultMatchType(columnType);
    }
    if (columnType.equals(DataTypes.STRING)) {
        try {
            MultiMatchQueryBuilder.Type.parse(matchType, ParseFieldMatcher.STRICT);
            return matchType;
        } catch (ElasticsearchParseException e) {
            throw new IllegalArgumentException(String.format(Locale.ENGLISH,
                    "invalid MATCH type '%s' for type '%s'", matchType, columnType), e);
        }
    } else if (columnType.equals(DataTypes.GEO_SHAPE)) {
        if (!SUPPORTED_GEO_MATCH_TYPES.contains(matchType)) {
            throw new IllegalArgumentException(String.format(Locale.ENGLISH,
                    "invalid MATCH type '%s' for type '%s', valid types are: [%s]",
                    matchType, columnType, Joiner.on(",").join(SUPPORTED_GEO_MATCH_TYPES)));
        }
        return matchType;
    }
    throw new IllegalArgumentException("No match type for dataType: " + columnType);
}
 
Example #5
Source Project: Elasticsearch   Author: baidu   File: NXYSignificanceHeuristic.java    License: 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 #6
Source Project: crate   Author: crate   File: BuilderFactory.java    License: Apache License 2.0 6 votes vote down vote up
private static Mapper.Builder<?, ?> detectInnerMapper(ParseContext parseContext,
                                                      String fieldName,
                                                      XContentParser parser) throws IOException {
    XContentParser.Token token = parser.currentToken();
    if (token == XContentParser.Token.START_ARRAY) {
        token = parser.nextToken();
    }

    // can't use nulls to detect type
    while (token == XContentParser.Token.VALUE_NULL) {
        token = parser.nextToken();
    }

    if (token == XContentParser.Token.START_ARRAY) {
        throw new ElasticsearchParseException("nested arrays are not supported");
    } else if (token == XContentParser.Token.END_ARRAY) {
        // array is empty or has only null values
        return null;
    }
    return DocumentParser.createBuilderFromDynamicValue(parseContext, token, fieldName);
}
 
Example #7
Source Project: Elasticsearch   Author: baidu   File: XContentSettingsLoader.java    License: Apache License 2.0 6 votes vote down vote up
private void serializeValue(Map<String, String> settings, StringBuilder sb, List<String> path, XContentParser parser, String fieldName) throws IOException {
    sb.setLength(0);
    for (String pathEle : path) {
        sb.append(pathEle).append('.');
    }
    sb.append(fieldName);
    String key = sb.toString();
    String currentValue = parser.text();
    String previousValue = settings.put(key, currentValue);
    if (previousValue != null) {
        throw new ElasticsearchParseException(
                "duplicate settings key [{}] found at line number [{}], column number [{}], previous value [{}], current value [{}]",
                key,
                parser.getTokenLocation().lineNumber,
                parser.getTokenLocation().columnNumber,
                previousValue,
                currentValue
        );
    }
}
 
Example #8
Source Project: crate   Author: crate   File: GeoJsonParser.java    License: 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 #9
Source Project: Elasticsearch   Author: baidu   File: GeolocationContextMapping.java    License: Apache License 2.0 6 votes vote down vote up
private static final int parsePrecision(XContentParser parser) throws IOException, ElasticsearchParseException {
    switch (parser.currentToken()) {
    case VALUE_STRING:
        return GeoUtils.geoHashLevelsForPrecision(parser.text());
    case VALUE_NUMBER:
        switch (parser.numberType()) {
        case INT:
        case LONG:
            return parser.intValue();
        default:
            return GeoUtils.geoHashLevelsForPrecision(parser.doubleValue());
        }
    default:
        throw new ElasticsearchParseException("invalid precision value");
    }
}
 
Example #10
Source Project: Elasticsearch   Author: baidu   File: LeafFieldsLookup.java    License: Apache License 2.0 6 votes vote down vote up
private FieldLookup loadFieldData(String name) {
    FieldLookup data = cachedFieldData.get(name);
    if (data == null) {
        MappedFieldType fieldType = mapperService.smartNameFieldType(name, types);
        if (fieldType == null) {
            throw new IllegalArgumentException("No field found for [" + name + "] in mapping with types " + Arrays.toString(types) + "");
        }
        data = new FieldLookup(fieldType);
        cachedFieldData.put(name, data);
    }
    if (data.fields() == null) {
        String fieldName = data.fieldType().names().indexName();
        fieldVisitor.reset(fieldName);
        try {
            reader.document(docId, fieldVisitor);
            fieldVisitor.postProcess(data.fieldType());
            data.fields(ImmutableMap.of(name, fieldVisitor.fields().get(data.fieldType().names().indexName())));
        } catch (IOException e) {
            throw new ElasticsearchParseException("failed to load field [{}]", e, name);
        }
    }
    return data;
}
 
Example #11
Source Project: Elasticsearch   Author: baidu   File: ShapeBuilder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parse the geometries array of a GeometryCollection
 *
 * @param parser Parser that will be read from
 * @return Geometry[] geometries of the GeometryCollection
 * @throws IOException Thrown if an error occurs while reading from the XContentParser
 */
protected static GeometryCollectionBuilder parseGeometries(XContentParser parser, GeoShapeFieldMapper mapper) throws
        IOException {
    if (parser.currentToken() != XContentParser.Token.START_ARRAY) {
        throw new ElasticsearchParseException("geometries must be an array of geojson objects");
    }

    XContentParser.Token token = parser.nextToken();
    GeometryCollectionBuilder geometryCollection = newGeometryCollection( (mapper == null) ? Orientation.RIGHT : mapper
            .fieldType().orientation());
    while (token != XContentParser.Token.END_ARRAY) {
        ShapeBuilder shapeBuilder = GeoShapeType.parse(parser);
        geometryCollection.shape(shapeBuilder);
        token = parser.nextToken();
    }

    return geometryCollection;
}
 
Example #12
Source Project: Elasticsearch   Author: baidu   File: DateMathParser.java    License: Apache License 2.0 6 votes vote down vote up
public long parse(String text, Callable<Long> now, boolean roundUp, DateTimeZone timeZone) {
    long time;
    String mathString;
    if (text.startsWith("now")) {
        try {
            time = now.call();
        } catch (Exception e) {
            throw new ElasticsearchParseException("could not read the current timestamp", e);
        }
        mathString = text.substring("now".length());
    } else {
        int index = text.indexOf("||");
        if (index == -1) {
            return parseDateTime(text, timeZone);
        }
        time = parseDateTime(text.substring(0, index), timeZone);
        mathString = text.substring(index + 2);
        if (mathString.isEmpty()) {
            return time;
        }
    }

    return parseMath(mathString, time, roundUp, timeZone);
}
 
Example #13
Source Project: deprecated-security-advanced-modules   Author: opendistro-for-elasticsearch   File: Utils.java    License: Apache License 2.0 5 votes vote down vote up
public static String convertStructuredMapToJson(Map<String, Object> structuredMap) {
    try {
        return XContentHelper.convertToJson(convertStructuredMapToBytes(structuredMap), false, XContentType.JSON);
    } catch (IOException e) {
        throw new ElasticsearchParseException("Failed to convert map", e);
    }
}
 
Example #14
Source Project: crate   Author: crate   File: MatchPredicate.java    License: Apache License 2.0 5 votes vote down vote up
public static String getMatchType(@Nullable String matchType, DataType<?> columnType) {
    if (matchType == null) {
        return defaultMatchType(columnType);
    }
    if (columnType.equals(DataTypes.STRING)) {
        try {
            MultiMatchQueryType.parse(matchType, LoggingDeprecationHandler.INSTANCE);
            return matchType;
        } catch (ElasticsearchParseException e) {
            throw new IllegalArgumentException(String.format(
                Locale.ENGLISH,
                "invalid MATCH type '%s' for type '%s'",
                matchType,
                columnType), e);
        }
    } else if (columnType.equals(DataTypes.GEO_SHAPE)) {
        if (!SUPPORTED_GEO_MATCH_TYPES.contains(matchType)) {
            throw new IllegalArgumentException(String.format(
                Locale.ENGLISH,
                "invalid MATCH type '%s' for type '%s', valid types are: [%s]",
                matchType,
                columnType,
                String.join(",", SUPPORTED_GEO_MATCH_TYPES)));
        }
        return matchType;
    }
    throw new IllegalArgumentException("No match type for dataType: " + columnType);
}
 
Example #15
Source Project: crate   Author: crate   File: SnapshotShardFailure.java    License: Apache License 2.0 5 votes vote down vote up
private static SnapshotShardFailure constructSnapshotShardFailure(Object[] args) {
    String index = (String) args[0];
    String indexUuid = (String) args[1];
    final String nodeId = (String) args[2];
    String reason = (String) args[3];
    Integer intShardId = (Integer) args[4];
    final String status = (String) args[5];

    if (index == null) {
        throw new ElasticsearchParseException("index name was not set");
    }
    if (intShardId == null) {
        throw new ElasticsearchParseException("index shard was not set");
    }

    ShardId shardId = new ShardId(index, indexUuid != null ? indexUuid : IndexMetaData.INDEX_UUID_NA_VALUE, intShardId);

    // Workaround for https://github.com/elastic/elasticsearch/issues/25878
    // Some old snapshot might still have null in shard failure reasons
    String nonNullReason;
    if (reason != null) {
        nonNullReason = reason;
    } else {
        nonNullReason = "";
    }


    RestStatus restStatus;
    if (status != null) {
        restStatus = RestStatus.valueOf(status);
    } else {
        restStatus = RestStatus.INTERNAL_SERVER_ERROR;
    }

    return new SnapshotShardFailure(nodeId, shardId, nonNullReason, restStatus);
}
 
Example #16
Source Project: Elasticsearch   Author: baidu   File: ExpressionToMemoryValueVisitor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected ByteSizeValue visitStringLiteral(StringLiteral node, Context context) {
    try {
        return MemorySizeValue.parseBytesSizeValueOrHeapRatio(node.getValue(), context.settingName);
    } catch (ElasticsearchParseException e) {
        throw new IllegalArgumentException(
                String.format(Locale.ENGLISH, "Invalid byte size value '%s'", node.getValue()));
    }
}
 
Example #17
Source Project: crate   Author: crate   File: GeoWKTParser.java    License: Apache License 2.0 5 votes vote down vote up
private static double nextNumber(StreamTokenizer stream) throws IOException, ElasticsearchParseException {
    if (stream.nextToken() == StreamTokenizer.TT_WORD) {
        if (stream.sval.equalsIgnoreCase(NAN)) {
            return Double.NaN;
        } else {
            try {
                return Double.parseDouble(stream.sval);
            } catch (NumberFormatException e) {
                throw new ElasticsearchParseException("invalid number found: " + stream.sval, stream.lineno());
            }
        }
    }
    throw new ElasticsearchParseException("expected number but found: " + tokenString(stream), stream.lineno());
}
 
Example #18
Source Project: Elasticsearch   Author: baidu   File: PercolatorService.java    License: Apache License 2.0 5 votes vote down vote up
private void parseSort(XContentParser parser, PercolateContext context) throws Exception {
    sortParseElement.parse(parser, context);
    // null, means default sorting by relevancy
    if (context.sort() == null) {
        context.doSort = true;
    } else {
        throw new ElasticsearchParseException("Only _score desc is supported");
    }
}
 
Example #19
Source Project: crate   Author: crate   File: DiskThresholdSettings.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to parse the watermark into a {@link ByteSizeValue}, returning zero bytes if it can not be parsed and the specified lenient
 * parameter is true, otherwise throwing an {@link ElasticsearchParseException}.
 *
 * @param watermark the watermark to parse as a byte size
 * @param settingName the name of the setting
 * @param lenient true if lenient parsing should be applied
 * @return the parsed byte size value
 */
private static ByteSizeValue thresholdBytesFromWatermark(String watermark, String settingName, boolean lenient) {
    try {
        return ByteSizeValue.parseBytesSizeValue(watermark, settingName);
    } catch (ElasticsearchParseException ex) {
        // NOTE: this is not end-user leniency, since up above we check that it's a valid byte or percentage, and then store the two
        // cases separately
        if (lenient) {
            return ByteSizeValue.parseBytesSizeValue("0b", settingName);
        }
        throw ex;
    }
}
 
Example #20
Source Project: Elasticsearch   Author: baidu   File: Aggregator.java    License: Apache License 2.0 5 votes vote down vote up
public static SubAggCollectionMode parse(String value, ParseFieldMatcher parseFieldMatcher) {
    SubAggCollectionMode[] modes = SubAggCollectionMode.values();
    for (SubAggCollectionMode mode : modes) {
        if (parseFieldMatcher.match(value, mode.parseField)) {
            return mode;
        }
    }
    throw new ElasticsearchParseException("no [{}] found for value [{}]", KEY.getPreferredName(), value);
}
 
Example #21
Source Project: crate   Author: crate   File: PutIndexTemplateRequest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets the aliases that will be associated with the index when it gets created
 */
public PutIndexTemplateRequest aliases(BytesReference source) {
    // EMPTY is safe here because we never call namedObject
    try (XContentParser parser = XContentHelper
            .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, source)) {
        //move to the first alias
        parser.nextToken();
        while ((parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            alias(Alias.fromXContent(parser));
        }
        return this;
    } catch (IOException e) {
        throw new ElasticsearchParseException("Failed to parse aliases", e);
    }
}
 
Example #22
Source Project: Elasticsearch   Author: baidu   File: JLHScore.java    License: 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 #23
Source Project: crate   Author: crate   File: GeoPointFieldMapper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Parses geopoint represented as a string and ignores malformed geopoints if needed
 */
private void parseGeoPointStringIgnoringMalformed(ParseContext context, GeoPoint sparse) throws IOException {
    try {
        parse(context, sparse.resetFromString(context.parser().text(), ignoreZValue.value()));
    } catch (ElasticsearchParseException e) {
        if (ignoreMalformed.value() == false) {
            throw e;
        }
        context.addIgnoredField(fieldType.name());
    }
}
 
Example #24
Source Project: Elasticsearch   Author: baidu   File: CreateIndexRequest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets the aliases that will be associated with the index when it gets created
 */
public CreateIndexRequest aliases(BytesReference source) {
    try {
        XContentParser parser = XContentHelper.createParser(source);
        //move to the first alias
        parser.nextToken();
        while ((parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            alias(Alias.fromXContent(parser));
        }
        return this;
    } catch(IOException e) {
        throw new ElasticsearchParseException("Failed to parse aliases", e);
    }
}
 
Example #25
Source Project: crate   Author: crate   File: GeoWKTParser.java    License: Apache License 2.0 5 votes vote down vote up
private static MultiPointBuilder parseMultiPoint(StreamTokenizer stream, final boolean ignoreZValue)
        throws IOException, ElasticsearchParseException {
    String token = nextEmptyOrOpen(stream);
    if (token.equals(EMPTY)) {
        return null;
    }
    return new MultiPointBuilder(parseCoordinateList(stream, ignoreZValue));
}
 
Example #26
Source Project: crate   Author: crate   File: DiskThresholdSettings.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to parse the watermark into a percentage, returning 100.0% if it can not be parsed and the specified lenient parameter is
 * true, otherwise throwing an {@link ElasticsearchParseException}.
 *
 * @param watermark the watermark to parse as a percentage
 * @param lenient true if lenient parsing should be applied
 * @return the parsed percentage
 */
private static double thresholdPercentageFromWatermark(String watermark, boolean lenient) {
    try {
        return RatioValue.parseRatioValue(watermark).getAsPercent();
    } catch (ElasticsearchParseException ex) {
        // NOTE: this is not end-user leniency, since up above we check that it's a valid byte or percentage, and then store the two
        // cases separately
        if (lenient) {
            return 100.0;
        }
        throw ex;
    }
}
 
Example #27
Source Project: Elasticsearch   Author: baidu   File: InternalSearchHit.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns bytes reference, also un compress the source if needed.
 */
@Override
public BytesReference sourceRef() {
    try {
        this.source = CompressorFactory.uncompressIfNeeded(this.source);
        return this.source;
    } catch (IOException e) {
        throw new ElasticsearchParseException("failed to decompress source", e);
    }
}
 
Example #28
Source Project: crate   Author: crate   File: CreateIndexRequest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets the aliases that will be associated with the index when it gets created
 */
public CreateIndexRequest aliases(BytesReference source) {
    // EMPTY is safe here because we never call namedObject
    try (XContentParser parser = XContentHelper
            .createParser(NamedXContentRegistry.EMPTY, LoggingDeprecationHandler.INSTANCE, source)) {
        //move to the first alias
        parser.nextToken();
        while ((parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            alias(Alias.fromXContent(parser));
        }
        return this;
    } catch (IOException e) {
        throw new ElasticsearchParseException("Failed to parse aliases", e);
    }
}
 
Example #29
Source Project: Elasticsearch   Author: baidu   File: RescoreParseElement.java    License: Apache License 2.0 5 votes vote down vote up
public void parseSingleRescoreContext(XContentParser parser, SearchContext context) throws Exception {
    String fieldName = null;
    RescoreSearchContext rescoreContext = null;
    Integer windowSize = null;
    XContentParser.Token token;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            fieldName = parser.currentName();
            if (QueryRescorer.NAME.equals(fieldName)) {
                // we only have one at this point
                Rescorer rescorer = QueryRescorer.INSTANCE;
                token = parser.nextToken();
                if (token != XContentParser.Token.START_OBJECT) {
                    throw new ElasticsearchParseException("rescore type malformed, must start with start_object");
                }
                rescoreContext = rescorer.parse(parser, context);
            }
        } else if (token.isValue()) {
            if ("window_size".equals(fieldName)) {
                windowSize = parser.intValue();
            } else {
                throw new IllegalArgumentException("rescore doesn't support [" + fieldName + "]");
            }
        }
    }
    if (rescoreContext == null) {
        throw new IllegalArgumentException("missing rescore type");
    }
    if (windowSize != null) {
        rescoreContext.setWindowSize(windowSize.intValue());
    }
    context.addRescore(rescoreContext);
}
 
Example #30
Source Project: Elasticsearch   Author: baidu   File: DecayFunctionParser.java    License: 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;
}