elasticsearch 7.x 地理距离过滤geo_distance使用 -- 附近的商店,附近的人等

获取以指定经纬度为圆心,指定距离为半径,落在该圆中的点

地理坐标获取

添加索引映射,类型为geo_point需要手动设置
PUT /address
{
    
    
  "mappings": {
    
    
    "properties": {
    
    
      "name": {
    
    
        "type": "text"
      },
      "location": {
    
    
        "type": "geo_point"
      }
    }
  }
}
添加测试数据

注:如果geo_point为字符串或者对象时,先纬度,后经度,如果geo_point为数组时,先经度,后纬度

POST /address/_doc/1
{
    
    
  "name": "广州公园前",
  "location": "23.131479, 113.270719"
}

POST /address/_doc/2
{
    
    
  "name": "广百百货",
  "location": "23.129881, 113.274646"
}

PUT /address/_doc/3 
{
    
    
  "name": "广州市妇幼医院",
  "location": "23.129785, 113.260777"
}

POST /address/_doc/4 
{
    
    
  "name": "广州市银河烈士陵园",
  "location": "23.168615, 113.343607"
}
查找坐标为(纬度,经度)“23.131304,113.262402”,1公里内的文档

_geo_distance:用于计算两点间的距离
unit:指定单位为km,默认为m

GET /restaurant/_search
{
    
    
  "query": {
    
    
    "bool": {
    
    
      "filter": {
    
    
        "geo_distance": {
    
    
          "distance": "1km",
          "location": {
    
    
            "lat": 23.131304,
            "lon": 113.262402
          }
        }
      }
    }
  },
  "sort": [
    {
    
    
      "_geo_distance": {
    
    
        "unit": "km", 
        "location": {
    
    
          "lat": 23.131304,
          "lon": 113.262402
        },
        "order": "asc"
      }
    }
  ]
}

查找结果
{
    
    
  "took" : 2,
  "timed_out" : false,
  "_shards" : {
    
    
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    
    
    "total" : {
    
    
      "value" : 2,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [
      {
    
    
        "_index" : "restaurant",
        "_type" : "_doc",
        "_id" : "3",
        "_score" : null,
        "_source" : {
    
    
          "name" : "广州市妇幼医院",
          "location" : "23.129785, 113.260777"
        },
        "sort" : [
          0.23694189365651083
        ]
      },
      {
    
    
        "_index" : "restaurant",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : null,
        "_source" : {
    
    
          "name" : "公园前",
          "location" : "23.131479, 113.270719"
        },
        "sort" : [
          0.8506760921207346
        ]
      }
    ]
  }
}

猜你喜欢

转载自blog.csdn.net/coffee_shop/article/details/107110707