Link Search Menu Expand Document Documentation Menu

地理距离聚合

geo_distance 聚合根据文档与起始 geo_point 字段的距离,将文档分组到同心圆中。它与 range 聚合类似,但适用于地理位置。

例如,您可以使用 geo_distance 聚合查找距离您 1 公里范围内的所有披萨店。搜索结果被限制在您指定的 1 公里半径内,但您可以添加在 2 公里范围内找到的另一个结果。

您只能在映射为 geo_point 的字段上使用 geo_distance 聚合。

点是单个地理坐标,例如智能手机显示您的当前位置。OpenSearch 中的点表示如下

{
  "location": {
    "type": "point",
    "coordinates": {
      "lat": 83.76,
      "lon": -81.2
    }
  }
}

您还可以将纬度和经度指定为数组 [-81.20, 83.76] 或字符串 "83.76, -81.20"

下表列出了 geo_distance 聚合的相关字段

字段 描述 必需
field 指定要操作的地理坐标点字段。
origin 指定用于计算距离的地理坐标点。
ranges 指定一系列范围,以根据文档与目标点的距离来收集文档。
unit 定义 ranges 数组中使用的单位。unit 默认为 m(米),但您可以切换到其他单位,如 km(公里)、mi(英里)、in(英寸)、yd(码)、cm(厘米)和 mm(毫米)。
distance_type 指定 OpenSearch 如何计算距离。默认值为 sloppy_arc(速度更快但精度较低),也可以设置为 arc(速度较慢但精度最高)或 plane(速度最快但精度最低)。由于误差范围较大,plane 仅适用于小地理区域。

语法如下

{
  "aggs": {
    "aggregation_name": {
      "geo_distance": {
        "field": "field_1",
        "origin": "x, y",
        "ranges": [
          {
            "to": "value_1"
          },
          {
            "from": "value_2",
            "to": "value_3"
          },
          {
            "from": "value_4"
          }
        ]
      }
    }
  }
}

此示例根据与 geo-point 字段的以下距离形成桶

  • 小于 10 公里
  • 从 10 公里到 20 公里
  • 从 20 公里到 50 公里
  • 从 50 公里到 100 公里
  • 大于 100 公里
GET opensearch_dashboards_sample_data_logs/_search
{
  "size": 0,
  "aggs": {
    "position": {
      "geo_distance": {
        "field": "geo.coordinates",
        "origin": {
          "lat": 83.76,
          "lon": -81.2
        },
        "ranges": [
          {
            "to": 10
          },
          {
            "from": 10,
            "to": 20
          },
          {
            "from": 20,
            "to": 50
          },
          {
            "from": 50,
            "to": 100
          },
          {
            "from": 100
          }
        ]
      }
    }
  }
}

示例响应

...
"aggregations" : {
  "position" : {
    "buckets" : [
      {
        "key" : "*-10.0",
        "from" : 0.0,
        "to" : 10.0,
        "doc_count" : 0
      },
      {
        "key" : "10.0-20.0",
        "from" : 10.0,
        "to" : 20.0,
        "doc_count" : 0
      },
      {
        "key" : "20.0-50.0",
        "from" : 20.0,
        "to" : 50.0,
        "doc_count" : 0
      },
      {
        "key" : "50.0-100.0",
        "from" : 50.0,
        "to" : 100.0,
        "doc_count" : 0
      },
      {
        "key" : "100.0-*",
        "from" : 100.0,
        "doc_count" : 14074
      }
    ]
  }
 }
}
剩余 350 字符

有问题?

想贡献?