Search in sources :

Example 21 with ElasticsearchParseException

use of org.elasticsearch.ElasticsearchParseException in project elasticsearch by elastic.

the class RestRequest method contentOrSourceParamParser.

/**
     * A parser for the contents of this request if it has contents, otherwise a parser for the {@code source} parameter if there is one,
     * otherwise throws an {@link ElasticsearchParseException}. Use {@link #withContentOrSourceParamParserOrNull(CheckedConsumer)} instead
     * if you need to handle the absence request content gracefully.
     */
public final XContentParser contentOrSourceParamParser() throws IOException {
    Tuple<XContentType, BytesReference> tuple = contentOrSourceParam();
    BytesReference content = tuple.v2();
    if (content.length() == 0) {
        throw new ElasticsearchParseException("Body required");
    }
    return tuple.v1().xContent().createParser(xContentRegistry, content);
}
Also used : BytesReference(org.elasticsearch.common.bytes.BytesReference) XContentType(org.elasticsearch.common.xcontent.XContentType) ElasticsearchParseException(org.elasticsearch.ElasticsearchParseException)

Example 22 with ElasticsearchParseException

use of org.elasticsearch.ElasticsearchParseException in project elasticsearch by elastic.

the class GeoDistanceSortBuilder method parseGeoPoints.

static void parseGeoPoints(XContentParser parser, List<GeoPoint> geoPoints) throws IOException {
    while (!parser.nextToken().equals(XContentParser.Token.END_ARRAY)) {
        if (parser.currentToken() == XContentParser.Token.VALUE_NUMBER) {
            // we might get here if the geo point is " number, number] " and the parser already moved over the
            // opening bracket in this case we cannot use GeoUtils.parseGeoPoint(..) because this expects an opening
            // bracket
            double lon = parser.doubleValue();
            parser.nextToken();
            if (!parser.currentToken().equals(XContentParser.Token.VALUE_NUMBER)) {
                throw new ElasticsearchParseException("geo point parsing: expected second number but got [{}] instead", parser.currentToken());
            }
            double lat = parser.doubleValue();
            GeoPoint point = new GeoPoint();
            point.reset(lat, lon);
            geoPoints.add(point);
        } else {
            GeoPoint point = new GeoPoint();
            GeoUtils.parseGeoPoint(parser, point);
            geoPoints.add(point);
        }
    }
}
Also used : GeoPoint(org.elasticsearch.common.geo.GeoPoint) ElasticsearchParseException(org.elasticsearch.ElasticsearchParseException)

Example 23 with ElasticsearchParseException

use of org.elasticsearch.ElasticsearchParseException in project elasticsearch by elastic.

the class GeoDistanceSortBuilder method build.

@Override
public SortFieldAndFormat build(QueryShardContext context) throws IOException {
    final boolean indexCreatedBeforeV2_0 = context.indexVersionCreated().before(Version.V_2_0_0);
    // validation was not available prior to 2.x, so to support bwc percolation queries we only ignore_malformed
    // on 2.x created indexes
    GeoPoint[] localPoints = points.toArray(new GeoPoint[points.size()]);
    if (!indexCreatedBeforeV2_0 && !GeoValidationMethod.isIgnoreMalformed(validation)) {
        for (GeoPoint point : localPoints) {
            if (GeoUtils.isValidLatitude(point.lat()) == false) {
                throw new ElasticsearchParseException("illegal latitude value [{}] for [GeoDistanceSort] for field [{}].", point.lat(), fieldName);
            }
            if (GeoUtils.isValidLongitude(point.lon()) == false) {
                throw new ElasticsearchParseException("illegal longitude value [{}] for [GeoDistanceSort] for field [{}].", point.lon(), fieldName);
            }
        }
    }
    if (GeoValidationMethod.isCoerce(validation)) {
        for (GeoPoint point : localPoints) {
            GeoUtils.normalizePoint(point, true, true);
        }
    }
    boolean reverse = (order == SortOrder.DESC);
    final MultiValueMode finalSortMode;
    if (sortMode == null) {
        finalSortMode = reverse ? MultiValueMode.MAX : MultiValueMode.MIN;
    } else {
        finalSortMode = MultiValueMode.fromString(sortMode.toString());
    }
    MappedFieldType fieldType = context.fieldMapper(fieldName);
    if (fieldType == null) {
        throw new IllegalArgumentException("failed to find mapper for [" + fieldName + "] for geo distance based sort");
    }
    final IndexGeoPointFieldData geoIndexFieldData = context.getForField(fieldType);
    final Nested nested = resolveNested(context, nestedPath, nestedFilter);
    if (// only works with 5.x geo_point
    geoIndexFieldData.getClass() == LatLonPointDVIndexFieldData.class && nested == null && // LatLonDocValuesField internally picks the closest point
    finalSortMode == MultiValueMode.MIN && unit == DistanceUnit.METERS && reverse == false && localPoints.length == 1) {
        return new SortFieldAndFormat(LatLonDocValuesField.newDistanceSort(fieldName, localPoints[0].lat(), localPoints[0].lon()), DocValueFormat.RAW);
    }
    IndexFieldData.XFieldComparatorSource geoDistanceComparatorSource = new IndexFieldData.XFieldComparatorSource() {

        @Override
        public SortField.Type reducedType() {
            return SortField.Type.DOUBLE;
        }

        @Override
        public FieldComparator<?> newComparator(String fieldname, int numHits, int sortPos, boolean reversed) {
            return new FieldComparator.DoubleComparator(numHits, null, null) {

                @Override
                protected NumericDocValues getNumericDocValues(LeafReaderContext context, String field) throws IOException {
                    final MultiGeoPointValues geoPointValues = geoIndexFieldData.load(context).getGeoPointValues();
                    final SortedNumericDoubleValues distanceValues = GeoUtils.distanceValues(geoDistance, unit, geoPointValues, localPoints);
                    final NumericDoubleValues selectedValues;
                    if (nested == null) {
                        selectedValues = finalSortMode.select(distanceValues, Double.POSITIVE_INFINITY);
                    } else {
                        final BitSet rootDocs = nested.rootDocs(context);
                        final DocIdSetIterator innerDocs = nested.innerDocs(context);
                        selectedValues = finalSortMode.select(distanceValues, Double.POSITIVE_INFINITY, rootDocs, innerDocs, context.reader().maxDoc());
                    }
                    return selectedValues.getRawDoubleValues();
                }
            };
        }
    };
    return new SortFieldAndFormat(new SortField(fieldName, geoDistanceComparatorSource, reverse), DocValueFormat.RAW);
}
Also used : IndexGeoPointFieldData(org.elasticsearch.index.fielddata.IndexGeoPointFieldData) Nested(org.elasticsearch.index.fielddata.IndexFieldData.XFieldComparatorSource.Nested) BitSet(org.apache.lucene.util.BitSet) SortField(org.apache.lucene.search.SortField) NumericDoubleValues(org.elasticsearch.index.fielddata.NumericDoubleValues) SortedNumericDoubleValues(org.elasticsearch.index.fielddata.SortedNumericDoubleValues) MultiValueMode(org.elasticsearch.search.MultiValueMode) GeoPoint(org.elasticsearch.common.geo.GeoPoint) LatLonPointDVIndexFieldData(org.elasticsearch.index.fielddata.plain.AbstractLatLonPointDVIndexFieldData.LatLonPointDVIndexFieldData) ElasticsearchParseException(org.elasticsearch.ElasticsearchParseException) MappedFieldType(org.elasticsearch.index.mapper.MappedFieldType) LeafReaderContext(org.apache.lucene.index.LeafReaderContext) LatLonPointDVIndexFieldData(org.elasticsearch.index.fielddata.plain.AbstractLatLonPointDVIndexFieldData.LatLonPointDVIndexFieldData) IndexFieldData(org.elasticsearch.index.fielddata.IndexFieldData) SortedNumericDoubleValues(org.elasticsearch.index.fielddata.SortedNumericDoubleValues) MultiGeoPointValues(org.elasticsearch.index.fielddata.MultiGeoPointValues) DocIdSetIterator(org.apache.lucene.search.DocIdSetIterator)

Example 24 with ElasticsearchParseException

use of org.elasticsearch.ElasticsearchParseException in project elasticsearch by elastic.

the class GeoUtils method parseGeoPoint.

/**
     * 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;
    NumberFormatException numberFormatException = 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:
                            try {
                                lat = parser.doubleValue(true);
                            } catch (NumberFormatException e) {
                                numberFormatException = e;
                            }
                            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:
                            try {
                                lon = parser.doubleValue(true);
                            } catch (NumberFormatException e) {
                                numberFormatException = e;
                            }
                            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 (numberFormatException != null) {
            throw new ElasticsearchParseException("[{}] and [{}] must be valid double values", numberFormatException, LATITUDE, LONGITUDE);
        } 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");
    }
}
Also used : ElasticsearchParseException(org.elasticsearch.ElasticsearchParseException)

Example 25 with ElasticsearchParseException

use of org.elasticsearch.ElasticsearchParseException in project elasticsearch by elastic.

the class CancelAllocationCommand method fromXContent.

public static CancelAllocationCommand 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 CancelAllocationCommand(index, shardId, nodeId, allowPrimary);
}
Also used : ElasticsearchParseException(org.elasticsearch.ElasticsearchParseException) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Aggregations

ElasticsearchParseException (org.elasticsearch.ElasticsearchParseException)81 XContentParser (org.elasticsearch.common.xcontent.XContentParser)29 HashMap (java.util.HashMap)25 ArrayList (java.util.ArrayList)12 IOException (java.io.IOException)10 Map (java.util.Map)9 Matchers.containsString (org.hamcrest.Matchers.containsString)6 List (java.util.List)5 ParsingException (org.elasticsearch.common.ParsingException)5 GeoPoint (org.elasticsearch.common.geo.GeoPoint)5 IndexMetaData (org.elasticsearch.cluster.metadata.IndexMetaData)4 Token (org.elasticsearch.common.xcontent.XContentParser.Token)4 HashSet (java.util.HashSet)3 PutPipelineRequest (org.elasticsearch.action.ingest.PutPipelineRequest)3 BytesReference (org.elasticsearch.common.bytes.BytesReference)3 XContentBuilder (org.elasticsearch.common.xcontent.XContentBuilder)3 Script (org.elasticsearch.script.Script)3 UncheckedIOException (java.io.UncheckedIOException)2 Set (java.util.Set)2 ParameterizedMessage (org.apache.logging.log4j.message.ParameterizedMessage)2