下面列出了org.apache.lucene.search.ConstantScoreWeight#org.elasticsearch.common.geo.GeoPoint 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
@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;
}
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));
}
}
/**
* 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);
}
@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);
}
@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();
}
@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);
}
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;
}
@Override
public AtomicQuery parse(ElasticsearchParser.GeoPolygonClauseContext expression) {
String field=expression.ID().getText();
List<GeoPoint> points=new ArrayList<>(expression.point().size());
for(ElasticsearchParser.PointContext pointContext:expression.point()){
points.add(GeoUtils.parseGeoPoint(pointContext));
}
return new AtomicQuery(QueryBuilders.geoPolygonQuery(field,points));
}
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;
}
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);
}
}
@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);
}
/**
* Parses geopoint represented as an object or an array, ignores malformed geopoints if needed
*/
private void parseGeoPointIgnoringMalformed(ParseContext context, GeoPoint sparse) throws IOException {
try {
parse(context, GeoUtils.parseGeoPoint(context.parser(), sparse));
} catch (ElasticsearchParseException e) {
if (ignoreMalformed.value() == false) {
throw e;
}
context.addIgnoredField(fieldType.name());
}
}
@Override
public GeoPoint topLeft() {
BoundingBox boundingBox = resolveBoundingBox();
if (boundingBox == null) {
return null;
} else {
return boundingBox.topLeft();
}
}
public InternalGeoCentroid(String name, GeoPoint centroid, long count, List<PipelineAggregator>
pipelineAggregators, Map<String, Object> metaData) {
super(name, pipelineAggregators, metaData);
this.centroid = centroid;
assert count >= 0;
this.count = count;
}
@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);
}
@Override
protected void doReadFrom(StreamInput in) throws IOException {
count = in.readVLong();
if (in.readBoolean()) {
centroid = GeoPoint.fromIndexLong(in.readLong());
} else {
centroid = null;
}
}
protected GeoCentroidAggregator(String name, AggregationContext aggregationContext, Aggregator parent,
ValuesSource.GeoPoint valuesSource, List<PipelineAggregator> pipelineAggregators,
Map<String, Object> metaData) throws IOException {
super(name, aggregationContext, parent, pipelineAggregators, metaData);
this.valuesSource = valuesSource;
if (valuesSource != null) {
final BigArrays bigArrays = context.bigArrays();
centroids = bigArrays.newLongArray(1, true);
counts = bigArrays.newLongArray(1, true);
}
}
@Override
public LeafBucketCollector getLeafCollector(LeafReaderContext ctx, LeafBucketCollector sub) throws IOException {
if (valuesSource == null) {
return LeafBucketCollector.NO_OP_COLLECTOR;
}
final BigArrays bigArrays = context.bigArrays();
final MultiGeoPointValues values = valuesSource.geoPointValues(ctx);
return new LeafBucketCollectorBase(sub, values) {
@Override
public void collect(int doc, long bucket) throws IOException {
centroids = bigArrays.grow(centroids, bucket + 1);
counts = bigArrays.grow(counts, bucket + 1);
values.setDocument(doc);
final int valueCount = values.count();
if (valueCount > 0) {
double[] pt = new double[2];
// get the previously accumulated number of counts
long prevCounts = counts.get(bucket);
// increment by the number of points for this document
counts.increment(bucket, valueCount);
// get the previous GeoPoint if a moving avg was computed
if (prevCounts > 0) {
final GeoPoint centroid = GeoPoint.fromIndexLong(centroids.get(bucket));
pt[0] = centroid.lon();
pt[1] = centroid.lat();
}
// update the moving average
for (int i = 0; i < valueCount; ++i) {
GeoPoint value = values.valueAt(i);
pt[0] = pt[0] + (value.getLon() - pt[0]) / ++prevCounts;
pt[1] = pt[1] + (value.getLat() - pt[1]) / prevCounts;
}
centroids.set(bucket, GeoEncodingUtils.mortonHash(pt[0], pt[1]));
}
}
};
}
@Override
public InternalAggregation buildAggregation(long bucket) {
if (valuesSource == null || bucket >= centroids.size()) {
return buildEmptyAggregation();
}
final long bucketCount = counts.get(bucket);
final GeoPoint bucketCentroid = (bucketCount > 0) ? GeoPoint.fromIndexLong(centroids.get(bucket)) :
new GeoPoint(Double.NaN, Double.NaN);
return new InternalGeoCentroid(name, bucketCentroid , bucketCount, pipelineAggregators(), metaData());
}
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());
}
@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);
});
}
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;
}
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);
}
@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);
}
@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();
}
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);
}
@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;
}
@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;
}
/**
* 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);
}