OpenSearch如何查询指定边界框内的多边形?
问题描述
尝试执行边界框查询:
GET thing/_search { "query": { "bool": { "must": { "match_all": {} }, "filter": { "geo_bounding_box": { "location": { "top_left": { "lat": 47.7328, "lon": -122.448 }, "bottom_right": { "lat": 47.468, "lon": -122.0924 } } } } } } }
返回错误:
"failed_shards" : [ { "shard" : 0, "index" : "geofence", "node" : "rLGHWGhqRTqDxDlhjA3hhA", "reason" : { "type" : "query_shard_exception", "reason" : "failed to find geo_point field [location]", "index" : "geofence", "index_uuid" : "sBbXbANQROeQ15IzmBRf3g" } } ]
尝试修改mapping:
PUT /thing/_mapping { "mappings": { "properties": { "point": { "type": "geo_point" } } } }
返回语法错误:
"type" : "mapper_parsing_exception", "reason" : "Root mapping definition has unsupported parameters: [mappings : {properties={point={type=geo_point}}}]"
能运行但不符合需求的geo_shape查询:
GET geofence/_search { "query": { "geo_shape": { "geometry": { "shape": { "type": "envelope", "coordinates": [ [ -90.0, 90.0], [ 90.0, -90.0] ] }, "relation": "WITHIN" } } } }
现有多边形数据结构:
"geometry" : { "type" : "Polygon", "coordinates" : [ [ [ -122.661806, 45.596338 ], [ -122.661324, 45.597164 ], [ -122.661865, 45.597326 ], [ -122.662461, 45.597532 ], [ -122.662868, 45.597652 ], [ -122.663405, 45.597825 ], [ -122.664381, 45.598088 ], [ -122.66421, 45.598846 ], [ -122.663995, 45.599551 ], [ -122.663974, 45.599672 ], [ -122.664135, 45.599844 ], [ -122.663898, 45.600662 ], [ -122.664574, 45.60088 ], [ -122.665272, 45.601008 ], [ -122.665808, 45.601128 ], [ -122.666162, 45.599799 ], [ -122.665304, 45.599582 ], [ -122.665411, 45.599046 ], [ -122.66599, 45.597269 ], [ -122.66378, 45.596884 ], [ -122.661806, 45.596338 ] ] ] }
解决方案
1. 修正Mapping语法错误
修改mapping时不需要外层的mappings键,直接指定properties。针对你的geofence索引,确保geometry字段为geo_shape类型(适配Polygon数据),执行:
PUT /geofence/_mapping { "properties": { "geometry": { "type": "geo_shape" } } }
注意:如果索引已有数据,修改字段类型可能失败,需重新创建索引并设置正确mapping后重新导入数据。
2. 针对Polygon的边界框查询(推荐)
直接使用geo_shape查询的envelope类型,坐标格式为[[最小经度, 最大纬度], [最大经度, 最小纬度]],根据需求选择关联关系:
GET geofence/_search { "query": { "geo_shape": { "geometry": { "shape": { "type": "envelope", "coordinates": [ [-122.448, 47.7328], // [最小经度, 最大纬度] [-122.0924, 47.468] // [最大经度, 最小纬度] ] }, "relation": "INTERSECTS" // 可选值:WITHIN(完全在框内)/ INTERSECTS(与框相交)/ CONTAINS(包含框) } } } }
3. 若要使用geo_bounding_box查询
geo_bounding_box仅适用于geo_point类型字段,若需用该方式,可新增centroid字段存储多边形中心点:
PUT /geofence/_mapping { "properties": { "centroid": { "type": "geo_point" } } }
更新数据填入中心点坐标后,执行查询:
GET geofence/_search { "query": { "bool": { "filter": { "geo_bounding_box": { "centroid": { "top_left": { "lat": 47.7328, "lon": -122.448 }, "bottom_right": { "lat": 47.468, "lon": -122.0924 } } } } } } }
内容的提问来源于stack exchange,提问作者studiobrain
相关产品推荐
相关产品推荐

