org.elasticsearch.ElasticsearchParseException Java Examples

The following examples show how to use org.elasticsearch.ElasticsearchParseException. 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: XContentSettingsLoader.java    From Elasticsearch with 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 #2
Source File: DefaultAggregationService.java    From jetlinks-community with 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 #3
Source File: DateMathParser.java    From Elasticsearch with 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 #4
Source File: ShapeBuilder.java    From Elasticsearch with 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 #5
Source File: BuilderFactory.java    From crate with 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 #6
Source File: LeafFieldsLookup.java    From Elasticsearch with 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 #7
Source File: ArrayMapper.java    From Elasticsearch with 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 #8
Source File: GeoPoint.java    From crate with 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 #9
Source File: MatchPredicate.java    From Elasticsearch with 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 #10
Source File: GeolocationContextMapping.java    From Elasticsearch with 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 #11
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 #12
Source File: NXYSignificanceHeuristic.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public SignificanceHeuristic parse(XContentParser parser, ParseFieldMatcher parseFieldMatcher, SearchContext context)
        throws IOException, QueryParsingException {
    String givenName = parser.currentName();
    boolean includeNegatives = false;
    boolean backgroundIsSuperset = true;
    XContentParser.Token token = parser.nextToken();
    while (!token.equals(XContentParser.Token.END_OBJECT)) {
        if (parseFieldMatcher.match(parser.currentName(), INCLUDE_NEGATIVES_FIELD)) {
            parser.nextToken();
            includeNegatives = parser.booleanValue();
        } else if (parseFieldMatcher.match(parser.currentName(), BACKGROUND_IS_SUPERSET)) {
            parser.nextToken();
            backgroundIsSuperset = parser.booleanValue();
        } else {
            throw new ElasticsearchParseException("failed to parse [{}] significance heuristic. unknown field [{}]", givenName, parser.currentName());
        }
        token = parser.nextToken();
    }
    return newHeuristic(includeNegatives, backgroundIsSuperset);
}
 
Example #13
Source File: DiskThresholdDecider.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Inject
public DiskThresholdDecider(Settings settings, NodeSettingsService nodeSettingsService, ClusterInfoService infoService, Client client) {
    super(settings);
    String lowWatermark = settings.get(CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK,
            DEFAULT_LOW_DISK_WATERMARK);
    String highWatermark = settings.get(CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK,
            DEFAULT_HIGH_DISK_WATERMARK);

    if (!validWatermarkSetting(lowWatermark, CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK)) {
        throw new ElasticsearchParseException("unable to parse low watermark [{}]", lowWatermark);
    }
    if (!validWatermarkSetting(highWatermark, CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK)) {
        throw new ElasticsearchParseException("unable to parse high watermark [{}]", highWatermark);
    }
    // Watermark is expressed in terms of used data, but we need "free" data watermark
    this.freeDiskThresholdLow = 100.0 - thresholdPercentageFromWatermark(lowWatermark);
    this.freeDiskThresholdHigh = 100.0 - thresholdPercentageFromWatermark(highWatermark);

    this.freeBytesThresholdLow = thresholdBytesFromWatermark(lowWatermark, CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK);
    this.freeBytesThresholdHigh = thresholdBytesFromWatermark(highWatermark, CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK);
    this.includeRelocations = settings.getAsBoolean(CLUSTER_ROUTING_ALLOCATION_INCLUDE_RELOCATIONS,
            DEFAULT_INCLUDE_RELOCATIONS);
    this.rerouteInterval = settings.getAsTime(CLUSTER_ROUTING_ALLOCATION_REROUTE_INTERVAL, TimeValue.timeValueSeconds(60));

    this.enabled = settings.getAsBoolean(CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED,
            DEFAULT_THRESHOLD_ENABLED);
    nodeSettingsService.addListener(new ApplySettings());
    infoService.addListener(new DiskListener(client));
}
 
Example #14
Source File: GeoWKTParser.java    From crate with Apache License 2.0 5 votes vote down vote up
private static EnvelopeBuilder parseBBox(StreamTokenizer stream) throws IOException, ElasticsearchParseException {
    if (nextEmptyOrOpen(stream).equals(EMPTY)) {
        return null;
    }
    final double minLon = nextNumber(stream);
    nextComma(stream);
    final double maxLon = nextNumber(stream);
    nextComma(stream);
    final double maxLat = nextNumber(stream);
    nextComma(stream);
    final double minLat = nextNumber(stream);
    nextCloser(stream);
    return new EnvelopeBuilder(new Coordinate(minLon, maxLat), new Coordinate(maxLon, minLat));
}
 
Example #15
Source File: XContentMapValues.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
public static Map<String, Object> nodeMapValue(Object node, String desc) {
    if (node instanceof Map) {
        return (Map<String, Object>) node;
    } else {
        throw new ElasticsearchParseException(desc + " should be a hash but was of type: " + node.getClass());
    }
}
 
Example #16
Source File: FilterJoinNode.java    From siren-join with GNU Affero General Public License v3.0 5 votes vote down vote up
public String[] getLookupTypes() {
  Map<String, Object> conf = (Map<String, Object>) this.self.get(this.getField());
  Object o = conf.get("types");
  if (o == null) {
    return new String[0];
  }
  if (o instanceof String) {
    return new String[]{ (String) o };
  }
  if (o instanceof List) {
    return ((List<String>) o).toArray(new String[((List) o).size()]);
  }
  throw new ElasticsearchParseException("Unable to build the lookup query - Invalid 'types' parameter.");
}
 
Example #17
Source File: ShapeBuilder.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
protected static void validatePointNode(CoordinateNode node) {
    if (node.isEmpty()) {
        throw new ElasticsearchParseException("invalid number of points (0) provided when expecting a single coordinate ([lat, lng])");
    } else if (node.coordinate == null) {
        if (node.children.isEmpty() == false) {
            throw new ElasticsearchParseException("multipoint data provided when single point data expected.");
        }
    }
}
 
Example #18
Source File: AllocateAllocationCommand.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public AllocateAllocationCommand fromXContent(XContentParser parser) throws IOException {
    String index = null;
    int shardId = -1;
    String nodeId = null;
    boolean allowPrimary = false;

    String currentFieldName = null;
    XContentParser.Token token;
    while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
        if (token == XContentParser.Token.FIELD_NAME) {
            currentFieldName = parser.currentName();
        } else if (token.isValue()) {
            if ("index".equals(currentFieldName)) {
                index = parser.text();
            } else if ("shard".equals(currentFieldName)) {
                shardId = parser.intValue();
            } else if ("node".equals(currentFieldName)) {
                nodeId = parser.text();
            } else if ("allow_primary".equals(currentFieldName) || "allowPrimary".equals(currentFieldName)) {
                allowPrimary = parser.booleanValue();
            } else {
                throw new ElasticsearchParseException("[{}] command does not support field [{}]", NAME, currentFieldName);
            }
        } else {
            throw new ElasticsearchParseException("[{}] command does not support complex json tokens [{}]", NAME, token);
        }
    }
    if (index == null) {
        throw new ElasticsearchParseException("[{}] command missing the index parameter", NAME);
    }
    if (shardId == -1) {
        throw new ElasticsearchParseException("[{}] command missing the shard parameter", NAME);
    }
    if (nodeId == null) {
        throw new ElasticsearchParseException("[{}] command missing the node parameter", NAME);
    }
    return new AllocateAllocationCommand(new ShardId(index, shardId), nodeId, allowPrimary);
}
 
Example #19
Source File: LineContext.java    From crate with Apache License 2.0 5 votes vote down vote up
@Nullable
Map<String, Object> sourceAsMap() {
    if (parsedSource == null) {
        if (rawSource != null) {
            try {
                parsedSource = XContentHelper.toMap(new BytesArray(rawSource), XContentType.JSON);
            } catch (ElasticsearchParseException | NotXContentException e) {
                throw new RuntimeException("JSON parser error: " + e.getMessage(), e);
            }
        }
    }
    return parsedSource;
}
 
Example #20
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 #21
Source File: XmlXContentFactory.java    From elasticsearch-xml with Apache License 2.0 5 votes vote down vote up
/**
 * Guesses the content type based on the provided bytes.
 */
public static XContent xContent(byte[] data, int offset, int length) {
    XmlXContentType type = xContentType(data, offset, length);
    if (type == null) {
        throw new ElasticsearchParseException("Failed to derive xcontent from (offset=" + offset + ", length=" + length + "): " + Arrays.toString(data));
    }
    return xContent(type);
}
 
Example #22
Source File: DiskThresholdDecider.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Attempts to parse the watermark into a {@link ByteSizeValue}, returning
 * a ByteSizeValue of 0 bytes if the value cannot be parsed.
 */
public ByteSizeValue thresholdBytesFromWatermark(String watermark, String settingName) {
    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
        return ByteSizeValue.parseBytesSizeValue("0b", settingName);
    }
}
 
Example #23
Source File: GetResult.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Returns bytes reference, also un compress the source if needed.
 */
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 #24
Source File: XContentMapValues.java    From crate with Apache License 2.0 5 votes vote down vote up
public static Map<String, Object> nodeMapValue(Object node, String desc) {
    if (node instanceof Map) {
        return (Map<String, Object>) node;
    } else {
        throw new ElasticsearchParseException(desc + " should be a hash but was of type: " + node.getClass());
    }
}
 
Example #25
Source File: CreateIndexRequest.java    From crate with 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 #26
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 #27
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 #28
Source File: DecayFunctionParser.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Parses bodies of the kind
 *
 * <pre>
 * <code>
 * {
 *      "fieldname1" : {
 *          "origin" = "someValue",
 *          "scale" = "someValue"
 *      }
 *
 * }
 * </code>
 * </pre>
 *
 * */
@Override
public ScoreFunction parse(QueryParseContext parseContext, XContentParser parser) throws IOException, QueryParsingException {
    String currentFieldName;
    XContentParser.Token token;
    AbstractDistanceScoreFunction scoreFunction;
    String multiValueMode = "MIN";
    XContentBuilder variableContent = XContentFactory.jsonBuilder();
    String fieldName = null;
    while ((token = parser.nextToken()) == XContentParser.Token.FIELD_NAME) {
        currentFieldName = parser.currentName();
        token = parser.nextToken();
        if (token == XContentParser.Token.START_OBJECT) {
            variableContent.copyCurrentStructure(parser);
            fieldName = currentFieldName;
        } else if (parseContext.parseFieldMatcher().match(currentFieldName, MULTI_VALUE_MODE)) {
            multiValueMode = parser.text();
        } else {
            throw new ElasticsearchParseException("malformed score function score parameters.");
        }
    }
    if (fieldName == null) {
        throw new ElasticsearchParseException("malformed score function score parameters.");
    }
    XContentParser variableParser = XContentFactory.xContent(variableContent.string()).createParser(variableContent.string());
    scoreFunction = parseVariable(fieldName, variableParser, parseContext, MultiValueMode.fromString(multiValueMode.toUpperCase(Locale.ROOT)));
    return scoreFunction;
}
 
Example #29
Source File: RescoreParseElement.java    From Elasticsearch with 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 File: Utils.java    From deprecated-security-advanced-modules with 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);
    }
}