elasticsearch 中的 API 在处理某个或某几个索引时可以接受索引名。索引别名API可以对索引命名,其它API会自动将别名转换成真正的索引。一个别名也可以对应多个索引,在定义时,别名会自动扩展其名下的索引列表。别名也可以关联到filter,在搜索时会自动转换。别名也可以和路由值关联。
下面是为索引 test1 创建别名 alias1 的例子 :
curl -XPOST 'http://localhost:9200/_aliases' -d '
{
    "actions" : [
        { "add" : { "index" : "test1", "alias" : "alias1" } }
    ]
}'
别名也可以去掉, 比如:
curl -XPOST 'http://localhost:9200/_aliases' -d '
{
    "actions" : [
        { "remove" : { "index" : "test1", "alias" : "alias1" } }
    ]
}'
索引的重命名就是在同一个APi中先 remove 之后再 add :
curl -XPOST 'http://localhost:9200/_aliases' -d '
{
    "actions" : [
        { "remove" : { "index" : "test1", "alias" : "alias1" } },
        { "add" : { "index" : "test1", "alias" : "alias2" } }
    ]
}'
将别名对应到多个索引就是执行多个 add 动作:
curl -XPOST 'http://localhost:9200/_aliases' -d '
{
    "actions" : [
        { "add" : { "index" : "test1", "alias" : "alias1" } },
        { "add" : { "index" : "test2", "alias" : "alias1" } }
    ]
}'
为指向多个索引的别名创建索引是错误的。
别名过滤
带有filters的别名可以很容易的实现同一索引的不同“视图”。filter可以用Query DSL定义,并且适用于该别名的所有查询、计数、删除查询结果集等操作。比如:
curl -XPOST 'http://localhost:9200/_aliases' -d '
{
    "actions" : [
        {
            "add" : {
                 "index" : "test1",
                 "alias" : "alias2",
                 "filter" : { "term" : { "user" : "kimchy" } }
            }
        }
    ]
}'
路由
路由值也可以关联到别名。这个特性可以和filtering 别名共同使用,以避免非必要的shard操作。
下面的命令创建了指向索引 test 的新别名 alias1 。在 alias1 创建成功后, 所有与该别名有关的操作都自动使用路由 1 :
curl -XPOST 'http://localhost:9200/_aliases' -d '
{
    "actions" : [
        {
            "add" : {
                 "index" : "test",
                 "alias" : "alias1",
                 "routing" : "1"
            }
        }
    ]
}'
也可以针对查询和索引操作指定不同的路由:
curl -XPOST 'http://localhost:9200/_aliases' -d '
{
    "actions" : [
        {
            "add" : {
                 "index" : "test",
                 "alias" : "alias2",
                 "search_routing" : "1,2",
                 "index_routing" : "2"
            }
        }
    ]
}'
如上例所示, 搜索路由可包括多个,有逗号分隔。索引路由必须唯一。
如果操作中既有路由别名也有路由参数,会使用它们的交集。比如下例中会用 “2” 作为路由值:
curl -XGET 'http://localhost:9200/alias2/_search?q=user:kimchy&routing=2,3'
获取现有别名
可以通过get API 获取现有的别名, 既可以查询所有索引对应的全部别名,也可以查询特定索引对应的别名:
curl -XGET 'localhost:9200/test/_aliases' curl -XGET 'localhost:9200/test1,test2/_aliases' curl -XGET 'localhost:9200/_aliases'
