ES中索引模板有什么作用?

  • A+
所属分类:全文检索

当您使用 Elasticsearch 索引模板时,可以为新创建的索引指定一组默认的映射和设置,而无需手动为每个新索引设置相同的设置。以下是一些索引模板的示例用途和作用:

  1. 默认映射和设置

假设您的应用程序需要存储大量的日志数据,并且您希望将其存储在 Elasticsearch 中以便进行搜索和分析。在这种情况下,您可以创建一个索引模板,将其中包含的默认映射应用于所有新创建的索引。例如,以下索引模板将日期类型映射应用于所有新索引:

  1. PUT _template/logs_template
  2. {
  3. "index_patterns": ["logs-*"],
  4. "settings": {
  5. "number_of_shards": 1
  6. },
  7. "mappings": {
  8. "properties": {
  9. "timestamp": {
  10. "type": "date"
  11. }
  12. }
  13. }
  14. }
PUT _template/logs_template
{
  "index_patterns": ["logs-*"],
  "settings": {
    "number_of_shards": 1
  },
  "mappings": {
    "properties": {
      "timestamp": {
        "type": "date"
      }
    }
  }
}

此模板定义了一个匹配 logs-* 模式的索引模板,它将在所有 logs-* 开头的新索引中应用。该模板定义了默认的 number_of_shards 设置为 1,并为 timestamp 字段定义了日期类型的映射。

  1. 自动设置别名

假设您的应用程序需要使用别名来引用多个索引,并且您希望自动将新创建的索引添加到特定的别名中。在这种情况下,您可以创建一个索引模板,并在其中指定要自动添加到别名的索引。例如,以下索引模板将新创建的索引自动添加到名为 logs 的别名中:

  1. PUT _template/logs_template
  2. {
  3. "index_patterns": ["logs-*"],
  4. "aliases": {
  5. "logs": {}
  6. }
  7. }
PUT _template/logs_template
{
  "index_patterns": ["logs-*"],
  "aliases": {
    "logs": {}
  }
}

此模板定义了一个匹配 logs-* 模式的索引模板,它将在所有 logs-* 开头的新索引中应用。该模板定义了一个别名 logs,它将自动添加到所有新索引中。

  1. 根据索引名称匹配规则

假设您的应用程序需要存储来自不同客户的数据,并且您希望根据客户名称将数据存储在不同的索引中。在这种情况下,您可以创建一个索引模板,并在其中指定匹配索引名称的规则。例如,以下索引模板将新创建的索引自动命名为 customer-<customer_id>,其中 <customer_id> 是从索引名称中提取的值:

  1. PUT _template/customer_template
  2. {
  3. "index_patterns": ["customer-*"],
  4. "settings": {
  5. "number_of_shards": 1
  6. },
  7. "mappings": {
  8. "properties": {
  9. "timestamp": {
  10. "type": "date"
  11. }
  12. }
  13. },
  14. "index_patterns": [
  15. "customer-*"
  16. ],
  17. "index": {
  18. "routing": {
  19. "required": true,
  20. "path": "customer_id"
PUT _template/customer_template
{
  "index_patterns": ["customer-*"],
  "settings": {
    "number_of_shards": 1
  },
  "mappings": {
    "properties": {
      "timestamp": {
        "type": "date"
      }
    }
  },
  "index_patterns": [
    "customer-*"
  ],
  "index": {
    "routing": {
      "required": true,
      "path": "customer_id"