Spec-Zone.ru › Elasticsearch 8
›Elasticsearch Guide [8.17] ›Ingest pipelines ›Ingest processor reference

Процессор geo-grid

Преобразует определения гео-ячеек сетки или ячеек в обычные прямоугольные рамки или полигоны, описывающие их форму. Это полезно, если есть необходимость взаимодействовать с формами ячеек как с пространственно индексируемыми полями. Например, значение поля geotile "4/8/3" можно было бы индексировать как строковое поле, но это не позволит выполнять какие-либо пространственные операции с ним. Вместо этого преобразуйте его в значение "POLYGON ((0.0 40.979898069620134, 22.5 40.979898069620134, 22.5 55.77657301866769, 0.0 55.77657301866769, 0.0 40.979898069620134))", которое можно индексировать как поле geo_shape.

Таблица 21. Параметры процессора geo_grid

Имя Обязательно По умолчанию Описание

field

да

-

Поле для интерпретации в качестве гео-ячейки. Формат поля определяется значением tile_type.

tile_type

да

-

Поддерживаются три формата ячеек: geohash, geotile и geohex.

target_field

нет

field

Поле, которому присваивается форма полигона. По умолчанию поле field обновляется на месте.

parent_field

нет

-

Если указано и родительская ячейка существует, сохранить адрес этой ячейки в это поле.

children_field

нет

-

Если указано и дочерние ячейки существуют, сохранить адреса этих ячеек в это поле в виде массива строк.

non_children_field

нет

-

Если указано и пересекающиеся не-дочерние ячейки существуют, сохранить их адреса в это поле в виде массива строк.

precision_field

нет

-

Если указано, сохранить точность ячейки (уровень масштабирования) в виде целого числа в это поле.

ignore_missing

нет

-

Если true и field не существует, процессор спокойно завершает работу, не изменяя документ.

target_format

нет

"GeoJSON"

Формат сохранения сгенерированного полигона. Либо WKT, либо GeoJSON.

description

нет

-

Описание процессора. Полезно для описания цели процессора или его конфигурации.

if

нет

-

Условное выполнение процессора. См. Условное выполнение процессора.

ignore_failure

нет

false

Игнорировать ошибки для процессора. См. Обработка сбоев конвейера.

on_failure

нет

-

Обработка ошибок для процессора. См. Обработка сбоев конвейера.

tag

нет

-

Идентификатор процессора. Полезно для отладки и метрик.

Для демонстрации использования этого процессора ingest рассмотрим индекс под названием geocells с отображением для поля geocell типа geo_shape. Для заполнения этого индекса с использованием полей geotile и geohex определите два процессора ingest:

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

resp1 = client.ingest.put_pipeline(
    id="geotile2shape",
    description="translate rectangular z/x/y geotile to bounding box",
    processors=[
        {
            "geo_grid": {
                "field": "geocell",
                "tile_type": "geotile"
            }
        }
    ],
)
print(resp1)

resp2 = client.ingest.put_pipeline(
    id="geohex2shape",
    description="translate H3 cell to polygon",
    processors=[
        {
            "geo_grid": {
                "field": "geocell",
                "tile_type": "geohex",
                "target_format": "wkt"
            }
        }
    ],
)
print(resp2)
response = client.indices.create(
  index: 'geocells',
  body: {
    mappings: {
      properties: {
        geocell: {
          type: 'geo_shape'
        }
      }
    }
  }
)
puts response

response = client.ingest.put_pipeline(
  id: 'geotile2shape',
  body: {
    description: 'translate rectangular z/x/y geotile to bounding box',
    processors: [
      {
        geo_grid: {
          field: 'geocell',
          tile_type: 'geotile'
        }
      }
    ]
  }
)
puts response

response = client.ingest.put_pipeline(
  id: 'geohex2shape',
  body: {
    description: 'translate H3 cell to polygon',
    processors: [
      {
        geo_grid: {
          field: 'geocell',
          tile_type: 'geohex',
          target_format: 'wkt'
        }
      }
    ]
  }
)
puts response
const response = await client.indices.create({
  index: "geocells",
  mappings: {
    properties: {
      geocell: {
        type: "geo_shape",
      },
    },
  },
});
console.log(response);

const response1 = await client.ingest.putPipeline({
  id: "geotile2shape",
  description: "translate rectangular z/x/y geotile to bounding box",
  processors: [
    {
      geo_grid: {
        field: "geocell",
        tile_type: "geotile",
      },
    },
  ],
});
console.log(response1);

const response2 = await client.ingest.putPipeline({
  id: "geohex2shape",
  description: "translate H3 cell to polygon",
  processors: [
    {
      geo_grid: {
        field: "geocell",
        tile_type: "geohex",
        target_format: "wkt",
      },
    },
  ],
});
console.log(response2);
PUT geocells
{
  "mappings": {
    "properties": {
      "geocell": {
        "type": "geo_shape"
      }
    }
  }
}

PUT _ingest/pipeline/geotile2shape
{
  "description": "translate rectangular z/x/y geotile to bounding box",
  "processors": [
    {
      "geo_grid": {
        "field": "geocell",
        "tile_type": "geotile"
      }
    }
  ]
}

PUT _ingest/pipeline/geohex2shape
{
  "description": "translate H3 cell to polygon",
  "processors": [
    {
      "geo_grid": {
        "field": "geocell",
        "tile_type": "geohex",
        "target_format": "wkt"
      }
    }
  ]
}

Эти два конвейера можно использовать для индексирования документов в индекс geocells. Поле geocell будет представлять собой строковую версию прямоугольной ячейки с форматом z/x/y или адрес ячейки H3, в зависимости от того, какой процессор ingest мы используем при индексировании документа. Результирующая геометрия будет представлена и индексирована как поле geo_shape в формате GeoJSON или Well-Known Text.

Пример: Прямоугольная гео-ячейка с охватом в формате GeoJSON

В этом примере поле geocell со значением, определенным в формате z/x/y, индексируется как прямоугольная рамка GeoJSON, так как процессор ingest определен с параметром target_format по умолчанию.

resp = client.index(
    index="geocells",
    id="1",
    pipeline="geotile2shape",
    document={
        "geocell": "4/8/5"
    },
)
print(resp)

resp1 = client.get(
    index="geocells",
    id="1",
)
print(resp1)
response = client.index(
  index: 'geocells',
  id: 1,
  pipeline: 'geotile2shape',
  body: {
    geocell: '4/8/5'
  }
)
puts response

response = client.get(
  index: 'geocells',
  id: 1
)
puts response
const response = await client.index({
  index: "geocells",
  id: 1,
  pipeline: "geotile2shape",
  document: {
    geocell: "4/8/5",
  },
});
console.log(response);

const response1 = await client.get({
  index: "geocells",
  id: 1,
});
console.log(response1);
PUT geocells/_doc/1?pipeline=geotile2shape
{
  "geocell": "4/8/5"
}

GET geocells/_doc/1

Ответ показывает, как процессор ingest заменил поле geocell индексируемым полем geo_shape:

{
 "_index": "geocells",
  "_id": "1",
  "_version": 1,
  "_seq_no": 0,
  "_primary_term": 1,
  "found": true,
  "_source": {
    "geocell": {
      "type": "Envelope",
      "coordinates": [
        [ 0.0, 55.77657301866769 ],
        [ 22.5, 40.979898069620134 ]
      ]
    }
  }
}

Kibana map with showing the geotile at 4/8/5 and its four child cells

Пример: Гексагональная гео-ячейка с полигоном в формате WKT

В этом примере поле geocell со строковым адресом H3 индексируется как полигон WKT, так как этот процессор ingest явно определил target_format.

resp = client.index(
    index="geocells",
    id="1",
    pipeline="geohex2shape",
    document={
        "geocell": "811fbffffffffff"
    },
)
print(resp)

resp1 = client.get(
    index="geocells",
    id="1",
)
print(resp1)
response = client.index(
  index: 'geocells',
  id: 1,
  pipeline: 'geohex2shape',
  body: {
    geocell: '811fbffffffffff'
  }
)
puts response

response = client.get(
  index: 'geocells',
  id: 1
)
puts response
const response = await client.index({
  index: "geocells",
  id: 1,
  pipeline: "geohex2shape",
  document: {
    geocell: "811fbffffffffff",
  },
});
console.log(response);

const response1 = await client.get({
  index: "geocells",
  id: 1,
});
console.log(response1);
PUT geocells/_doc/1?pipeline=geohex2shape
{
  "geocell": "811fbffffffffff"
}

GET geocells/_doc/1

Ответ показывает, как процессор ingest заменил поле geocell индексируемым полем geo_shape:

{
 "_index": "geocells",
  "_id": "1",
  "_version": 1,
  "_seq_no": 0,
  "_primary_term": 1,
  "found": true,
  "_source": {
    "geocell": "POLYGON ((1.1885095294564962 49.470279179513454, 2.0265689212828875 45.18424864858389, 7.509948452934623 43.786609335802495, 12.6773177459836 46.40695743262768, 12.345747342333198 50.55427505169064, 6.259687012061477 51.964770150370896, 3.6300085578113794 50.610463307239115, 1.1885095294564962 49.470279179513454))"
  }
}

Kibana map with showing an H3 cell

Пример: Подробные данные о ячейках

Как описано в параметрах процессора geo_grid, можно задать множество других полей, которые обогатят доступную информацию. Например, у ячеек H3 есть 7 дочерних ячеек, но только первая полностью содержится в родительской. Остальные шесть частично перекрываются с родительской ячейкой, и существует еще шесть не-дочерних ячеек, которые перекрываются с родительской. Это можно исследовать, добавив дополнительные поля родителя и ребенка в процессор ingest:

resp = client.ingest.put_pipeline(
    id="geohex2shape",
    description="translate H3 cell to polygon with enriched fields",
    processors=[
        {
            "geo_grid": {
                "description": "Ingest H3 cells like '811fbffffffffff' and create polygons",
                "field": "geocell",
                "tile_type": "geohex",
                "target_format": "wkt",
                "target_field": "shape",
                "parent_field": "parent",
                "children_field": "children",
                "non_children_field": "nonChildren",
                "precision_field": "precision"
            }
        }
    ],
)
print(resp)
response = client.ingest.put_pipeline(
  id: 'geohex2shape',
  body: {
    description: 'translate H3 cell to polygon with enriched fields',
    processors: [
      {
        geo_grid: {
          description: "Ingest H3 cells like '811fbffffffffff' and create polygons",
          field: 'geocell',
          tile_type: 'geohex',
          target_format: 'wkt',
          target_field: 'shape',
          parent_field: 'parent',
          children_field: 'children',
          non_children_field: 'nonChildren',
          precision_field: 'precision'
        }
      }
    ]
  }
)
puts response
const response = await client.ingest.putPipeline({
  id: "geohex2shape",
  description: "translate H3 cell to polygon with enriched fields",
  processors: [
    {
      geo_grid: {
        description:
          "Ingest H3 cells like '811fbffffffffff' and create polygons",
        field: "geocell",
        tile_type: "geohex",
        target_format: "wkt",
        target_field: "shape",
        parent_field: "parent",
        children_field: "children",
        non_children_field: "nonChildren",
        precision_field: "precision",
      },
    },
  ],
});
console.log(response);
PUT _ingest/pipeline/geohex2shape
{
  "description": "translate H3 cell to polygon with enriched fields",
  "processors": [
    {
      "geo_grid": {
        "description": "Ingest H3 cells like '811fbffffffffff' and create polygons",
        "field": "geocell",
        "tile_type": "geohex",
        "target_format": "wkt",
        "target_field": "shape",
        "parent_field": "parent",
        "children_field": "children",
        "non_children_field": "nonChildren",
        "precision_field": "precision"
      }
    }
  ]
}

Индексируйте документ, чтобы увидеть другой результат:

resp = client.index(
    index="geocells",
    id="1",
    pipeline="geohex2shape",
    document={
        "geocell": "811fbffffffffff"
    },
)
print(resp)

resp1 = client.get(
    index="geocells",
    id="1",
)
print(resp1)
response = client.index(
  index: 'geocells',
  id: 1,
  pipeline: 'geohex2shape',
  body: {
    geocell: '811fbffffffffff'
  }
)
puts response

response = client.get(
  index: 'geocells',
  id: 1
)
puts response
const response = await client.index({
  index: "geocells",
  id: 1,
  pipeline: "geohex2shape",
  document: {
    geocell: "811fbffffffffff",
  },
});
console.log(response);

const response1 = await client.get({
  index: "geocells",
  id: 1,
});
console.log(response1);
PUT geocells/_doc/1?pipeline=geohex2shape
{
  "geocell": "811fbffffffffff"
}

GET geocells/_doc/1

Ответ на этот запрос индексирования:

{
  "_index": "geocells",
  "_id": "1",
  "_version": 1,
  "_seq_no": 0,
  "_primary_term": 1,
  "found": true,
  "_source": {
    "parent": "801ffffffffffff",
    "geocell": "811fbffffffffff",
    "precision": 1,
    "shape": "POLYGON ((1.1885095294564962 49.470279179513454, 2.0265689212828875 45.18424864858389, 7.509948452934623 43.786609335802495, 12.6773177459836 46.40695743262768, 12.345747342333198 50.55427505169064, 6.259687012061477 51.964770150370896, 3.6300085578113794 50.610463307239115, 1.1885095294564962 49.470279179513454))",
    "children": [
      "821f87fffffffff",
      "821f8ffffffffff",
      "821f97fffffffff",
      "821f9ffffffffff",
      "821fa7fffffffff",
      "821faffffffffff",
      "821fb7fffffffff"
    ],
    "nonChildren": [
      "821ea7fffffffff",
      "82186ffffffffff",
      "82396ffffffffff",
      "821f17fffffffff",
      "821e37fffffffff",
      "82194ffffffffff"
    ]
  }
}

Эта дополнительная информация позволит, например, создать визуализацию ячейки H3, ее дочерних элементов и пересекающихся не-дочерних элементов.

Kibana map with three H3 layers: cell

© 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/ingest-geo-grid-processor.html

Spec-Zone.ru

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