ES geo_shape 查询
今天遇到一个网友询问关于一个地理位置查询的问题。
类似美团,饿了么是如何判断用户是否在商店的配送范围了?
我的第一反应是以用户为中心,做矩形或者圆形范围查询,现在很多数据库Mongo 以及ES 都支持这种地理位置范围查询。以及距离查询算法等等
但是其实是我理会错了提问者的真实意图。因为类似美团,饿了么的查询都不是以用户为中心进行检索的,而是以商家为中心,判断用户是否在商家的配送范围内,从而给出用户的可选商店列表。是一个反向距离检索的过程,每个商家的配送范围也不相同,从而无法使用上述方法或者类似的算法实现。
不过ES 其实也是支持类似的地理位置关系检索的,下面简单介绍ES 中的geo_shape 类型检索
Spatial Relations
The geo_shape strategy mapping parameter determines which spatial relation operators may be used at search time.
The following is a complete list of spatial relation operators available when searching a field of type geo_shape:
- INTERSECTS - (default) Return all documents whose geo_shape field intersects the query geometry.
- DISJOINT - Return all documents whose geo_shape field has nothing in common with the query geometry.
- WITHIN - Return all documents whose geo_shape field is within the query geometry.
- CONTAINS - Return all documents whose geo_shape field contains the query geometry.
以上节选自ES 官网的教程,指出ES 针对geo_shape 支持 intersects(相交)、disjoint(相离)、within(内含)、contains(包含)等方式检索。下面简单介绍如何使用
PUT /example
{
"mappings": {
"properties": {
"location": {
"type": "geo_shape"
}
}
}
}
POST /example/_doc
{
"location" : {
"type" : "polygon",
"coordinates" : [
[ [100.0, 0.0], [105.0, 0.0], [105.0, 5.0], [100.0, 5.0], [100.0, 0.0] ]
]
}
}
POST /example/_doc
{
"location" : {
"type" : "polygon",
"coordinates" : [
[ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [101.0, 0.0], [100.0, 0.0] ]
]
}
}
上述操作在es中创建了一个example的索引,并且插入了两条矩形数据
假设中心的图标为用户,小正方形为商家A的配送范围,大正方形为商家B的配送范围,用户在检索商家列表的时候只会检索到B而不会检索到A,使用相交(intersects)查询,传入用户的坐标点位置,等到的结果是
GET /example/_search
{
"query": {
"bool": {
"must": {
"match_all": {}
},
"filter": {
"geo_shape": {
"location": {
"shape": {
"type": "point",
"coordinates": [103.0, 3.0]
},
"relation": "intersects"
}
}
}
}
}
}
// search结果输出
{
"took" : 0,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.0,
"hits" : [
{
"_index" : "example",
"_type" : "_doc",
"_id" : "zZ8sU3EBiI7T0tPfrf2X",
"_score" : 1.0,
"_source" : {
"location" : {
"type" : "polygon",
"coordinates" : [
[
[
100.0,
0.0
],
[
105.0,
0.0
],
[
105.0,
5.0
],
[
100.0,
5.0
],
[
100.0,
0.0
]
]
]
}
}
}
]
}
}
本文主要内容结束,只是以问题引出ES 的geo_shape查询,具体的美团还有饿了么肯定不是这么做的,检索算法肯定要比这个复杂的多,本文也仅是一个参考,类似的Mongo也支持类似的操作。
本人才疏学浅,仅以此文作为一个参考和学习笔记,如有问题,欢迎斧正。