Spec-Zone.ru › Elasticsearch 8
›Elasticsearch Guide [8.17] ›Агрегации ›Агрегации метрик

Агрегация гео-центроида

Метрическая агрегация, которая вычисляет взвешенный центроид по всем значениям координат для геополей.

Пример:

resp = client.indices.create(
    index="museums",
    mappings={
        "properties": {
            "location": {
                "type": "geo_point"
            }
        }
    },
)
print(resp)

resp1 = client.bulk(
    index="museums",
    refresh=True,
    operations=[
        {
            "index": {
                "_id": 1
            }
        },
        {
            "location": "POINT (4.912350 52.374081)",
            "city": "Amsterdam",
            "name": "NEMO Science Museum"
        },
        {
            "index": {
                "_id": 2
            }
        },
        {
            "location": "POINT (4.901618 52.369219)",
            "city": "Amsterdam",
            "name": "Museum Het Rembrandthuis"
        },
        {
            "index": {
                "_id": 3
            }
        },
        {
            "location": "POINT (4.914722 52.371667)",
            "city": "Amsterdam",
            "name": "Nederlands Scheepvaartmuseum"
        },
        {
            "index": {
                "_id": 4
            }
        },
        {
            "location": "POINT (4.405200 51.222900)",
            "city": "Antwerp",
            "name": "Letterenhuis"
        },
        {
            "index": {
                "_id": 5
            }
        },
        {
            "location": "POINT (2.336389 48.861111)",
            "city": "Paris",
            "name": "Musée du Louvre"
        },
        {
            "index": {
                "_id": 6
            }
        },
        {
            "location": "POINT (2.327000 48.860000)",
            "city": "Paris",
            "name": "Musée d'Orsay"
        }
    ],
)
print(resp1)

resp2 = client.search(
    index="museums",
    size="0",
    aggs={
        "centroid": {
            "geo_centroid": {
                "field": "location"
            }
        }
    },
)
print(resp2)
response = client.indices.create(
  index: 'museums',
  body: {
    mappings: {
      properties: {
        location: {
          type: 'geo_point'
        }
      }
    }
  }
)
puts response

response = client.bulk(
  index: 'museums',
  refresh: true,
  body: [
    {
      index: {
        _id: 1
      }
    },
    {
      location: 'POINT (4.912350 52.374081)',
      city: 'Amsterdam',
      name: 'NEMO Science Museum'
    },
    {
      index: {
        _id: 2
      }
    },
    {
      location: 'POINT (4.901618 52.369219)',
      city: 'Amsterdam',
      name: 'Museum Het Rembrandthuis'
    },
    {
      index: {
        _id: 3
      }
    },
    {
      location: 'POINT (4.914722 52.371667)',
      city: 'Amsterdam',
      name: 'Nederlands Scheepvaartmuseum'
    },
    {
      index: {
        _id: 4
      }
    },
    {
      location: 'POINT (4.405200 51.222900)',
      city: 'Antwerp',
      name: 'Letterenhuis'
    },
    {
      index: {
        _id: 5
      }
    },
    {
      location: 'POINT (2.336389 48.861111)',
      city: 'Paris',
      name: 'Musée du Louvre'
    },
    {
      index: {
        _id: 6
      }
    },
    {
      location: 'POINT (2.327000 48.860000)',
      city: 'Paris',
      name: "Musée d'Orsay"
    }
  ]
)
puts response

response = client.search(
  index: 'museums',
  size: 0,
  body: {
    aggregations: {
      centroid: {
        geo_centroid: {
          field: 'location'
        }
      }
    }
  }
)
puts response
const response = await client.indices.create({
  index: "museums",
  mappings: {
    properties: {
      location: {
        type: "geo_point",
      },
    },
  },
});
console.log(response);

const response1 = await client.bulk({
  index: "museums",
  refresh: "true",
  operations: [
    {
      index: {
        _id: 1,
      },
    },
    {
      location: "POINT (4.912350 52.374081)",
      city: "Amsterdam",
      name: "NEMO Science Museum",
    },
    {
      index: {
        _id: 2,
      },
    },
    {
      location: "POINT (4.901618 52.369219)",
      city: "Amsterdam",
      name: "Museum Het Rembrandthuis",
    },
    {
      index: {
        _id: 3,
      },
    },
    {
      location: "POINT (4.914722 52.371667)",
      city: "Amsterdam",
      name: "Nederlands Scheepvaartmuseum",
    },
    {
      index: {
        _id: 4,
      },
    },
    {
      location: "POINT (4.405200 51.222900)",
      city: "Antwerp",
      name: "Letterenhuis",
    },
    {
      index: {
        _id: 5,
      },
    },
    {
      location: "POINT (2.336389 48.861111)",
      city: "Paris",
      name: "Musée du Louvre",
    },
    {
      index: {
        _id: 6,
      },
    },
    {
      location: "POINT (2.327000 48.860000)",
      city: "Paris",
      name: "Musée d'Orsay",
    },
  ],
});
console.log(response1);

const response2 = await client.search({
  index: "museums",
  size: 0,
  aggs: {
    centroid: {
      geo_centroid: {
        field: "location",
      },
    },
  },
});
console.log(response2);
PUT /museums
{
  "mappings": {
    "properties": {
      "location": {
        "type": "geo_point"
      }
    }
  }
}

POST /museums/_bulk?refresh
{"index":{"_id":1}}
{"location": "POINT (4.912350 52.374081)", "city": "Amsterdam", "name": "NEMO Science Museum"}
{"index":{"_id":2}}
{"location": "POINT (4.901618 52.369219)", "city": "Amsterdam", "name": "Museum Het Rembrandthuis"}
{"index":{"_id":3}}
{"location": "POINT (4.914722 52.371667)", "city": "Amsterdam", "name": "Nederlands Scheepvaartmuseum"}
{"index":{"_id":4}}
{"location": "POINT (4.405200 51.222900)", "city": "Antwerp", "name": "Letterenhuis"}
{"index":{"_id":5}}
{"location": "POINT (2.336389 48.861111)", "city": "Paris", "name": "Musée du Louvre"}
{"index":{"_id":6}}
{"location": "POINT (2.327000 48.860000)", "city": "Paris", "name": "Musée d'Orsay"}

POST /museums/_search?size=0
{
  "aggs": {
    "centroid": {
      "geo_centroid": {
        "field": "location" 
      }
    }
  }
}

Агрегация geo_centroid указывает поле, используемое для вычисления центроида. (ПРИМЕЧАНИЕ: поле должно быть типа Geopoint)

Вышеприведенная агрегация демонстрирует, как вычислить центроид поля местоположения для всех документов музеев.

Ответ на вышеуказанную агрегацию:

{
  ...
  "aggregations": {
    "centroid": {
      "location": {
        "lat": 51.00982965203002,
        "lon": 3.9662131341174245
      },
      "count": 6
    }
  }
}

Агрегация geo_centroid становится более интересной, когда используется в качестве под-агрегации к другим агрегациям по корзинам.

Пример:

resp = client.search(
    index="museums",
    size="0",
    aggs={
        "cities": {
            "terms": {
                "field": "city.keyword"
            },
            "aggs": {
                "centroid": {
                    "geo_centroid": {
                        "field": "location"
                    }
                }
            }
        }
    },
)
print(resp)
response = client.search(
  index: 'museums',
  size: 0,
  body: {
    aggregations: {
      cities: {
        terms: {
          field: 'city.keyword'
        },
        aggregations: {
          centroid: {
            geo_centroid: {
              field: 'location'
            }
          }
        }
      }
    }
  }
)
puts response
const response = await client.search({
  index: "museums",
  size: 0,
  aggs: {
    cities: {
      terms: {
        field: "city.keyword",
      },
      aggs: {
        centroid: {
          geo_centroid: {
            field: "location",
          },
        },
      },
    },
  },
});
console.log(response);
POST /museums/_search?size=0
{
  "aggs": {
    "cities": {
      "terms": { "field": "city.keyword" },
      "aggs": {
        "centroid": {
          "geo_centroid": { "field": "location" }
        }
      }
    }
  }
}

В приведенном выше примере используется geo_centroid в качестве под-агрегации к агрегации по корзинам terms для поиска центрального местоположения музеев в каждом городе.

Ответ на вышеуказанную агрегацию:

{
  ...
  "aggregations": {
    "cities": {
      "sum_other_doc_count": 0,
      "doc_count_error_upper_bound": 0,
      "buckets": [
        {
          "key": "Amsterdam",
          "doc_count": 3,
          "centroid": {
            "location": {
              "lat": 52.371655656024814,
              "lon": 4.909563297405839
            },
            "count": 3
          }
        },
        {
          "key": "Paris",
          "doc_count": 2,
          "centroid": {
            "location": {
              "lat": 48.86055548675358,
              "lon": 2.3316944623366
            },
            "count": 2
          }
        },
        {
          "key": "Antwerp",
          "doc_count": 1,
          "centroid": {
            "location": {
              "lat": 51.22289997059852,
              "lon": 4.40519998781383
            },
            "count": 1
          }
        }
      ]
    }
  }
}

Агрегация Geo Centroid на полях geo_shape

Метрика центроида для гео-форм более сложная, чем для точек. Центроид определенной корзины агрегации, содержащей формы, — это центроид формы с наивысшей размерностью в этой корзине. Например, если корзина содержит фигуры, состоящие из многоугольников и линий, то линии не влияют на метрику центроида. Центроид каждого типа формы рассчитывается по-разному. Области и окружности, импортированные с помощью Circle, обрабатываются как многоугольники.

Тип геометрии Вычисление центроида

[Много]Точка

взвешенное среднее значение всех координат

[Много]Линия

взвешенное среднее всех центроидов каждого отрезка, где вес каждого отрезка — это его длина в градусах

[Много]Многоугольник

взвешенное среднее всех центроидов всех треугольников многоугольника, где треугольники образуются каждыми двумя последовательными вершинами и начальной точкой. дыры имеют отрицательные веса. веса представляют площадь треугольника в deg^2, рассчитанную

Геометрия

Центроид всех подлежащих геометрий с наивысшей размерностью. Если Многоугольники и Линии и/или Точки, то линии и/или точки игнорируются. Если Линии и Точки, то точки игнорируются

Пример:

resp = client.indices.create(
    index="places",
    mappings={
        "properties": {
            "geometry": {
                "type": "geo_shape"
            }
        }
    },
)
print(resp)

resp1 = client.bulk(
    index="places",
    refresh=True,
    operations=[
        {
            "index": {
                "_id": 1
            }
        },
        {
            "name": "NEMO Science Museum",
            "geometry": "POINT(4.912350 52.374081)"
        },
        {
            "index": {
                "_id": 2
            }
        },
        {
            "name": "Sportpark De Weeren",
            "geometry": {
                "type": "Polygon",
                "coordinates": [
                    [
                        [
                            4.965305328369141,
                            52.39347642069457
                        ],
                        [
                            4.966979026794433,
                            52.391721758934835
                        ],
                        [
                            4.969425201416015,
                            52.39238958618537
                        ],
                        [
                            4.967944622039794,
                            52.39420969150824
                        ],
                        [
                            4.965305328369141,
                            52.39347642069457
                        ]
                    ]
                ]
            }
        }
    ],
)
print(resp1)

resp2 = client.search(
    index="places",
    size="0",
    aggs={
        "centroid": {
            "geo_centroid": {
                "field": "geometry"
            }
        }
    },
)
print(resp2)
response = client.indices.create(
  index: 'places',
  body: {
    mappings: {
      properties: {
        geometry: {
          type: 'geo_shape'
        }
      }
    }
  }
)
puts response

response = client.bulk(
  index: 'places',
  refresh: true,
  body: [
    {
      index: {
        _id: 1
      }
    },
    {
      name: 'NEMO Science Museum',
      geometry: 'POINT(4.912350 52.374081)'
    },
    {
      index: {
        _id: 2
      }
    },
    {
      name: 'Sportpark De Weeren',
      geometry: {
        type: 'Polygon',
        coordinates: [
          [
            [
              4.965305328369141,
              52.39347642069457
            ],
            [
              4.966979026794433,
              52.391721758934835
            ],
            [
              4.969425201416015,
              52.39238958618537
            ],
            [
              4.967944622039794,
              52.39420969150824
            ],
            [
              4.965305328369141,
              52.39347642069457
            ]
          ]
        ]
      }
    }
  ]
)
puts response

response = client.search(
  index: 'places',
  size: 0,
  body: {
    aggregations: {
      centroid: {
        geo_centroid: {
          field: 'geometry'
        }
      }
    }
  }
)
puts response
const response = await client.indices.create({
  index: "places",
  mappings: {
    properties: {
      geometry: {
        type: "geo_shape",
      },
    },
  },
});
console.log(response);

const response1 = await client.bulk({
  index: "places",
  refresh: "true",
  operations: [
    {
      index: {
        _id: 1,
      },
    },
    {
      name: "NEMO Science Museum",
      geometry: "POINT(4.912350 52.374081)",
    },
    {
      index: {
        _id: 2,
      },
    },
    {
      name: "Sportpark De Weeren",
      geometry: {
        type: "Polygon",
        coordinates: [
          [
            [4.965305328369141, 52.39347642069457],
            [4.966979026794433, 52.391721758934835],
            [4.969425201416015, 52.39238958618537],
            [4.967944622039794, 52.39420969150824],
            [4.965305328369141, 52.39347642069457],
          ],
        ],
      },
    },
  ],
});
console.log(response1);

const response2 = await client.search({
  index: "places",
  size: 0,
  aggs: {
    centroid: {
      geo_centroid: {
        field: "geometry",
      },
    },
  },
});
console.log(response2);
PUT /places
{
  "mappings": {
    "properties": {
      "geometry": {
        "type": "geo_shape"
      }
    }
  }
}

POST /places/_bulk?refresh
{"index":{"_id":1}}
{"name": "NEMO Science Museum", "geometry": "POINT(4.912350 52.374081)" }
{"index":{"_id":2}}
{"name": "Sportpark De Weeren", "geometry": { "type": "Polygon", "coordinates": [ [ [ 4.965305328369141, 52.39347642069457 ], [ 4.966979026794433, 52.391721758934835 ], [ 4.969425201416015, 52.39238958618537 ], [ 4.967944622039794, 52.39420969150824 ], [ 4.965305328369141, 52.39347642069457 ] ] ] } }

POST /places/_search?size=0
{
  "aggs": {
    "centroid": {
      "geo_centroid": {
        "field": "geometry"
      }
    }
  }
}
{
  ...
  "aggregations": {
    "centroid": {
      "location": {
        "lat": 52.39296147599816,
        "lon": 4.967404240742326
      },
      "count": 2
    }
  }
}

Использование geo_centroid в качестве под-агрегации geohash_grid

Агрегация geohash_grid помещает документы, а не отдельные гео-точки, в корзины. Если поле geo_point документа содержит несколько значений, документ может быть назначен нескольким корзинам, даже если одна или несколько его гео-точек находятся за пределами границ корзины.

Если также используется под-агрегация geocentroid, каждый центроид рассчитывается с использованием всех гео-точек в корзине, включая те, что находятся за пределами границ корзины. Это может привести к центроидам за пределами границ корзины.

© 2023-2025 Elasticsearch
As of September 2024, Elasticsearch is available under a choice of three licenses: the Server Side Public License (SSPL), the Elastic License, or the AGPLv3 (OSI approved).
Elasticsearch and the Elasticsearch logo are trademarks of Elasticsearch B.V., registered in the U.S. and in other countries.
https://www.elastic.co/guide/en/elasticsearch/reference/8.17/search-aggregations-metrics-geocentroid-aggregation.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API