Spec-Zone.ru › Elasticsearch 8
›Elasticsearch Guide [8.17] ›Query DSL ›Объединение запросов

Запрос по идентификатору родителя

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

Пример запроса

Настройка индекса

Для использования запроса parent_id ваш индекс должен содержать отображение поля соединения. Чтобы увидеть, как настроить индекс для запроса parent_id, попробуйте следующий пример.

  1. Создайте индекс с отображением поля соединения.

    resp = client.indices.create(
        index="my-index-000001",
        mappings={
            "properties": {
                "my-join-field": {
                    "type": "join",
                    "relations": {
                        "my-parent": "my-child"
                    }
                }
            }
        },
    )
    print(resp)
    response = client.indices.create(
      index: 'my-index-000001',
      body: {
        mappings: {
          properties: {
            "my-join-field": {
              type: 'join',
              relations: {
                "my-parent": 'my-child'
              }
            }
          }
        }
      }
    )
    puts response
    const response = await client.indices.create({
      index: "my-index-000001",
      mappings: {
        properties: {
          "my-join-field": {
            type: "join",
            relations: {
              "my-parent": "my-child",
            },
          },
        },
      },
    });
    console.log(response);
    PUT /my-index-000001
    {
      "mappings": {
        "properties": {
          "my-join-field": {
            "type": "join",
            "relations": {
              "my-parent": "my-child"
            }
          }
        }
      }
    }
  2. Индексируйте родительский документ с идентификатором 1.

    resp = client.index(
        index="my-index-000001",
        id="1",
        refresh=True,
        document={
            "text": "This is a parent document.",
            "my-join-field": "my-parent"
        },
    )
    print(resp)
    response = client.index(
      index: 'my-index-000001',
      id: 1,
      refresh: true,
      body: {
        text: 'This is a parent document.',
        "my-join-field": 'my-parent'
      }
    )
    puts response
    const response = await client.index({
      index: "my-index-000001",
      id: 1,
      refresh: "true",
      document: {
        text: "This is a parent document.",
        "my-join-field": "my-parent",
      },
    });
    console.log(response);
    PUT /my-index-000001/_doc/1?refresh
    {
      "text": "This is a parent document.",
      "my-join-field": "my-parent"
    }
  3. Индексируйте дочерний документ родительского документа.

    resp = client.index(
        index="my-index-000001",
        id="2",
        routing="1",
        refresh=True,
        document={
            "text": "This is a child document.",
            "my-join-field": {
                "name": "my-child",
                "parent": "1"
            }
        },
    )
    print(resp)
    const response = await client.index({
      index: "my-index-000001",
      id: 2,
      routing: 1,
      refresh: "true",
      document: {
        text: "This is a child document.",
        "my-join-field": {
          name: "my-child",
          parent: "1",
        },
      },
    });
    console.log(response);
    PUT /my-index-000001/_doc/2?routing=1&refresh
    {
      "text": "This is a child document.",
      "my-join-field": {
        "name": "my-child",
        "parent": "1"
      }
    }

Пример запроса

Следующий запрос возвращает дочерние документы для родительского документа с идентификатором 1.

resp = client.search(
    index="my-index-000001",
    query={
        "parent_id": {
            "type": "my-child",
            "id": "1"
        }
    },
)
print(resp)
const response = await client.search({
  index: "my-index-000001",
  query: {
    parent_id: {
      type: "my-child",
      id: "1",
    },
  },
});
console.log(response);
GET /my-index-000001/_search
{
  "query": {
      "parent_id": {
          "type": "my-child",
          "id": "1"
      }
  }
}

Параметры верхнего уровня для parent_id

type
(Обязательно, строка) Название отображения дочерних отношений для поля соединения.
id
(Обязательно, строка) Идентификатор родительского документа. Запрос вернёт дочерние документы этого родительского документа.
ignore_unmapped

(Необязательно, логическое значение) Указывает, игнорировать ли неотображенное поле type и не возвращать документы, а вместо этого выдать ошибку. По умолчанию false.

Если false, Elasticsearch вернёт ошибку, если поле type не отображено.

Можно использовать этот параметр для запроса нескольких индексов, которые могут не содержать поле type.

© 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/query-dsl-parent-id-query.html

Spec-Zone.ru

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