跳到主要内容

索引别名 alias

Index Aliases

别名可以理解为指向多个索引的一个引用,类似于数据的视图,常见的使用场景

  • 查询指向别名,使用别名任意切换后端的索引对比搜索效果。
  • 一组按天翻滚的索引,写入别名指向当天索引,查询别名为所有索引。
  • 字段发生变更,在数据重建后将别名切换到新索引。
提示

索引的别名让我们可以以视图的方式来操作多个索引,这个视图可是多个索引,也可是一个索引或索引的一部分。

新建别名

POST /_aliases
{
"actions" : [
{ "add" : { "index" : "test1", "alias" : "alias1" } }
]
}

删除别名

POST /_aliases
{
"actions" : [
{ "remove" : { "index" : "test1", "alias" : "alias1" } }
]
}

重命名别名

POST /_aliases
{
"actions" : [
{ "remove" : { "index" : "test1", "alias" : "alias1" } },
{ "add" : { "index" : "test2", "alias" : "alias1" } }
]
}

多个添加别名操作

POST /_aliases
{
"actions" : [
{ "add" : { "index" : "test1", "alias" : "alias1" } },
{ "add" : { "index" : "test2", "alias" : "alias1" } }
]
}

为同一个索引添加多个别名

# 数组方式
POST /_aliases
{
"actions" : [
{ "add" : { "indices" : ["test1", "test2"], "alias" : "alias1" } }
]
}

# 通配符方式
POST /_aliases
{
"actions" : [
{ "add" : { "index" : "test*", "alias" : "all_test_indices" } }
]
}

Filtered Aliases

带有filters的别名提供了创建同一索引的不同“视图”。可以使用查询DSL定义filter,并将其应用于具有此别名的所有Search、Count、Delete By Query和其他类似操作。

要创建Filtered Aliases,首先需要确保mapping中已经存在字段

PUT /test1
{
"mappings": {
"_doc": {
"properties": {
"user" : {
"type": "keyword"
}
}
}
}
}

现在,我们可以创建一个对字段user使用过滤器的别名:

POST /_aliases
{
"actions" : [
{
"add" : {
"index" : "test1",
"alias" : "alias2",
"filter" : { "term" : { "user" : "kimchy" } }
}
}
]
}

Write Index

可以将别名指向的索引关联为写索引。指定后,针对指向多个索引的别名的所有索引和更新请求都将尝试解析为一个索引,即写索引。每次只能为每个别名分配一个索引作为写索引。如果未指定写入索引,并且别名引用了多个索引,则不允许写入。

可以使用别名API和索引创建API将与别名关联的索引指定为写索引。

POST /_aliases
{
"actions" : [
{
"add" : {
"index" : "test",
"alias" : "alias1",
"is_write_index" : true
}
},
{
"add" : {
"index" : "test2",
"alias" : "alias1"
}
}
]
}

在本例中,我们将别名alias1与test和test2相关联,其中test为写入的索引。

PUT /alias1/_doc/1
{
"foo": "bar"
}

索引为/alias1/doc/1的新文档将被索引为/test/doc/1。

GET /test/_doc/1

要交换别名的写索引,可以利用别名API进行原子交换。

POST /_aliases
{
"actions" : [
{
"add" : {
"index" : "test",
"alias" : "alias1",
"is_write_index" : false
}
}, {
"add" : {
"index" : "test2",
"alias" : "alias1",
"is_write_index" : true
}
}
]
}

添加单个别名

PUT /{index}/_alias/{name}

参数说明
index别名引用的索引. 可以是 * 、 _all 、name1, name2, …
name别名名称
routing(可选)与别名关联的routing
filter(可选)与别名关联的filter

例子

单索引别名

PUT /logs_201305/_alias/2013

filter

PUT /users
{
"mappings" : {
"_doc" : {
"properties" : {
"user_id" : {"type" : "integer"}
}
}
}
}

PUT /users/_alias/user_12
{
"routing" : "12",
"filter" : {
"term" : {
"user_id" : 12
}
}
}

在创建索引期间指定别名

PUT /logs_20162801
{
"mappings" : {
"_doc" : {
"properties" : {
"year" : {"type" : "integer"}
}
}
},
"aliases" : {
"current_day" : {},
"2016" : {
"filter" : {
"term" : {"year" : 2016 }
}
}
}
}

删除索引别名

DELETE /logs_20162801/_alias/current_day