Elaticsearch 索引模板

以关系型数据表 customer 表为例,按每个月创建索引并归档数据

create table customer
(
    user_name varchar(100),
    email varchar(100)
);

单索引模板与别名创建

  • 执行索引创建脚本,其中包含别名:customer_alias,索引字段结构
PUT index_template/customer_template 
{
    "priority": 200,
    "index_patterns": [
        "customer*"
    ],
    "template": {
        "aliases": {
            "customer_alias": {}
        },
        "mappings": {
            "properties": {
                "user_name": {
                    "type": "keyword"
                },
                "email": {
                    "type": "keyword"
                }
            }
        }
    }
}
  • 创建customer 2020年1月的索引,索引创建后会自动关联别名
PUT /customer_202001
{
    "priority": 200,
    "index_patterns": [
        "customer_*"
    ],
    "template": {
        "aliases": {
            "customer_alias": {}
        },
        "mappings": {
            "properties": {
                "user_name": {
                    "type": "keyword"
                },
                "email": {
                    "type": "keyword"
                }
            }
        }
    }
}
  • 查看索引结构
GET /customer_202001

创建具有索引生命周期的索引模板

  • 索引生命周期:

    • Hot Phase
    • Warm phase
    • Cold Phase
    • Delete phase
  • 设置索引刷新频率为5秒

PUT _cluster/settings
{
    "persistent": {
        "indices.lifecycle.poll_interval": "5s"
    }
}
  • 创建索引生命周期 customer_policy

  • 执行具有索引生命周期的索引模板创建脚本

PUT index_template/customer_template 
{
    "priority": 200,
    "index_patterns": [
        "customer_*"
    ],
    "template": {
        "settings": {
            "index": {
                "lifecycle": {
                    "name": "customer_policy",
                    "rollover_alias": "customer_alias"
                },
                "number_of_shards": "3",
                "number_of_replicas": "1"
            }
        },
        "aliases": {
            "customer_alias": {}
        },
        "mappings": {
            "properties": {
                "user_name": {
                    "type": "keyword"
                },
                "email": {
                    "type": "keyword"
                }
            }
        }
    }
}