Spec-Zone.ru › Elasticsearch 8
›Elasticsearch Guide [8.17] ›Отображение ›Типы данных полей

Тип поля «пропускающее объект»

Объекты «пропускающие» расширяют функциональность объектов, позволяя получать доступ к их подполям, не включая имя объекта «пропускающего» в качестве префикса. Например:

resp = client.indices.create(
    index="my-index-000001",
    mappings={
        "properties": {
            "attributes": {
                "type": "passthrough",
                "priority": 10,
                "properties": {
                    "id": {
                        "type": "keyword"
                    }
                }
            }
        }
    },
)
print(resp)

resp1 = client.index(
    index="my-index-000001",
    id="1",
    document={
        "attributes": {
            "id": "foo",
            "zone": 10
        }
    },
)
print(resp1)

resp2 = client.search(
    index="my-index-000001",
    query={
        "bool": {
            "must": [
                {
                    "match": {
                        "id": "foo"
                    }
                },
                {
                    "match": {
                        "zone": 10
                    }
                }
            ]
        }
    },
)
print(resp2)

resp3 = client.search(
    index="my-index-000001",
    query={
        "bool": {
            "must": [
                {
                    "match": {
                        "attributes.id": "foo"
                    }
                },
                {
                    "match": {
                        "attributes.zone": 10
                    }
                }
            ]
        }
    },
)
print(resp3)
const response = await client.indices.create({
  index: "my-index-000001",
  mappings: {
    properties: {
      attributes: {
        type: "passthrough",
        priority: 10,
        properties: {
          id: {
            type: "keyword",
          },
        },
      },
    },
  },
});
console.log(response);

const response1 = await client.index({
  index: "my-index-000001",
  id: 1,
  document: {
    attributes: {
      id: "foo",
      zone: 10,
    },
  },
});
console.log(response1);

const response2 = await client.search({
  index: "my-index-000001",
  query: {
    bool: {
      must: [
        {
          match: {
            id: "foo",
          },
        },
        {
          match: {
            zone: 10,
          },
        },
      ],
    },
  },
});
console.log(response2);

const response3 = await client.search({
  index: "my-index-000001",
  query: {
    bool: {
      must: [
        {
          match: {
            "attributes.id": "foo",
          },
        },
        {
          match: {
            "attributes.zone": 10,
          },
        },
      ],
    },
  },
});
console.log(response3);
PUT my-index-000001
{
  "mappings": {
    "properties": {
      "attributes": {
        "type": "passthrough", 
        "priority": 10,
        "properties": {
          "id": {
            "type": "keyword"
          }
        }
      }
    }
  }
}

PUT my-index-000001/_doc/1
{
  "attributes" : {  
    "id": "foo",
    "zone": 10
  }
}

GET my-index-000001/_search
{
  "query": {
    "bool": {
      "must": [
        { "match": { "id": "foo" }},  
        { "match": { "zone": 10 }}
      ]
    }
  }
}

GET my-index-000001/_search
{
  "query": {
    "bool": {
      "must": [
        { "match": { "attributes.id": "foo" }}, 
        { "match": { "attributes.zone": 10 }}
      ]
    }
  }
}

Объект определяется как «пропускающий». Его приоритет (обязательный) используется для разрешения конфликтов.

Содержание объекта индексируется как обычно, включая динамическое отображение.

Подполя могут быть указаны в запросах так, как будто они определены на корневом уровне.

Подполя также могут быть указаны, включая имя объекта в качестве префикса.

Разрешение конфликтов

Возможны конфликтующие имена для полей, определенных в различных областях:

  1. Объект «пропускающий» определяется рядом с полем, имеющим такое же имя, как одно из подполей объекта «пропускающего», например:

    resp = client.index(
        index="my-index-000001",
        id="1",
        document={
            "attributes": {
                "id": "foo"
            },
            "id": "bar"
        },
    )
    print(resp)
    const response = await client.index({
      index: "my-index-000001",
      id: 1,
      document: {
        attributes: {
          id: "foo",
        },
        id: "bar",
      },
    });
    console.log(response);
    PUT my-index-000001/_doc/1
    {
      "attributes" : {
        "id": "foo"
      },
      "id": "bar"
    }

    В этом случае ссылки на id указывают на поле на корневом уровне, а поле attributes.id может быть доступно только с полным путем.

  2. Два (или более) объекта «пропускающих» определены в одном объекте и содержат поля с одинаковым именем, например:

    resp = client.indices.create(
        index="my-index-000002",
        mappings={
            "properties": {
                "attributes": {
                    "type": "passthrough",
                    "priority": 10,
                    "properties": {
                        "id": {
                            "type": "keyword"
                        }
                    }
                },
                "resource.attributes": {
                    "type": "passthrough",
                    "priority": 20,
                    "properties": {
                        "id": {
                            "type": "keyword"
                        }
                    }
                }
            }
        },
    )
    print(resp)
    const response = await client.indices.create({
      index: "my-index-000002",
      mappings: {
        properties: {
          attributes: {
            type: "passthrough",
            priority: 10,
            properties: {
              id: {
                type: "keyword",
              },
            },
          },
          "resource.attributes": {
            type: "passthrough",
            priority: 20,
            properties: {
              id: {
                type: "keyword",
              },
            },
          },
        },
      },
    });
    console.log(response);
    PUT my-index-000002
    {
      "mappings": {
        "properties": {
          "attributes": {
            "type": "passthrough",
            "priority": 10,
            "properties": {
              "id": {
                "type": "keyword"
              }
            }
          },
          "resource.attributes": {
            "type": "passthrough",
            "priority": 20,
            "properties": {
              "id": {
                "type": "keyword"
              }
            }
          }
        }
      }
    }

    В этом случае параметр priority используется для разрешения конфликтов, при этом поля с более высокими значениями имеют приоритет. В приведенном примере resource.attributes имеет более высокий приоритет, чем attributes, поэтому ссылки на id указывают на поле внутри resource.attributes. attributes.id все еще может быть доступен по полному пути.

Определение подполей в качестве измерений временных рядов

Можно настроить поле «пропускающее» в качестве контейнера для измерений временных рядов. В этом случае все подполя получают одинаковый параметр под капотом, и они также включаются в пути маршрутизации и вычисления tsid, упрощая настройку TSDS:

resp = client.indices.put_index_template(
    name="my-metrics",
    index_patterns=[
        "metrics-mymetrics-*"
    ],
    priority=200,
    data_stream={},
    template={
        "settings": {
            "index.mode": "time_series"
        },
        "mappings": {
            "properties": {
                "attributes": {
                    "type": "passthrough",
                    "priority": 10,
                    "time_series_dimension": True,
                    "properties": {
                        "host.name": {
                            "type": "keyword"
                        }
                    }
                },
                "cpu": {
                    "type": "integer",
                    "time_series_metric": "counter"
                }
            }
        }
    },
)
print(resp)

resp1 = client.index(
    index="metrics-mymetrics-test",
    document={
        "@timestamp": "2020-01-01T00:00:00.000Z",
        "attributes": {
            "host.name": "foo",
            "zone": "bar"
        },
        "cpu": 10
    },
)
print(resp1)
const response = await client.indices.putIndexTemplate({
  name: "my-metrics",
  index_patterns: ["metrics-mymetrics-*"],
  priority: 200,
  data_stream: {},
  template: {
    settings: {
      "index.mode": "time_series",
    },
    mappings: {
      properties: {
        attributes: {
          type: "passthrough",
          priority: 10,
          time_series_dimension: true,
          properties: {
            "host.name": {
              type: "keyword",
            },
          },
        },
        cpu: {
          type: "integer",
          time_series_metric: "counter",
        },
      },
    },
  },
});
console.log(response);

const response1 = await client.index({
  index: "metrics-mymetrics-test",
  document: {
    "@timestamp": "2020-01-01T00:00:00.000Z",
    attributes: {
      "host.name": "foo",
      zone: "bar",
    },
    cpu: 10,
  },
});
console.log(response1);
PUT _index_template/my-metrics
{
  "index_patterns": ["metrics-mymetrics-*"],
  "priority": 200,
  "data_stream": { },
  "template": {
    "settings": {
      "index.mode": "time_series"
    },
    "mappings": {
      "properties": {
        "attributes": {
          "type": "passthrough",
          "priority": 10,
          "time_series_dimension": true,
          "properties": {
            "host.name": {
              "type": "keyword"
            }
          }
        },
        "cpu": {
          "type": "integer",
          "time_series_metric": "counter"
        }
      }
    }
  }
}

POST metrics-mymetrics-test/_doc
{
  "@timestamp": "2020-01-01T00:00:00.000Z",
  "attributes" : {
    "host.name": "foo",
    "zone": "bar"
  },
  "cpu": 10
}

В приведенном примере attributes определяется как контейнер измерений. Его подполя host.name (статическое) и zone (динамическое) включаются в путь маршрутизации и tsid и могут быть указаны в запросах без префикса attributes..

Автоматическое сглаживание подполей

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

Параметры для полей passthrough

Следующие параметры принимаются полями passthrough:

priority

(Обязательно) используется для разрешения конфликтов имен между пропускающими полями. Поле с наибольшим значением выигрывает. Принимает целые неотрицательные значения.

time_series_dimension

Следует ли рассматривать подполя как измерения временных рядов. Принимает false (по умолчанию) или true.

dynamic

Следует ли добавлять новые properties динамически к существующему объекту. Принимает true (по умолчанию), runtime, false и strict.

enabled

Следует ли анализировать и индексировать JSON-значение, заданное для поля объекта (true, по умолчанию), или полностью игнорировать его (false).

properties

Поля внутри объекта, которые могут быть любого типа данных, включая object. Новые свойства могут быть добавлены к существующему объекту.

Если вам нужно индексировать массивы объектов вместо отдельных объектов, сначала ознакомьтесь с Вложенными.

© 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/passthrough.html

Spec-Zone.ru

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