索引别名
在 Elasticsearch 所有的 API 中,对应的是一个或者多个索引,Elasticsearch 可以对一个或者多个索引指定别名,通过别名可以查询到一个或者多个索引的内容。在内部,Elasticsearch 会自动把别名映射到相应的索引上。可以对别名编写过滤器或者路由,在系统中别名不能重复,也不能喝索引名重复。其实 Elasticsearch 的别名机制有点像数据库中的视图。
创建、删除、更新别名
curl -u $user:$pwd -H "Content-Type:application/json" -XPOST "http://127.0.0.1:9200/_aliases" -d'
{
"actions" : [
{
"add" : {
"index" : ["index_name", "index_name2"], //一个别名关联多个索引
"alias" : "aliase_name"
}
// "remove" 删除别名,格式同上
// 更新别名:先加再删
}
]
}'
也可以使用通配符关联多个索引,index 写为 index_name*
创建过滤别名
通过过滤索引来指定别名提供了对索引查看的不同视图,该过滤器可以使用查询 DSL 来定义适用于所有的搜索,计数,查询删除等,以及更多类型这样的与此别名的操作。
要创建一个带过滤的别名,首先需要保证映射中已经存在需要过滤的字段:
curl -u $user:$pwd -H "Content-Type:application/json" -XPUT "http://127.0.0.1:9200/index_name/_mapping/type_name" -d'
{
"mappings": {
"type1": {
"properties": {
"user": {
"type": "text",
"index": true
}
}
}
}
}'
curl -u $user:$pwd -H "Content-Type:application/json" -XPOST "http://127.0.0.1:9200/_aliases" -d'
{
"actions" : [
{
"add" : {
"index" : "index_name",
"alias" : "aliase_name",
"filter": {
"term": {
"user": "kimchy"
}
}
}
}
]
}'
查询现有的别名
可以通过索引名或者别名进行查询。参数如下:
- index:索引别名的名称,可以使用通配符或者逗号分隔指定多个索引名称,还可以使用索引的别名名称
- alias:在向应用返回的别名名称。该参数支持通配符和用逗号分隔的多个别名
- ignore_unavailable:如果一个指定的索引名称不存在该怎么办。如果设置为 true,这些索引将被忽略
//别名查询
curl -u $user:$password -H "Content-Type:application/json" -XGET "http://$ip:$port/_alias/$index?pretty
//ES增加或移除别名 add/remove
curl -u $user:$password -H "Content-Type:application/json" -XPOST "http://$ip:$port/_aliases" -d '
{
"actions" : [
{ "remove" : { "index" :$index,"alias" : $index_alias } }
]
}'
curl -u $user:$password -H "Content-Type:application/json" -XPOST "http://$ip:$port/_aliases" -d '
{
"actions" : [
{ "add" : { "index" : $index,"alias" : $index_alias } }
]
}'
旧文Alias
别名,意思是在我创建索引的时候,为其添加一个别名,所有的查询以及添加内容等操作,不需要通过索引名称,全部需要通过别名操作,这样的好处是在我不确定这个索引 mapping 是否后期需要变更的时候作为一个后期变更 mapping 的一个手段,也有一些弊端,这样在我需要把 mapping 字段改变时,只需要把另外创建好的 mapping 在于这个 alias 关联即可,后面我知道不是一个索引了,前面却不知道后面已经变更为其他索引,但是这时候会有两个 index 需要铭记。