org.elasticsearch.common.geo.GeoPoint Java Examples
The following examples show how to use
org.elasticsearch.common.geo.GeoPoint.
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: DecayFunctionParser.java From Elasticsearch with Apache License 2.0 | 6 votes |
@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 File: DecayFunctionParser.java From Elasticsearch with Apache License 2.0 | 6 votes |
@Override protected String getDistanceString(LeafReaderContext ctx, int docId) { StringBuilder values = new StringBuilder(mode.name()); values.append(" of: ["); final MultiGeoPointValues geoPointValues = fieldData.load(ctx).getGeoPointValues(); geoPointValues.setDocument(docId); final int num = geoPointValues.count(); if (num > 0) { for (int i = 0; i < num; i++) { GeoPoint value = geoPointValues.valueAt(i); values.append("Math.max(arcDistance("); values.append(value).append("(=doc value),").append(origin).append("(=origin)) - ").append(offset).append("(=offset), 0)"); if (i != num - 1) { values.append(", "); } } } else { values.append("0.0"); } values.append("]"); return values.toString(); }
Example #3
Source File: GeoJsonParser.java From crate with Apache License 2.0 | 6 votes |
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 #4
Source File: InternalGeoBounds.java From Elasticsearch with Apache License 2.0 | 6 votes |
private BoundingBox resolveBoundingBox() { if (Double.isInfinite(top)) { return null; } else if (Double.isInfinite(posLeft)) { return new BoundingBox(new GeoPoint(top, negLeft), new GeoPoint(bottom, negRight)); } else if (Double.isInfinite(negLeft)) { return new BoundingBox(new GeoPoint(top, posLeft), new GeoPoint(bottom, posRight)); } else if (wrapLongitude) { double unwrappedWidth = posRight - negLeft; double wrappedWidth = (180 - posLeft) - (-180 - negRight); if (unwrappedWidth <= wrappedWidth) { return new BoundingBox(new GeoPoint(top, negLeft), new GeoPoint(bottom, posRight)); } else { return new BoundingBox(new GeoPoint(top, posLeft), new GeoPoint(bottom, negRight)); } } else { return new BoundingBox(new GeoPoint(top, negLeft), new GeoPoint(bottom, posRight)); } }
Example #5
Source File: GeoPointFieldMapper.java From Elasticsearch with Apache License 2.0 | 6 votes |
@Override protected void parse(ParseContext context, GeoPoint point, String geoHash) throws IOException { if (ignoreMalformed.value() == false) { if (point.lat() > 90.0 || point.lat() < -90.0) { throw new IllegalArgumentException("illegal latitude value [" + point.lat() + "] for " + name()); } if (point.lon() > 180.0 || point.lon() < -180) { throw new IllegalArgumentException("illegal longitude value [" + point.lon() + "] for " + name()); } } else { // LUCENE WATCH: This will be folded back into Lucene's GeoPointField GeoUtils.normalizePoint(point); } if (fieldType().indexOptions() != IndexOptions.NONE || fieldType().stored()) { context.doc().add(new GeoPointField(fieldType().names().indexName(), point.lon(), point.lat(), fieldType() )); } super.parse(context, point, geoHash); }
Example #6
Source File: AggregationContext.java From Elasticsearch with Apache License 2.0 | 6 votes |
/** * Return the original values source, before we apply `missing`. */ private <VS extends ValuesSource> VS originalValuesSource(ValuesSourceConfig<VS> config) throws IOException { if (config.fieldContext == null) { if (ValuesSource.Numeric.class.isAssignableFrom(config.valueSourceType)) { return (VS) numericScript(config); } if (ValuesSource.Bytes.class.isAssignableFrom(config.valueSourceType)) { return (VS) bytesScript(config); } throw new AggregationExecutionException("value source of type [" + config.valueSourceType.getSimpleName() + "] is not supported by scripts"); } if (ValuesSource.Numeric.class.isAssignableFrom(config.valueSourceType)) { return (VS) numericField(config); } if (ValuesSource.GeoPoint.class.isAssignableFrom(config.valueSourceType)) { return (VS) geoPointField(config); } // falling back to bytes values return (VS) bytesField(config); }
Example #7
Source File: InternalGeoBounds.java From Elasticsearch with Apache License 2.0 | 6 votes |
@Override public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException { GeoPoint topLeft = topLeft(); GeoPoint bottomRight = bottomRight(); if (topLeft != null) { builder.startObject("bounds"); builder.startObject("top_left"); builder.field("lat", topLeft.lat()); builder.field("lon", topLeft.lon()); builder.endObject(); builder.startObject("bottom_right"); builder.field("lat", bottomRight.lat()); builder.field("lon", bottomRight.lon()); builder.endObject(); builder.endObject(); } return builder; }
Example #8
Source File: ElasticsearchIndex.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
@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 #9
Source File: GeoHashGridParser.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override public void setDocument(int docId) { geoValues.setDocument(docId); resize(geoValues.count()); for (int i = 0; i < count(); ++i) { GeoPoint target = geoValues.valueAt(i); values[i] = GeoHashUtils.longEncode(target.getLon(), target.getLat(), precision); } sort(); }
Example #10
Source File: GeoHashGridParser.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override protected Aggregator doCreateInternal(final ValuesSource.GeoPoint valuesSource, AggregationContext aggregationContext, Aggregator parent, boolean collectsFromSingleBucket, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData) throws IOException { if (collectsFromSingleBucket == false) { return asMultiBucketAggregator(this, aggregationContext, parent); } CellIdSource cellIdSource = new CellIdSource(valuesSource, precision); return new GeoHashGridAggregator(name, factories, cellIdSource, requiredSize, shardSize, aggregationContext, parent, pipelineAggregators, metaData); }
Example #11
Source File: GeoUtils.java From elasticsearch-plugin-geoshape with MIT License | 5 votes |
public static List<GeoPoint> getBboxFromCoords(Coordinate[] coords) { GeoPoint topLeft = new GeoPoint( org.elasticsearch.common.geo.GeoUtils.normalizeLat(coords[0].y), org.elasticsearch.common.geo.GeoUtils.normalizeLon(coords[0].x) ); GeoPoint bottomRight = new GeoPoint( org.elasticsearch.common.geo.GeoUtils.normalizeLat(coords[2].y), org.elasticsearch.common.geo.GeoUtils.normalizeLon(coords[2].x) ); return Arrays.asList(topLeft, bottomRight); }
Example #12
Source File: GeoDistanceParser.java From Elasticsearch with Apache License 2.0 | 5 votes |
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 #13
Source File: InMemoryGeoBoundingBoxQuery.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override public boolean get(int doc) { values.setDocument(doc); final int length = values.count(); for (int i = 0; i < length; i++) { GeoPoint point = values.valueAt(i); if (((topLeft.lon() <= point.lon() || bottomRight.lon() >= point.lon())) && (topLeft.lat() >= point.lat() && bottomRight.lat() <= point.lat())) { return true; } } return false; }
Example #14
Source File: AggregationContext.java From Elasticsearch with Apache License 2.0 | 5 votes |
private ValuesSource.GeoPoint geoPointField(ValuesSourceConfig<?> config) throws IOException { if (!(config.fieldContext.indexFieldData() instanceof IndexGeoPointFieldData)) { throw new IllegalArgumentException("Expected geo_point type on field [" + config.fieldContext.field() + "], but got [" + config.fieldContext.fieldType().typeName() + "]"); } return new ValuesSource.GeoPoint.Fielddata((IndexGeoPointFieldData) config.fieldContext.indexFieldData()); }
Example #15
Source File: GeoPointFieldMapperLegacy.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override public BytesRef binaryValue() { final byte[] bytes = new byte[points.size() * 16]; int off = 0; for (Iterator<ObjectCursor<GeoPoint>> it = points.iterator(); it.hasNext(); ) { final GeoPoint point = it.next().value; ByteUtils.writeDoubleLE(point.getLat(), bytes, off); ByteUtils.writeDoubleLE(point.getLon(), bytes, off + 8); off += 16; } return new BytesRef(bytes); }
Example #16
Source File: LuceneQueryBuilder.java From Elasticsearch with Apache License 2.0 | 5 votes |
private Query getQuery(Function inner, Context context) { RefLiteralPair innerPair = new RefLiteralPair(inner); if (!innerPair.isValid()) { return null; } if (innerPair.reference().valueType().equals(DataTypes.GEO_SHAPE)) { // we have within('POINT(0 0)', shape_column) return genericFunctionFilter(inner, context); } GeoPointFieldMapper.GeoPointFieldType geoPointFieldType = getGeoPointFieldType( innerPair.reference().ident().columnIdent().fqn(), context.mapperService); Map<String, Object> geoJSON = (Map<String, Object>) innerPair.input().value(); Shape shape = GeoJSONUtils.map2Shape(geoJSON); Geometry geometry = JtsSpatialContext.GEO.getGeometryFrom(shape); IndexGeoPointFieldData fieldData = context.fieldDataService.getForField(geoPointFieldType); if (geometry.isRectangle()) { Rectangle boundingBox = shape.getBoundingBox(); return new InMemoryGeoBoundingBoxQuery( new GeoPoint(boundingBox.getMaxY(), boundingBox.getMinX()), new GeoPoint(boundingBox.getMinY(), boundingBox.getMaxX()), fieldData ); } else { Coordinate[] coordinates = geometry.getCoordinates(); GeoPoint[] points = new GeoPoint[coordinates.length]; for (int i = 0; i < coordinates.length; i++) { Coordinate coordinate = coordinates[i]; points[i] = new GeoPoint(coordinate.y, coordinate.x); } return new GeoPolygonQuery(fieldData, points); } }
Example #17
Source File: StatisticsLocationUtil.java From arctic-sea with Apache License 2.0 | 5 votes |
private Map<String, Object> ip2SpatialData(InetAddress ip) { if (!enabled) { return null; } if (reader == null) { LOG.warn("Location database is not initialized. Exiting."); return null; } try { Map<String, Object> holder = new HashMap<>(3); if (dbType == LocationDatabaseType.COUNTRY) { Country country = reader.country(ip).getCountry(); holder.put(ObjectEsParameterFactory.GEOLOC_COUNTRY_CODE.getName(), country.getIsoCode()); } else { CityResponse city = reader.city(ip); Location loc = city.getLocation(); holder.put(ObjectEsParameterFactory.GEOLOC_COUNTRY_CODE.getName(), city.getCountry().getIsoCode()); holder.put(ObjectEsParameterFactory.GEOLOC_CITY_NAME.getName(), city.getCity().getName()); holder.put(ObjectEsParameterFactory.GEOLOC_GEO_POINT.getName(), new GeoPoint(loc.getLatitude(), loc.getLongitude())); } return holder; } catch (Throwable e) { LOG.warn("Can't convert IP to GeoIp", e); } return null; }
Example #18
Source File: GeoPointArrayLegacyAtomicFieldData.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override public MultiGeoPointValues getGeoPointValues() { final GeoPoint point = new GeoPoint(); final GeoPointValues values = new GeoPointValues() { @Override public GeoPoint get(int docID) { if (set == null || set.get(docID)) { return point.reset(lat.get(docID), lon.get(docID)); } return point.reset(Double.NaN, Double.NaN); } }; return FieldData.singleton(values, set); }
Example #19
Source File: DecayFunctionParser.java From Elasticsearch with Apache License 2.0 | 5 votes |
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 #20
Source File: GeoWKTParser.java From crate with Apache License 2.0 | 5 votes |
private static PointBuilder parsePoint(StreamTokenizer stream, final boolean ignoreZValue) throws IOException, ElasticsearchParseException { if (nextEmptyOrOpen(stream).equals(EMPTY)) { return null; } PointBuilder pt = new PointBuilder(nextNumber(stream), nextNumber(stream)); if (isNumberNext(stream) == true) { GeoPoint.assertZValue(ignoreZValue, nextNumber(stream)); } nextCloser(stream); return pt; }
Example #21
Source File: InMemoryGeoBoundingBoxQuery.java From Elasticsearch with Apache License 2.0 | 5 votes |
@Override public boolean get(int doc) { values.setDocument(doc); final int length = values.count(); for (int i = 0; i < length; i++) { GeoPoint point = values.valueAt(i); if (topLeft.lon() <= point.lon() && bottomRight.lon() >= point.lon() && topLeft.lat() >= point.lat() && bottomRight.lat() <= point.lat()) { return true; } } return false; }
Example #22
Source File: InternalGeoPointClustering.java From elasticsearch-aggregation-geoclustering with Apache License 2.0 | 5 votes |
/** * Read from a stream. */ private Bucket(StreamInput in) throws IOException { geohashAsLong = in.readLong(); docCount = in.readVLong(); final long hash = in.readLong(); centroid = new GeoPoint(decodeLatitude(hash), decodeLongitude(hash)); visited = in.readBoolean(); aggregations = new InternalAggregations(in); }
Example #23
Source File: ElasticsearchDocumentDistance.java From rdf4j with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 #24
Source File: ScriptDocValues.java From Elasticsearch with Apache License 2.0 | 5 votes |
public GeoPoint getValue() { int numValues = values.count(); if (numValues == 0) { return null; } return values.valueAt(0); }
Example #25
Source File: ScriptDocValues.java From Elasticsearch with Apache License 2.0 | 5 votes |
public double[] getLats() { List<GeoPoint> points = getValues(); double[] lats = new double[points.size()]; for (int i = 0; i < points.size(); i++) { lats[i] = points.get(i).lat(); } return lats; }
Example #26
Source File: GeoPointClusteringAggregator.java From elasticsearch-aggregation-geoclustering with Apache License 2.0 | 5 votes |
GeoPointClusteringAggregator( String name, AggregatorFactories factories, ValuesSource.GeoPoint valuesSource, int precision, double radius, double ratio, int requiredSize, int shardSize, SearchContext aggregationContext, Aggregator parent, List<PipelineAggregator> pipelineAggregators, Map<String, Object> metaData ) throws IOException { super(name, factories, aggregationContext, parent, pipelineAggregators, metaData); this.valuesSource = valuesSource; this.precision = precision; this.radius = radius; this.ratio = ratio; this.requiredSize = requiredSize; this.shardSize = shardSize; bucketOrds = new LongHash(1, aggregationContext.bigArrays()); centroids = context.bigArrays().newObjectArray(1); }
Example #27
Source File: BaseGeoPointFieldMapper.java From Elasticsearch with Apache License 2.0 | 5 votes |
protected void parse(ParseContext context, GeoPoint point, String geoHash) throws IOException { if (fieldType().isGeoHashEnabled()) { if (geoHash == null) { geoHash = GeoHashUtils.stringEncode(point.lon(), point.lat()); } addGeoHashField(context, geoHash); } if (fieldType().isLatLonEnabled()) { latMapper.parse(context.createExternalValueContext(point.lat())); lonMapper.parse(context.createExternalValueContext(point.lon())); } multiFields.parse(this, context.createExternalValueContext(point)); }
Example #28
Source File: GeoPointFieldMapper.java From crate with Apache License 2.0 | 5 votes |
/** * 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 #29
Source File: ScriptDocValues.java From Elasticsearch with Apache License 2.0 | 5 votes |
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 #30
Source File: ScriptDocValues.java From Elasticsearch with Apache License 2.0 | 5 votes |
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); }