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

Агрегация картезианского центра

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

Пример:

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

resp1 = client.bulk(
    index="museums",
    refresh=True,
    operations=[
        {
            "index": {
                "_id": 1
            }
        },
        {
            "location": "POINT (491.2350 5237.4081)",
            "city": "Amsterdam",
            "name": "NEMO Science Museum"
        },
        {
            "index": {
                "_id": 2
            }
        },
        {
            "location": "POINT (490.1618 5236.9219)",
            "city": "Amsterdam",
            "name": "Museum Het Rembrandthuis"
        },
        {
            "index": {
                "_id": 3
            }
        },
        {
            "location": "POINT (491.4722 5237.1667)",
            "city": "Amsterdam",
            "name": "Nederlands Scheepvaartmuseum"
        },
        {
            "index": {
                "_id": 4
            }
        },
        {
            "location": "POINT (440.5200 5122.2900)",
            "city": "Antwerp",
            "name": "Letterenhuis"
        },
        {
            "index": {
                "_id": 5
            }
        },
        {
            "location": "POINT (233.6389 4886.1111)",
            "city": "Paris",
            "name": "Musée du Louvre"
        },
        {
            "index": {
                "_id": 6
            }
        },
        {
            "location": "POINT (232.7000 4886.0000)",
            "city": "Paris",
            "name": "Musée d'Orsay"
        }
    ],
)
print(resp1)

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

response = client.bulk(
  index: 'museums',
  refresh: true,
  body: [
    {
      index: {
        _id: 1
      }
    },
    {
      location: 'POINT (491.2350 5237.4081)',
      city: 'Amsterdam',
      name: 'NEMO Science Museum'
    },
    {
      index: {
        _id: 2
      }
    },
    {
      location: 'POINT (490.1618 5236.9219)',
      city: 'Amsterdam',
      name: 'Museum Het Rembrandthuis'
    },
    {
      index: {
        _id: 3
      }
    },
    {
      location: 'POINT (491.4722 5237.1667)',
      city: 'Amsterdam',
      name: 'Nederlands Scheepvaartmuseum'
    },
    {
      index: {
        _id: 4
      }
    },
    {
      location: 'POINT (440.5200 5122.2900)',
      city: 'Antwerp',
      name: 'Letterenhuis'
    },
    {
      index: {
        _id: 5
      }
    },
    {
      location: 'POINT (233.6389 4886.1111)',
      city: 'Paris',
      name: 'Musée du Louvre'
    },
    {
      index: {
        _id: 6
      }
    },
    {
      location: 'POINT (232.7000 4886.0000)',
      city: 'Paris',
      name: "Musée d'Orsay"
    }
  ]
)
puts response

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

const response1 = await client.bulk({
  index: "museums",
  refresh: "true",
  operations: [
    {
      index: {
        _id: 1,
      },
    },
    {
      location: "POINT (491.2350 5237.4081)",
      city: "Amsterdam",
      name: "NEMO Science Museum",
    },
    {
      index: {
        _id: 2,
      },
    },
    {
      location: "POINT (490.1618 5236.9219)",
      city: "Amsterdam",
      name: "Museum Het Rembrandthuis",
    },
    {
      index: {
        _id: 3,
      },
    },
    {
      location: "POINT (491.4722 5237.1667)",
      city: "Amsterdam",
      name: "Nederlands Scheepvaartmuseum",
    },
    {
      index: {
        _id: 4,
      },
    },
    {
      location: "POINT (440.5200 5122.2900)",
      city: "Antwerp",
      name: "Letterenhuis",
    },
    {
      index: {
        _id: 5,
      },
    },
    {
      location: "POINT (233.6389 4886.1111)",
      city: "Paris",
      name: "Musée du Louvre",
    },
    {
      index: {
        _id: 6,
      },
    },
    {
      location: "POINT (232.7000 4886.0000)",
      city: "Paris",
      name: "Musée d'Orsay",
    },
  ],
});
console.log(response1);

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

POST /museums/_bulk?refresh
{"index":{"_id":1}}
{"location": "POINT (491.2350 5237.4081)", "city": "Amsterdam", "name": "NEMO Science Museum"}
{"index":{"_id":2}}
{"location": "POINT (490.1618 5236.9219)", "city": "Amsterdam", "name": "Museum Het Rembrandthuis"}
{"index":{"_id":3}}
{"location": "POINT (491.4722 5237.1667)", "city": "Amsterdam", "name": "Nederlands Scheepvaartmuseum"}
{"index":{"_id":4}}
{"location": "POINT (440.5200 5122.2900)", "city": "Antwerp", "name": "Letterenhuis"}
{"index":{"_id":5}}
{"location": "POINT (233.6389 4886.1111)", "city": "Paris", "name": "Musée du Louvre"}
{"index":{"_id":6}}
{"location": "POINT (232.7000 4886.0000)", "city": "Paris", "name": "Musée d'Orsay"}

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

Агрегация cartesian_centroid указывает поле, используемое для вычисления центра, которое должно быть типа Точка или Геометрия.

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

Результат вышеуказанной агрегации:

{
  ...
  "aggregations": {
    "centroid": {
      "location": {
        "x": 396.6213124593099,
        "y": 5100.982991536458
      },
      "count": 6
    }
  }
}

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

Пример:

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

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

Результат вышеуказанной агрегации:

{
  ...
  "aggregations": {
    "cities": {
      "sum_other_doc_count": 0,
      "doc_count_error_upper_bound": 0,
      "buckets": [
        {
          "key": "Amsterdam",
          "doc_count": 3,
          "centroid": {
            "location": {
              "x": 490.9563293457031,
              "y": 5237.16552734375
            },
            "count": 3
          }
        },
        {
          "key": "Paris",
          "doc_count": 2,
          "centroid": {
            "location": {
              "x": 233.16944885253906,
              "y": 4886.0556640625
            },
            "count": 2
          }
        },
        {
          "key": "Antwerp",
          "doc_count": 1,
          "centroid": {
            "location": {
              "x": 440.5199890136719,
              "y": 5122.2900390625
            },
            "count": 1
          }
        }
      ]
    }
  }
}

Агрегация картезианского центра по полям shape

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

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

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

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

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

Взвешенное среднее значение центров каждого сегмента, где вес каждого сегмента — его длина в тех же единицах, что и координаты

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

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

Геометрическая коллекция

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

Пример:

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

resp1 = client.bulk(
    index="places",
    refresh=True,
    operations=[
        {
            "index": {
                "_id": 1
            }
        },
        {
            "name": "NEMO Science Museum",
            "geometry": "POINT(491.2350 5237.4081)"
        },
        {
            "index": {
                "_id": 2
            }
        },
        {
            "name": "Sportpark De Weeren",
            "geometry": {
                "type": "Polygon",
                "coordinates": [
                    [
                        [
                            496.5305328369141,
                            5239.347642069457
                        ],
                        [
                            496.6979026794433,
                            5239.172175893484
                        ],
                        [
                            496.9425201416015,
                            5239.238958618537
                        ],
                        [
                            496.7944622039794,
                            5239.420969150824
                        ],
                        [
                            496.5305328369141,
                            5239.347642069457
                        ]
                    ]
                ]
            }
        }
    ],
)
print(resp1)

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

response = client.bulk(
  index: 'places',
  refresh: true,
  body: [
    {
      index: {
        _id: 1
      }
    },
    {
      name: 'NEMO Science Museum',
      geometry: 'POINT(491.2350 5237.4081)'
    },
    {
      index: {
        _id: 2
      }
    },
    {
      name: 'Sportpark De Weeren',
      geometry: {
        type: 'Polygon',
        coordinates: [
          [
            [
              496.5305328369141,
              5239.347642069457
            ],
            [
              496.6979026794433,
              5239.172175893484
            ],
            [
              496.9425201416015,
              5239.238958618537
            ],
            [
              496.7944622039794,
              5239.420969150824
            ],
            [
              496.5305328369141,
              5239.347642069457
            ]
          ]
        ]
      }
    }
  ]
)
puts response

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

const response1 = await client.bulk({
  index: "places",
  refresh: "true",
  operations: [
    {
      index: {
        _id: 1,
      },
    },
    {
      name: "NEMO Science Museum",
      geometry: "POINT(491.2350 5237.4081)",
    },
    {
      index: {
        _id: 2,
      },
    },
    {
      name: "Sportpark De Weeren",
      geometry: {
        type: "Polygon",
        coordinates: [
          [
            [496.5305328369141, 5239.347642069457],
            [496.6979026794433, 5239.172175893484],
            [496.9425201416015, 5239.238958618537],
            [496.7944622039794, 5239.420969150824],
            [496.5305328369141, 5239.347642069457],
          ],
        ],
      },
    },
  ],
});
console.log(response1);

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

POST /places/_bulk?refresh
{"index":{"_id":1}}
{"name": "NEMO Science Museum", "geometry": "POINT(491.2350 5237.4081)" }
{"index":{"_id":2}}
{"name": "Sportpark De Weeren", "geometry": { "type": "Polygon", "coordinates": [ [ [ 496.5305328369141, 5239.347642069457 ], [ 496.6979026794433, 5239.1721758934835 ], [ 496.9425201416015, 5239.238958618537 ], [ 496.7944622039794, 5239.420969150824 ], [ 496.5305328369141, 5239.347642069457 ] ] ] } }

POST /places/_search?size=0
{
  "aggs": {
    "centroid": {
      "cartesian_centroid": {
        "field": "geometry"
      }
    }
  }
}
{
  ...
  "aggregations": {
    "centroid": {
      "location": {
        "x": 496.74041748046875,
        "y": 5239.29638671875
      },
      "count": 2
    }
  }
}

© 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-cartesian-centroid-aggregation.html

Spec-Zone.ru

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