阅读量:1
目录
开发版本详见:Elasticsearch-经纬度查询(8.x-半径查询)_es经纬度范围查询-CSDN博客
一、字段设计
PUT /aoi_points { "mappings": { "properties": { "location": { "type": "geo_shape" } } } }
aoi_points
是索引名称,location
是字段名称,它将存储地理形状数据
二、数据录入
POST /aoi_points/_doc { "location": { "type": "point", "coordinates": [-74.0060, 40.7128] } }
三、查询语句
GET /aoi_points/_search { "query": { "bool": { "filter": { "geo_shape": { "location": { "shape": { "type": "polygon", "coordinates": [ [ [-74.02, 40.715], [-73.99, 40.715], [-73.99, 40.705], [-74.02, 40.705], [-74.02, 40.715] ] ] }, "relation": "within" } } } } } }
location
是存储地理位置的字段shape
定义了一个多边形区域,coordinates
是一个数组,包含多边形顶点的坐标relation
指定了查询的地理空间关系,这里是within
,表示查询多边形内部的点- 多边形的坐标点需要按顺序(通常是顺时针或逆时针)排列,形成一个闭合的多边形
四、Java代码实现
具体查询对象,可自行定义,本方法只提供思路,莫直接粘贴使用
// 封装ES查询参数 BoolQuery.Builder boolQueryBuilder = new BoolQuery.Builder(); // AOI范围查询 ShapePO shapePo = new ShapePO().setType(GeographyType.POLYGON.getValue()).setCoordinates(poi.getAoi().getCoordinates()); // 多边形查询 GeoShapeQuery geoShapeQuery = GeoShapeQuery.of(geoShape -> geoShape.field(PoiIndexConstant.LOCATION) .shape(s -> s.shape(JsonData.fromJson(JSONUtil.toJsonStr(shapePo))).relation(GeoShapeRelation.Within)))._toQuery().geoShape(); boolQueryBuilder.filter(f -> f.geoShape(geoShapeQuery)); int size = poi.getAoi().getCoordinates().get(0).size(); SearchRequest.Builder searchRequestBuilder = new SearchRequest.Builder(); searchRequestBuilder.index(esIndexProperties.getPoiIndexRead()) .query(query -> query.bool(boolQueryBuilder.build())) .size(size); // ES查询 SearchRequest searchRequest = searchRequestBuilder.build(); log.info("getSmallAttractionByPoiId query:{}", searchRequest.toString()); SearchResponse<PoiIndex> searchResponse = esUtil.queryDocument(searchRequest, PoiIndex.class); if (searchResponse.hits().hits().isEmpty()) { return List.of(); } List<SmallAttractionDTO> smallAttractionDtoList = new ArrayList<>(); for (Hit<PoiIndex> hit : searchResponse.hits().hits()) { // 业务处理 }