Geo queries 地理位置查询

Elasticsearch支持两种类型的地理数据:geo_point类型支持成对的纬度/经度,geo_shape类型支持点、线、圆、多边形、多个多边形等。
在这组的查询中:

  • geo_shape查询

查找要么相交,包含的,要么指定形状不相交的地理形状的文档。

查看Geo Shape Query

geo_shape 类型使用 Spatial4JJTS ,这两者都是可选的依赖项。 因此,必须将 Spatial4JJTS 添加到 classpath 中才能使用此类型:

  1. <dependency>
  2. <groupId>org.locationtech.spatial4j</groupId>
  3. <artifactId>spatial4j</artifactId>
  4. <version>0.6</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.vividsolutions</groupId>
  8. <artifactId>jts</artifactId>
  9. <version>1.13</version>
  10. <exclusions>
  11. <exclusion>
  12. <groupId>xerces</groupId>
  13. <artifactId>xercesImpl</artifactId>
  14. </exclusion>
  15. </exclusions>
  16. </dependency>
  1. // Import ShapeRelation and ShapeBuilder
  2. import org.elasticsearch.common.geo.ShapeRelation;
  3. import org.elasticsearch.common.geo.builders.ShapeBuilder;
  1. List<Coordinate> points = new ArrayList<>();
  2. points.add(new Coordinate(0, 0));
  3. points.add(new Coordinate(0, 10));
  4. points.add(new Coordinate(10, 10));
  5. points.add(new Coordinate(10, 0));
  6. points.add(new Coordinate(0, 0));
  7. QueryBuilder qb = geoShapeQuery(
  8. "pin.location", //field
  9. ShapeBuilders.newMultiPoint(points) //shape
  10. .relation(ShapeRelation.WITHIN); //relation 可以是 ShapeRelation.CONTAINS, ShapeRelation.WITHIN, ShapeRelation.INTERSECTS 或 ShapeRelation.DISJOINT
  1. // Using pre-indexed shapes
  2. QueryBuilder qb = geoShapeQuery(
  3. "pin.location", //field
  4. "DEU", //The ID of the document that containing the pre-indexed shape.
  5. "countries") //Index type where the pre-indexed shape is.
  6. .relation(ShapeRelation.WITHIN)) //relation
  7. .indexedShapeIndex("shapes") //Name of the index where the pre-indexed shape is. Defaults to shapes.
  8. .indexedShapePath("location"); //The field specified as path containing the pre-indexed shape. Defaults to shape.
  • geo_bounding_box 查询

查找落入指定的矩形地理点的文档。

查看Geo Bounding Box Query

  1. QueryBuilder qb = geoBoundingBoxQuery("pin.location") //field
  2. .setCorners(40.73, -74.1, //bounding box top left point
  3. 40.717, -73.99); //bounding box bottom right point
  • geo_distance 查询

查找在一个中心点指定范围内的地理点文档。

查看Geo Distance Query

  1. QueryBuilder qb = geoDistanceQuery("pin.location") //field
  2. .point(40, -70) //center point
  3. .distance(200, DistanceUnit.KILOMETERS); //distance from center point
  • geo_polygon 查询

查找指定多边形内地理点的文档。

查看Geo Polygon Query

  1. List<GeoPoint> points = new ArrayList<>(); //add your polygon of points a document should fall within
  2. points.add(new GeoPoint(40, -70));
  3. points.add(new GeoPoint(30, -80));
  4. points.add(new GeoPoint(20, -90));
  5. QueryBuilder qb =
  6. geoPolygonQuery("pin.location", points); //initialise the query with field and points