在ElasticSearch中,地理位置通过geo_point
这个数据类型来支持。地理位置的数据需要提供经纬度信息,当经纬度不合法时,ES会拒绝新增文档。这种类型的数据支持距离计算,范围查询等。在底层,索引使用Geohash实现。
1、创建索引
PUT创建一个索引cn_large_cities
,mapping
为city:
{
"mappings": {
"city": {
"properties": {
"city": {"type": "string"},
"state": {"type": "string"},
"location": {"type": "geo_point"}
}
}
}
}
geo_point类型必须显示指定,ES无法从数据中推断。在ES中,位置数据可以通过对象,字符串,数组三种形式表示,分别如下:
# "lat,lon"
"location":"40.715,-74.011"
"location": {
"lat":40.715,
"lon":-74.011
}
# [lon ,lat]
"location":[-74.011,40.715]
POST下面4条测试数据:
{"city": "Beijing", "state": "BJ","location": {"lat": "39.91667", "lon": "116.41667"}}
{"city": "Shanghai", "state": "SH","location": {"lat": "34.50000", "lon": "121.43333"}}
{"city": "Xiamen", "state": "FJ","location": {"lat": "24.46667", "lon": "118.10000"}}
{"city": "Fuzhou", "state": "FJ","location": {"lat": "26.08333", "lon": "119.30000"}}
{"city": "Guangzhou", "state": "GD","location": {"lat": "23.16667", "lon": "113.23333"}}
查看全部文档:
curl -X GET "http://localhost:9200/cn_large_cities/city/_search?pretty=true"
返回全部的5条数据,score均为1:
2、位置过滤
ES中有4中位置相关的过滤器,用于过滤位置信息:
- geo_distance: 查找距离某个中心点距离在一定范围内的位置
- geo_bounding_box: 查找某个长方形区域内的位置
- geo_distance_range: 查找距离某个中心的距离在min和max之间的位置
- geo_polygon: 查找位于多边形内的地点。
geo_distance
该类型过滤器查找的范围如下图:
下面是一个查询例子:
{
"query":{
"filtered":{
"filter":{
"geo_distance":"1km",
"location":{
"lat":40.715,
"lon": -73.988 }
}
}
}
}
以下查询,查找距厦门500公里以内的城市:
{
"query":{
"filtered":{
"filter":