Java Code Examples for org.elasticsearch.common.unit.DistanceUnit

The following examples show how to use org.elasticsearch.common.unit.DistanceUnit. 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: Elasticsearch   Author: baidu   File: DecayFunctionParser.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected NumericDoubleValues distance(LeafReaderContext context) {
    final MultiGeoPointValues geoPointValues = fieldData.load(context).getGeoPointValues();
    return mode.select(new MultiValueMode.UnsortedNumericDoubleValues() {
        @Override
        public int count() {
            return geoPointValues.count();
        }

        @Override
        public void setDocument(int docId) {
            geoPointValues.setDocument(docId);
        }

        @Override
        public double valueAt(int index) {
            GeoPoint other = geoPointValues.valueAt(index);
            return Math.max(0.0d, distFunction.calculate(origin.lat(), origin.lon(), other.lat(), other.lon(), DistanceUnit.METERS) - offset);
        }
    }, 0.0);
}
 
Example #2
Source Project: rdf4j   Author: eclipse   File: ElasticsearchDocumentDistance.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public double getDistance() {
	String geohash = (String) ((ElasticsearchDocument) getDocument()).getSource().get(geoPointField);
	GeoPoint dstPoint = GeoPoint.fromGeohash(geohash);

	double unitDist = GeoDistance.ARC.calculate(srcPoint.getLat(), srcPoint.getLon(), dstPoint.getLat(),
			dstPoint.getLon(), unit);
	double distance;
	if (GEOF.UOM_METRE.equals(units)) {
		distance = unit.toMeters(unitDist);
	} else if (GEOF.UOM_DEGREE.equals(units)) {
		distance = unitDist / unit.getDistancePerDegree();
	} else if (GEOF.UOM_RADIAN.equals(units)) {
		distance = DistanceUtils.dist2Radians(unit.convert(unitDist, DistanceUnit.KILOMETERS),
				DistanceUtils.EARTH_MEAN_RADIUS_KM);
	} else if (GEOF.UOM_UNITY.equals(units)) {
		distance = unit.convert(unitDist, DistanceUnit.KILOMETERS) / (Math.PI * DistanceUtils.EARTH_MEAN_RADIUS_KM);
	} else {
		throw new UnsupportedOperationException("Unsupported units: " + units);
	}
	return distance;
}
 
Example #3
Source Project: crate   Author: crate   File: GeoSettingsApplier.java    License: Apache License 2.0 6 votes vote down vote up
private static void applyPrecision(Map<String, Object> mapping, Settings geoSettings) {
    String precision = geoSettings.get("precision");
    if (precision == null) {
        Integer treeLevels = geoSettings.getAsInt("tree_levels", null);
        if (treeLevels != null) {
            mapping.put("tree_levels", treeLevels);
        }
    } else {
        try {
            DistanceUnit.parse(precision, DistanceUnit.DEFAULT, DistanceUnit.DEFAULT);
        } catch (IllegalArgumentException e) {
            throw new IllegalArgumentException(
                String.format(Locale.ENGLISH, "Value '%s' of setting precision is not a valid distance unit", precision)
            );
        }
        mapping.put("precision", precision);
    }
}
 
Example #4
Source Project: Elasticsearch   Author: baidu   File: DistanceFunction.java    License: Apache License 2.0 5 votes vote down vote up
public Double evaluate(Input arg1, Input arg2) {
    Object value1 = arg1.value();
    if (value1 == null) {
        return null;
    }
    Object value2 = arg2.value();
    if (value2 == null) {
        return null;
    }
    double sourceLongitude;
    double sourceLatitude;
    double targetLongitude;
    double targetLatitude;

     // need to handle list also - because e.g. ESSearchTask returns geo_points as list
    if (value1 instanceof List) {
        sourceLongitude = (Double)((List) value1).get(0);
        sourceLatitude = (Double)((List) value1).get(1);
    } else {
        sourceLongitude = ((Double[]) value1)[0];
        sourceLatitude = ((Double[]) value1)[1];
    }
    if (value2 instanceof List) {
        targetLongitude = (Double)((List) value2).get(0);
        targetLatitude = (Double)((List) value2).get(1);
    } else {
        targetLongitude = ((Double[]) value2)[0];
        targetLatitude = ((Double[]) value2)[1];
    }
    return GeoDistance.SLOPPY_ARC.calculate(
            sourceLatitude, sourceLongitude, targetLatitude, targetLongitude, DistanceUnit.METERS);
}
 
Example #5
Source Project: Elasticsearch   Author: baidu   File: GeoDistanceParser.java    License: Apache License 2.0 5 votes vote down vote up
public GeoDistanceFactory(String name, ValuesSourceConfig<ValuesSource.GeoPoint> valueSourceConfig,
                          InternalRange.Factory rangeFactory, GeoPoint origin, DistanceUnit unit, GeoDistance distanceType,
                          List<RangeAggregator.Range> ranges, boolean keyed) {
    super(name, rangeFactory.type(), valueSourceConfig);
    this.origin = origin;
    this.unit = unit;
    this.distanceType = distanceType;
    this.rangeFactory = rangeFactory;
    this.ranges = ranges;
    this.keyed = keyed;
}
 
Example #6
Source Project: Elasticsearch   Author: baidu   File: GeoDistanceParser.java    License: Apache License 2.0 5 votes vote down vote up
public DistanceSource(ValuesSource.GeoPoint source, GeoDistance distanceType, org.elasticsearch.common.geo.GeoPoint origin, DistanceUnit unit) {
    this.source = source;
    // even if the geo points are unique, there's no guarantee the distances are
    this.distanceType = distanceType;
    this.unit = unit;
    this.origin = origin;
}
 
Example #7
Source Project: Elasticsearch   Author: baidu   File: DecayFunctionParser.java    License: 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 Project: Elasticsearch   Author: baidu   File: ScriptDocValues.java    License: Apache License 2.0 5 votes vote down vote up
public double factorDistanceWithDefault(double lat, double lon, double defaultValue) {
    if (isEmpty()) {
        return defaultValue;
    }
    GeoPoint point = getValue();
    return GeoDistance.FACTOR.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT);
}
 
Example #9
Source Project: Elasticsearch   Author: baidu   File: ScriptDocValues.java    License: Apache License 2.0 5 votes vote down vote up
public double arcDistanceWithDefault(double lat, double lon, double defaultValue) {
    if (isEmpty()) {
        return defaultValue;
    }
    GeoPoint point = getValue();
    return GeoDistance.ARC.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT);
}
 
Example #10
Source Project: Elasticsearch   Author: baidu   File: ScriptDocValues.java    License: Apache License 2.0 5 votes vote down vote up
public double arcDistanceInKmWithDefault(double lat, double lon, double defaultValue) {
    if (isEmpty()) {
        return defaultValue;
    }
    GeoPoint point = getValue();
    return GeoDistance.ARC.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.KILOMETERS);
}
 
Example #11
Source Project: Elasticsearch   Author: baidu   File: ScriptDocValues.java    License: Apache License 2.0 5 votes vote down vote up
public double arcDistanceInMilesWithDefault(double lat, double lon, double defaultValue) {
    if (isEmpty()) {
        return defaultValue;
    }
    GeoPoint point = getValue();
    return GeoDistance.ARC.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.MILES);
}
 
Example #12
Source Project: Elasticsearch   Author: baidu   File: ScriptDocValues.java    License: Apache License 2.0 5 votes vote down vote up
public double distanceWithDefault(double lat, double lon, double defaultValue) {
    if (isEmpty()) {
        return defaultValue;
    }
    GeoPoint point = getValue();
    return GeoDistance.PLANE.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT);
}
 
Example #13
Source Project: Elasticsearch   Author: baidu   File: ScriptDocValues.java    License: Apache License 2.0 5 votes vote down vote up
public double distanceInKmWithDefault(double lat, double lon, double defaultValue) {
    if (isEmpty()) {
        return defaultValue;
    }
    GeoPoint point = getValue();
    return GeoDistance.PLANE.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.KILOMETERS);
}
 
Example #14
Source Project: Elasticsearch   Author: baidu   File: ScriptDocValues.java    License: Apache License 2.0 5 votes vote down vote up
public double distanceInMilesWithDefault(double lat, double lon, double defaultValue) {
    if (isEmpty()) {
        return defaultValue;
    }
    GeoPoint point = getValue();
    return GeoDistance.PLANE.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.MILES);
}
 
Example #15
Source Project: Elasticsearch   Author: baidu   File: GeoShapeFieldMapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
    Builder builder = geoShapeField(name);
    for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) {
        Map.Entry<String, Object> entry = iterator.next();
        String fieldName = Strings.toUnderscoreCase(entry.getKey());
        Object fieldNode = entry.getValue();
        if (Names.TREE.equals(fieldName)) {
            builder.fieldType().setTree(fieldNode.toString());
            iterator.remove();
        } else if (Names.TREE_LEVELS.equals(fieldName)) {
            builder.fieldType().setTreeLevels(Integer.parseInt(fieldNode.toString()));
            iterator.remove();
        } else if (Names.TREE_PRESISION.equals(fieldName)) {
            builder.fieldType().setPrecisionInMeters(DistanceUnit.parse(fieldNode.toString(), DistanceUnit.DEFAULT, DistanceUnit.DEFAULT));
            iterator.remove();
        } else if (Names.DISTANCE_ERROR_PCT.equals(fieldName)) {
            builder.fieldType().setDistanceErrorPct(Double.parseDouble(fieldNode.toString()));
            iterator.remove();
        } else if (Names.ORIENTATION.equals(fieldName)) {
            builder.fieldType().setOrientation(ShapeBuilder.orientationFromString(fieldNode.toString()));
            iterator.remove();
        } else if (Names.STRATEGY.equals(fieldName)) {
            builder.fieldType().setStrategyName(fieldNode.toString());
            iterator.remove();
        } else if (Names.COERCE.equals(fieldName)) {
            builder.coerce(nodeBooleanValue(fieldNode));
            iterator.remove();
        } else if (Names.STRATEGY_POINTS_ONLY.equals(fieldName)
            && builder.fieldType().strategyName.equals(SpatialStrategy.TERM.getStrategyName()) == false) {
            builder.fieldType().setPointsOnly(XContentMapValues.nodeBooleanValue(fieldNode));
            iterator.remove();
        }
    }
    return builder;
}
 
Example #16
Source Project: Elasticsearch   Author: baidu   File: GeoShapeFieldMapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException {
    builder.field("type", contentType());

    if (includeDefaults || fieldType().tree().equals(Defaults.TREE) == false) {
        builder.field(Names.TREE, fieldType().tree());
    }
    if (includeDefaults || fieldType().treeLevels() != 0) {
        builder.field(Names.TREE_LEVELS, fieldType().treeLevels());
    }
    if (includeDefaults || fieldType().precisionInMeters() != -1) {
        builder.field(Names.TREE_PRESISION, DistanceUnit.METERS.toString(fieldType().precisionInMeters()));
    }
    if (includeDefaults || fieldType().strategyName() != Defaults.STRATEGY) {
        builder.field(Names.STRATEGY, fieldType().strategyName());
    }
    if (includeDefaults || fieldType().distanceErrorPct() != fieldType().defaultDistanceErrorPct) {
        builder.field(Names.DISTANCE_ERROR_PCT, fieldType().distanceErrorPct());
    }
    if (includeDefaults || fieldType().orientation() != Defaults.ORIENTATION) {
        builder.field(Names.ORIENTATION, fieldType().orientation());
    }
    if (includeDefaults || fieldType().pointsOnly() != GeoShapeFieldMapper.Defaults.POINTS_ONLY) {
        builder.field(Names.STRATEGY_POINTS_ONLY, fieldType().pointsOnly());
    }
    if (includeDefaults || coerce.explicit()) {
        builder.field("coerce", coerce.value());
    }
}
 
Example #17
Source Project: Elasticsearch   Author: baidu   File: GeoPointFieldMapperLegacy.java    License: Apache License 2.0 5 votes vote down vote up
/** Get an instance based on the expected precision. Here are examples of the number of required bytes per value depending on the
 *  expected precision:<ul>
 *  <li>1km: 4 bytes</li>
 *  <li>3m: 6 bytes</li>
 *  <li>1m: 8 bytes</li>
 *  <li>1cm: 8 bytes</li>
 *  <li>1mm: 10 bytes</li></ul> */
public static final Encoding of(DistanceUnit.Distance precision) {
    for (Encoding encoding : INSTANCES) {
        if (encoding != null && encoding.precision().compareTo(precision) <= 0) {
            return encoding;
        }
    }
    return INSTANCES[MAX_NUM_BYTES];
}
 
Example #18
Source Project: rdf4j   Author: eclipse   File: ElasticsearchDocumentDistance.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public ElasticsearchDocumentDistance(SearchHit hit,
		Function<? super String, ? extends SpatialContext> geoContextMapper, String geoPointField, IRI units,
		GeoPoint srcPoint, DistanceUnit unit) {
	super(hit, geoContextMapper);
	this.geoPointField = geoPointField;
	this.units = units;
	this.srcPoint = srcPoint;
	this.unit = unit;
}
 
Example #19
Source Project: rdf4j   Author: eclipse   File: ElasticsearchIndex.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
protected Iterable<? extends DocumentDistance> geoQuery(final IRI geoProperty, Point p, final IRI units,
		double distance, String distanceVar, Var contextVar) throws MalformedQueryException, IOException {
	double unitDist;
	final DistanceUnit unit;
	if (GEOF.UOM_METRE.equals(units)) {
		unit = DistanceUnit.METERS;
		unitDist = distance;
	} else if (GEOF.UOM_DEGREE.equals(units)) {
		unit = DistanceUnit.KILOMETERS;
		unitDist = unit.getDistancePerDegree() * distance;
	} else if (GEOF.UOM_RADIAN.equals(units)) {
		unit = DistanceUnit.KILOMETERS;
		unitDist = DistanceUtils.radians2Dist(distance, DistanceUtils.EARTH_MEAN_RADIUS_KM);
	} else if (GEOF.UOM_UNITY.equals(units)) {
		unit = DistanceUnit.KILOMETERS;
		unitDist = distance * Math.PI * DistanceUtils.EARTH_MEAN_RADIUS_KM;
	} else {
		throw new MalformedQueryException("Unsupported units: " + units);
	}

	double lat = p.getY();
	double lon = p.getX();
	final String fieldName = toGeoPointFieldName(SearchFields.getPropertyField(geoProperty));
	QueryBuilder qb = QueryBuilders.functionScoreQuery(
			QueryBuilders.geoDistanceQuery(fieldName).point(lat, lon).distance(unitDist, unit),
			ScoreFunctionBuilders.linearDecayFunction(fieldName, GeohashUtils.encodeLatLon(lat, lon),
					new DistanceUnit.Distance(unitDist, unit).toString()));
	if (contextVar != null) {
		qb = addContextTerm(qb, (Resource) contextVar.getValue());
	}

	SearchRequestBuilder request = client.prepareSearch();
	SearchHits hits = search(request, qb);
	final GeoPoint srcPoint = new GeoPoint(lat, lon);
	return Iterables.transform(hits, (Function<SearchHit, DocumentDistance>) hit -> {
		return new ElasticsearchDocumentDistance(hit, geoContextMapper, fieldName, units, srcPoint, unit);
	});
}
 
Example #20
Source Project: Elasticsearch   Author: baidu   File: GeoDistanceParser.java    License: 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 #21
Source Project: Elasticsearch   Author: baidu   File: GeohashCellQuery.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public Query parse(QueryParseContext parseContext) throws IOException, QueryParsingException {
    XContentParser parser = parseContext.parser();

    String fieldName = null;
    String geohash = null;
    int levels = -1;
    boolean neighbors = false;


    XContentParser.Token token;
    if ((token = parser.currentToken()) != Token.START_OBJECT) {
        throw new ElasticsearchParseException("failed to parse [{}] query. expected an object but found [{}] instead", NAME, token);
    }

    while ((token = parser.nextToken()) != Token.END_OBJECT) {
        if (token == Token.FIELD_NAME) {
            String field = parser.currentName();

            if (parseContext.isDeprecatedSetting(field)) {
                // skip
            } else if (PRECISION.equals(field)) {
                token = parser.nextToken();
                if(token == Token.VALUE_NUMBER) {
                    levels = parser.intValue();
                } else if(token == Token.VALUE_STRING) {
                    double meters = DistanceUnit.parse(parser.text(), DistanceUnit.DEFAULT, DistanceUnit.METERS);
                    levels = GeoUtils.geoHashLevelsForPrecision(meters);
                }
            } else if (NEIGHBORS.equals(field)) {
                parser.nextToken();
                neighbors = parser.booleanValue();
            } else {
                fieldName = field;
                token = parser.nextToken();
                if(token == Token.VALUE_STRING) {
                    // A string indicates either a gehash or a lat/lon string
                    String location = parser.text();
                    if(location.indexOf(",")>0) {
                        geohash = GeoUtils.parseGeoPoint(parser).geohash();
                    } else {
                        geohash = location;
                    }
                } else {
                    geohash = GeoUtils.parseGeoPoint(parser).geohash();
                }
            }
        } else {
            throw new ElasticsearchParseException("failed to parse [{}] query. unexpected token [{}]", NAME, token);
        }
    }

    if (geohash == null) {
        throw new QueryParsingException(parseContext, "failed to parse [{}] query. missing geohash value", NAME);
    }

    MappedFieldType fieldType = parseContext.fieldMapper(fieldName);
    if (fieldType == null) {
        throw new QueryParsingException(parseContext, "failed to parse [{}] query. missing [{}] field [{}]", NAME, BaseGeoPointFieldMapper.CONTENT_TYPE, fieldName);
    }

    if (!(fieldType instanceof BaseGeoPointFieldMapper.GeoPointFieldType)) {
        throw new QueryParsingException(parseContext, "failed to parse [{}] query. field [{}] is not a geo_point field", NAME, fieldName);
    }

    BaseGeoPointFieldMapper.GeoPointFieldType geoFieldType = ((BaseGeoPointFieldMapper.GeoPointFieldType) fieldType);
    if (!geoFieldType.isGeoHashPrefixEnabled()) {
        throw new QueryParsingException(parseContext, "failed to parse [{}] query. [geohash_prefix] is not enabled for field [{}]", NAME, fieldName);
    }

    if(levels > 0) {
        int len = Math.min(levels, geohash.length());
        geohash = geohash.substring(0, len);
    }

    Query filter;
    if (neighbors) {
        filter = create(parseContext, geoFieldType, geohash, GeoHashUtils.addNeighbors(geohash, new ArrayList<CharSequence>(8)));
    } else {
        filter = create(parseContext, geoFieldType, geohash, null);
    }

    return filter;
}
 
Example #22
Source Project: Elasticsearch   Author: baidu   File: ScriptDocValues.java    License: Apache License 2.0 4 votes vote down vote up
public double factorDistance(double lat, double lon) {
    GeoPoint point = getValue();
    return GeoDistance.FACTOR.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT);
}
 
Example #23
Source Project: Elasticsearch   Author: baidu   File: ScriptDocValues.java    License: Apache License 2.0 4 votes vote down vote up
public double factorDistance02(double lat, double lon) {
    GeoPoint point = getValue();
    return GeoDistance.FACTOR.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT) + 1;
}
 
Example #24
Source Project: Elasticsearch   Author: baidu   File: ScriptDocValues.java    License: Apache License 2.0 4 votes vote down vote up
public double factorDistance13(double lat, double lon) {
    GeoPoint point = getValue();
    return GeoDistance.FACTOR.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT) + 2;
}
 
Example #25
Source Project: Elasticsearch   Author: baidu   File: ScriptDocValues.java    License: Apache License 2.0 4 votes vote down vote up
public double arcDistance(double lat, double lon) {
    GeoPoint point = getValue();
    return GeoDistance.ARC.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT);
}
 
Example #26
Source Project: Elasticsearch   Author: baidu   File: ScriptDocValues.java    License: Apache License 2.0 4 votes vote down vote up
public double arcDistanceInKm(double lat, double lon) {
    GeoPoint point = getValue();
    return GeoDistance.ARC.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.KILOMETERS);
}
 
Example #27
Source Project: Elasticsearch   Author: baidu   File: ScriptDocValues.java    License: Apache License 2.0 4 votes vote down vote up
public double arcDistanceInMiles(double lat, double lon) {
    GeoPoint point = getValue();
    return GeoDistance.ARC.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.MILES);
}
 
Example #28
Source Project: Elasticsearch   Author: baidu   File: ScriptDocValues.java    License: Apache License 2.0 4 votes vote down vote up
public double distance(double lat, double lon) {
    GeoPoint point = getValue();
    return GeoDistance.PLANE.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.DEFAULT);
}
 
Example #29
Source Project: Elasticsearch   Author: baidu   File: ScriptDocValues.java    License: Apache License 2.0 4 votes vote down vote up
public double distanceInKm(double lat, double lon) {
    GeoPoint point = getValue();
    return GeoDistance.PLANE.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.KILOMETERS);
}
 
Example #30
Source Project: Elasticsearch   Author: baidu   File: ScriptDocValues.java    License: Apache License 2.0 4 votes vote down vote up
public double distanceInMiles(double lat, double lon) {
    GeoPoint point = getValue();
    return GeoDistance.PLANE.calculate(point.lat(), point.lon(), lat, lon, DistanceUnit.MILES);
}