Spec-Zone.ru › Elasticsearch 8
›Руководство по Elasticsearch [8.17]

Псевдонимы

Псевдоним указывает на один или несколько индексов или потоков данных. Большинство API Elasticsearch принимают псевдоним вместо имени потока данных или индекса.

Псевдонимы позволяют:

  • Запрашивать несколько индексов/потоков данных вместе под одним именем
  • Изменять используемые вашим приложением индексы/потоки данных в реальном времени
  • Переиндексировать данные без простоев

Типы псевдонимов

Существует два типа псевдонимов:

  • Псевдоним потока данных указывает на один или несколько потоков данных.
  • Псевдоним индекса указывает на один или несколько индексов.

Псевдоним не может указывать одновременно на потоки данных и индексы. Вы также не можете добавить базовый индекс потока данных к псевдониму индекса.

Добавление псевдонима

Чтобы добавить существующий поток данных или индекс к псевдониму, используйте действие API псевдонимов add. Если псевдоним не существует, запрос его создаст.

resp = client.indices.update_aliases(
    actions=[
        {
            "add": {
                "index": "logs-nginx.access-prod",
                "alias": "logs"
            }
        }
    ],
)
print(resp)
response = client.indices.update_aliases(
  body: {
    actions: [
      {
        add: {
          index: 'logs-nginx.access-prod',
          alias: 'logs'
        }
      }
    ]
  }
)
puts response
const response = await client.indices.updateAliases({
  actions: [
    {
      add: {
        index: "logs-nginx.access-prod",
        alias: "logs",
      },
    },
  ],
});
console.log(response);
POST _aliases
{
  "actions": [
    {
      "add": {
        "index": "logs-nginx.access-prod",
        "alias": "logs"
      }
    }
  ]
}

Параметры API index и indices поддерживают подстановочные знаки (*). Шаблоны подстановочных знаков, которые соответствуют как потокам данных, так и индексам, возвращают ошибку.

resp = client.indices.update_aliases(
    actions=[
        {
            "add": {
                "index": "logs-*",
                "alias": "logs"
            }
        }
    ],
)
print(resp)
const response = await client.indices.updateAliases({
  actions: [
    {
      add: {
        index: "logs-*",
        alias: "logs",
      },
    },
  ],
});
console.log(response);
POST _aliases
{
  "actions": [
    {
      "add": {
        "index": "logs-*",
        "alias": "logs"
      }
    }
  ]
}

Удаление псевдонима

Чтобы удалить псевдоним, используйте действие API псевдонимов remove.

resp = client.indices.update_aliases(
    actions=[
        {
            "remove": {
                "index": "logs-nginx.access-prod",
                "alias": "logs"
            }
        }
    ],
)
print(resp)
response = client.indices.update_aliases(
  body: {
    actions: [
      {
        remove: {
          index: 'logs-nginx.access-prod',
          alias: 'logs'
        }
      }
    ]
  }
)
puts response
const response = await client.indices.updateAliases({
  actions: [
    {
      remove: {
        index: "logs-nginx.access-prod",
        alias: "logs",
      },
    },
  ],
});
console.log(response);
POST _aliases
{
  "actions": [
    {
      "remove": {
        "index": "logs-nginx.access-prod",
        "alias": "logs"
      }
    }
  ]
}

Несколько действий

Вы можете использовать API псевдонимов для выполнения нескольких действий в одной атомарной операции.

Например, псевдоним logs указывает на один поток данных. Следующий запрос меняет поток для псевдонима. Во время этой замены у псевдонима logs нет простоев и он никогда не указывает на оба потока одновременно.

resp = client.indices.update_aliases(
    actions=[
        {
            "remove": {
                "index": "logs-nginx.access-prod",
                "alias": "logs"
            }
        },
        {
            "add": {
                "index": "logs-my_app-default",
                "alias": "logs"
            }
        }
    ],
)
print(resp)
response = client.indices.update_aliases(
  body: {
    actions: [
      {
        remove: {
          index: 'logs-nginx.access-prod',
          alias: 'logs'
        }
      },
      {
        add: {
          index: 'logs-my_app-default',
          alias: 'logs'
        }
      }
    ]
  }
)
puts response
const response = await client.indices.updateAliases({
  actions: [
    {
      remove: {
        index: "logs-nginx.access-prod",
        alias: "logs",
      },
    },
    {
      add: {
        index: "logs-my_app-default",
        alias: "logs",
      },
    },
  ],
});
console.log(response);
POST _aliases
{
  "actions": [
    {
      "remove": {
        "index": "logs-nginx.access-prod",
        "alias": "logs"
      }
    },
    {
      "add": {
        "index": "logs-my_app-default",
        "alias": "logs"
      }
    }
  ]
}

Результаты нескольких действий

При использовании нескольких действий, если некоторые из них завершаются успешно, а некоторые — нет, будет возвращён список результатов по каждому действию.

Рассмотрим похожий список действий, как в предыдущем примере, но теперь с псевдонимом log-non-existing, который ещё не существует. В этом случае действие remove завершится неудачно, но действие add завершится успешно. Ответ будет содержать список action_results с результатом для каждого запрошенного действия.

resp = client.indices.update_aliases(
    actions=[
        {
            "remove": {
                "index": "index1",
                "alias": "logs-non-existing"
            }
        },
        {
            "add": {
                "index": "index2",
                "alias": "logs-non-existing"
            }
        }
    ],
)
print(resp)
response = client.indices.update_aliases(
  body: {
    actions: [
      {
        remove: {
          index: 'index1',
          alias: 'logs-non-existing'
        }
      },
      {
        add: {
          index: 'index2',
          alias: 'logs-non-existing'
        }
      }
    ]
  }
)
puts response
const response = await client.indices.updateAliases({
  actions: [
    {
      remove: {
        index: "index1",
        alias: "logs-non-existing",
      },
    },
    {
      add: {
        index: "index2",
        alias: "logs-non-existing",
      },
    },
  ],
});
console.log(response);
POST _aliases
{
  "actions": [
    {
      "remove": {
        "index": "index1",
        "alias": "logs-non-existing"
      }
    },
    {
      "add": {
        "index": "index2",
        "alias": "logs-non-existing"
      }
    }
  ]
}

API возвращает следующий результат:

{
  "acknowledged": true,
  "errors": true,
  "action_results": [
    {
      "action": {
        "type": "remove",
        "indices": [ "index1" ],
        "aliases": [ "logs-non-existing" ],
      },
      "status": 404,
      "error": {
        "type": "aliases_not_found_exception",
        "reason": "aliases [logs-non-existing] missing",
        "resource.type": "aliases",
        "resource.id": "logs-non-existing"
      }
    },
    {
      "action": {
        "type": "add",
        "indices": [ "index2" ],
        "aliases": [ "logs-non-existing" ],
      },
      "status": 200
    }
  ]
}

Разрешение списку действий завершиться частично может не обеспечить желаемого результата. Может быть более целесообразно установить must_exist на true, что приведёт к отказу всего списка действий, если одно из действий завершится неудачно.

Добавление псевдонима при создании индекса

Также можно использовать компонент или шаблон индекса, чтобы добавить псевдонимы индексов или потоков данных при их создании.

resp = client.cluster.put_component_template(
    name="my-aliases",
    template={
        "aliases": {
            "my-alias": {}
        }
    },
)
print(resp)

resp1 = client.indices.put_index_template(
    name="my-index-template",
    index_patterns=[
        "my-index-*"
    ],
    composed_of=[
        "my-aliases",
        "my-mappings",
        "my-settings"
    ],
    template={
        "aliases": {
            "yet-another-alias": {}
        }
    },
)
print(resp1)
response = client.cluster.put_component_template(
  name: 'my-aliases',
  body: {
    template: {
      aliases: {
        "my-alias": {}
      }
    }
  }
)
puts response

response = client.indices.put_index_template(
  name: 'my-index-template',
  body: {
    index_patterns: [
      'my-index-*'
    ],
    composed_of: [
      'my-aliases',
      'my-mappings',
      'my-settings'
    ],
    template: {
      aliases: {
        "yet-another-alias": {}
      }
    }
  }
)
puts response
const response = await client.cluster.putComponentTemplate({
  name: "my-aliases",
  template: {
    aliases: {
      "my-alias": {},
    },
  },
});
console.log(response);

const response1 = await client.indices.putIndexTemplate({
  name: "my-index-template",
  index_patterns: ["my-index-*"],
  composed_of: ["my-aliases", "my-mappings", "my-settings"],
  template: {
    aliases: {
      "yet-another-alias": {},
    },
  },
});
console.log(response1);
# Component template with index aliases
PUT _component_template/my-aliases
{
  "template": {
    "aliases": {
      "my-alias": {}
    }
  }
}

# Index template with index aliases
PUT _index_template/my-index-template
{
  "index_patterns": [
    "my-index-*"
  ],
  "composed_of": [
    "my-aliases",
    "my-mappings",
    "my-settings"
  ],
  "template": {
    "aliases": {
      "yet-another-alias": {}
    }
  }
}

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

resp = client.indices.create(
    index="<my-index-{now/d}-000001>",
    aliases={
        "my-alias": {}
    },
)
print(resp)
response = client.indices.create(
  index: '<my-index-{now/d}-000001>',
  body: {
    aliases: {
      "my-alias": {}
    }
  }
)
puts response
const response = await client.indices.create({
  index: "<my-index-{now/d}-000001>",
  aliases: {
    "my-alias": {},
  },
});
console.log(response);
# PUT <my-index-{now/d}-000001>
PUT %3Cmy-index-%7Bnow%2Fd%7D-000001%3E
{
  "aliases": {
    "my-alias": {}
  }
}

Просмотр псевдонимов

Чтобы получить список псевдонимов вашего кластера, используйте API получения псевдонима без аргументов.

resp = client.indices.get_alias()
print(resp)
response = client.indices.get_alias
puts response
const response = await client.indices.getAlias();
console.log(response);
GET _alias

Укажите поток данных или индекс перед _alias, чтобы просмотреть его псевдонимы.

resp = client.indices.get_alias(
    index="my-data-stream",
)
print(resp)
response = client.indices.get_alias(
  index: 'my-data-stream'
)
puts response
const response = await client.indices.getAlias({
  index: "my-data-stream",
});
console.log(response);
GET my-data-stream/_alias

Укажите псевдоним после _alias, чтобы просмотреть его потоки данных или индексы.

resp = client.indices.get_alias(
    name="logs",
)
print(resp)
response = client.indices.get_alias(
  name: 'logs'
)
puts response
const response = await client.indices.getAlias({
  name: "logs",
});
console.log(response);
GET _alias/logs

Запись в индекс

Вы можете использовать is_write_index для указания индекса или потока данных записи для псевдонима. Elasticsearch маршрутизирует все запросы записи для псевдонима в этот индекс или поток данных.

resp = client.indices.update_aliases(
    actions=[
        {
            "add": {
                "index": "logs-nginx.access-prod",
                "alias": "logs"
            }
        },
        {
            "add": {
                "index": "logs-my_app-default",
                "alias": "logs",
                "is_write_index": True
            }
        }
    ],
)
print(resp)
response = client.indices.update_aliases(
  body: {
    actions: [
      {
        add: {
          index: 'logs-nginx.access-prod',
          alias: 'logs'
        }
      },
      {
        add: {
          index: 'logs-my_app-default',
          alias: 'logs',
          is_write_index: true
        }
      }
    ]
  }
)
puts response
const response = await client.indices.updateAliases({
  actions: [
    {
      add: {
        index: "logs-nginx.access-prod",
        alias: "logs",
      },
    },
    {
      add: {
        index: "logs-my_app-default",
        alias: "logs",
        is_write_index: true,
      },
    },
  ],
});
console.log(response);
POST _aliases
{
  "actions": [
    {
      "add": {
        "index": "logs-nginx.access-prod",
        "alias": "logs"
      }
    },
    {
      "add": {
        "index": "logs-my_app-default",
        "alias": "logs",
        "is_write_index": true
      }
    }
  ]
}

Если псевдоним указывает на несколько индексов или потоков данных и is_write_index не задано, псевдоним отклоняет запросы записи. Если псевдоним индекса указывает на один индекс и is_write_index не задано, индекс автоматически выступает в качестве индекса записи. Псевдонимы потоков данных не автоматически устанавливают поток данных записи, даже если псевдоним указывает на один поток данных.

Рекомендуется использовать потоки данных для хранения данных временных рядов с добавлением только новых данных. Если вам необходимо обновлять или удалять существующие данные временных рядов, вы можете выполнить операции обновления или удаления непосредственно на базовом индексе потока данных. Если вы часто отправляете несколько документов, используя тот же _id, ожидая последней записи, вы можете использовать псевдоним индекса с индексом записи. См. Управление данными временных рядов без потоков данных.

Фильтр псевдонима

Параметр filter использует Query DSL для ограничения документов, к которым может получить доступ псевдоним.

resp = client.indices.update_aliases(
    actions=[
        {
            "add": {
                "index": "my-index-2099.05.06-000001",
                "alias": "my-alias",
                "filter": {
                    "bool": {
                        "filter": [
                            {
                                "range": {
                                    "@timestamp": {
                                        "gte": "now-1d/d",
                                        "lt": "now/d"
                                    }
                                }
                            },
                            {
                                "term": {
                                    "user.id": "kimchy"
                                }
                            }
                        ]
                    }
                }
            }
        }
    ],
)
print(resp)
response = client.indices.update_aliases(
  body: {
    actions: [
      {
        add: {
          index: 'my-index-2099.05.06-000001',
          alias: 'my-alias',
          filter: {
            bool: {
              filter: [
                {
                  range: {
                    "@timestamp": {
                      gte: 'now-1d/d',
                      lt: 'now/d'
                    }
                  }
                },
                {
                  term: {
                    'user.id' => 'kimchy'
                  }
                }
              ]
            }
          }
        }
      }
    ]
  }
)
puts response
const response = await client.indices.updateAliases({
  actions: [
    {
      add: {
        index: "my-index-2099.05.06-000001",
        alias: "my-alias",
        filter: {
          bool: {
            filter: [
              {
                range: {
                  "@timestamp": {
                    gte: "now-1d/d",
                    lt: "now/d",
                  },
                },
              },
              {
                term: {
                  "user.id": "kimchy",
                },
              },
            ],
          },
        },
      },
    },
  ],
});
console.log(response);
POST _aliases
{
  "actions": [
    {
      "add": {
        "index": "my-index-2099.05.06-000001",
        "alias": "my-alias",
        "filter": {
          "bool": {
            "filter": [
              {
                "range": {
                  "@timestamp": {
                    "gte": "now-1d/d",
                    "lt": "now/d"
                  }
                }
              },
              {
                "term": {
                  "user.id": "kimchy"
                }
              }
            ]
          }
        }
      }
    }
  ]
}

Фильтры применяются только при использовании Query DSL и не применяются при получении документа по ID.

Маршрутизация

Используйте параметр routing для маршрутизации запросов для псевдонима на определённый фрагмент. Это позволяет использовать кэши запросов фрагментов для ускорения поиска. Псевдонимы потоков данных не поддерживают параметры маршрутизации.

resp = client.indices.update_aliases(
    actions=[
        {
            "add": {
                "index": "my-index-2099.05.06-000001",
                "alias": "my-alias",
                "routing": "1"
            }
        }
    ],
)
print(resp)
response = client.indices.update_aliases(
  body: {
    actions: [
      {
        add: {
          index: 'my-index-2099.05.06-000001',
          alias: 'my-alias',
          routing: '1'
        }
      }
    ]
  }
)
puts response
const response = await client.indices.updateAliases({
  actions: [
    {
      add: {
        index: "my-index-2099.05.06-000001",
        alias: "my-alias",
        routing: "1",
      },
    },
  ],
});
console.log(response);
POST _aliases
{
  "actions": [
    {
      "add": {
        "index": "my-index-2099.05.06-000001",
        "alias": "my-alias",
        "routing": "1"
      }
    }
  ]
}

Используйте index_routing и search_routing для указания разных значений маршрутизации для индексирования и поиска. При указании эти параметры переопределяют значение routing для соответствующих операций.

resp = client.indices.update_aliases(
    actions=[
        {
            "add": {
                "index": "my-index-2099.05.06-000001",
                "alias": "my-alias",
                "search_routing": "1",
                "index_routing": "2"
            }
        }
    ],
)
print(resp)
response = client.indices.update_aliases(
  body: {
    actions: [
      {
        add: {
          index: 'my-index-2099.05.06-000001',
          alias: 'my-alias',
          search_routing: '1',
          index_routing: '2'
        }
      }
    ]
  }
)
puts response
const response = await client.indices.updateAliases({
  actions: [
    {
      add: {
        index: "my-index-2099.05.06-000001",
        alias: "my-alias",
        search_routing: "1",
        index_routing: "2",
      },
    },
  ],
});
console.log(response);
POST _aliases
{
  "actions": [
    {
      "add": {
        "index": "my-index-2099.05.06-000001",
        "alias": "my-alias",
        "search_routing": "1",
        "index_routing": "2"
      }
    }
  ]
}

Удаление индекса

Чтобы удалить индекс, используйте действие API псевдонимов remove_index.

resp = client.indices.update_aliases(
    actions=[
        {
            "remove_index": {
                "index": "my-index-2099.05.06-000001"
            }
        }
    ],
)
print(resp)
const response = await client.indices.updateAliases({
  actions: [
    {
      remove_index: {
        index: "my-index-2099.05.06-000001",
      },
    },
  ],
});
console.log(response);
POST _aliases
{
  "actions": [
    {
      "remove_index": {
        "index": "my-index-2099.05.06-000001"
      }
    }
  ]
}

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

Spec-Zone.ru

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