在OpenSearch Java API中使用geohash_grid聚合报错,求替代方案
在Java OpenSearch API中使用geohash_grid聚合报错的替代方案
问题说明
执行geohash_grid聚合查询时收到错误提示:
"Unknown aggregation type [geohash_grid]"
原聚合查询代码如下:
"aggs": { "filter_agg": { "filter": { "geo_bounding_box": { "ignore_unmapped": true, "location": { "top_left": { "lat": 90, "lon": -180 }, "bottom_right": { "lat": -90, "lon": 180 } } } }, "aggs": { "2": { "geohash_grid": { "field": "location", "precision": 2 }, "aggs": { "3": { "geo_centroid": { "field": "location" } } } } } }
替代方案
1. 使用geo_tile_grid聚合
OpenSearch官方推荐用geo_tile_grid替代geohash_grid,它基于Web Mercator瓦片系统,实现的地理分桶逻辑和原聚合一致,还能配合地图瓦片系统更直观展示结果。
修改后的查询示例:
"aggs": { "filter_agg": { "filter": { "geo_bounding_box": { "ignore_unmapped": true, "location": { "top_left": { "lat": 90, "lon": -180 }, "bottom_right": { "lat": -90, "lon": 180 } } } }, "aggs": { "2": { "geo_tile_grid": { "field": "location", "precision": 2 }, "aggs": { "3": { "geo_centroid": { "field": "location" } } } } } }
注意:geo_tile_grid的precision参数对应瓦片层级(范围1-29),和geohash_grid的精度逻辑略有差异,可根据需求调整层级匹配原分桶粒度。
2. 预计算geohash值,使用terms聚合
如果必须严格沿用geohash的分桶逻辑,可提前在文档中新增存储geohash值的字段(比如location_geohash):
- 索引阶段:为每个文档的
location字段计算对应精度(比如2)的geohash字符串,存入location_geohash字段 - 查询阶段替换聚合类型为
terms:
"aggs": { "filter_agg": { "filter": { "geo_bounding_box": { "ignore_unmapped": true, "location": { "top_left": { "lat": 90, "lon": -180 }, "bottom_right": { "lat": -90, "lon": 180 } } } }, "aggs": { "2": { "terms": { "field": "location_geohash", "size": 1000 }, "aggs": { "3": { "geo_centroid": { "field": "location" } } } } } }
这种方式需要额外维护geohash字段,但能完全匹配原geohash_grid的分桶效果。
内容的提问来源于stack exchange,提问作者Hayk Mkhitaryan
相关产品推荐
相关产品推荐

