ElasticSearch-多边形范围查询(8.x)

目录

一、字段设计

二、数据录入

三、查询语句

四、Java代码实现


开发版本详见: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()) {
            // 业务处理
        }

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值