给一个索引或多个索引建一个别名使索引之间
场景一:
假如我们的日志数据是以月数格式存储, 列如1,2,3月分别创建索引, 当我们想查询一个用户3个月中一个出现次数, 需要分别查询索引, 这种方式比较低效, 可以创建索引别名(last_three_mothod
), 同时进行查询
当请求last_three_mothod
时向3个索引进行了转发
# 添加数据
PUT /march_log # 创建3个格式一样的索引
{
"mappings": {
"properties": {
"title":{
"type": "text"
},
"city":{
"type": "keyword"
},
"price":{
"type": "double"
}
}
}
}
# 创建别名
POST /_aliases
{
"actions": [
{
"add": {
"index": "march_log",
"alias": "last_three_mothod",
"is_write_index": "true" # 当指定别名写入时
}
},
{
"add": {
"index": "january_log",
"alias": "last_three_mothod"
}
},
{
"add": {
"index": "februray_log",
"alias": "last_three_mothod"
}
}
]
}
GET last_three_mothod/_search
{
"query": {
"bool": {
"filter": [
{
"range": {
"price": {
"gte": 10
}
}
}
]
}
}
}
# 结果
{
"took" : 1,
"timed_out" : false,
"_shards" : {
"total" : 3,
"successful" : 3,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 3,
"relation" : "eq"
},
"max_score" : 0.0,
"hits" : [
{
"_index" : "februray_log", # 索引名称
"_type" : "_doc",
"_id" : "001", // 主键
"_score" : 0.0, 分数
"_source" : {
"title" : "河北宾馆",
"city" : "河北",
"price" : "1923.23"
}
},
{
"_index" : "january_log",
"_type" : "_doc",
"_id" : "001",
"_score" : 0.0,
"_source" : {
"title" : "好再来",
"city" : "青岛",
"price" : "753.23"
}
},
{
"_index" : "march_log",
"_type" : "_doc",
"_id" : "001",
"_score" : 0.0,
"_source" : {
"title" : "如家",
"city" : "河北",
"price" : "200.23"
}
}
]
}
}
注意:
当一个别名只绑定了一个索引时,可以指定别名进行写入,如果一个别名绑定了多个索引,不可以指定别名写入
但是可以在多个索引中指定一个索引进行写入,设置索引的is_write_index=true,此时再次写入就可以写入到指定的索引中
场景二:
引入别名以后,还可以使用别名表示索引之间的关系.
比如一个索引在创建以后, 有些值是不能改变的(主分片个数), 但是随着业务的增大,需要更改索引参数进行优化, 我们需要平滑解决, 即更改索引设置,又不更改索引名称,
以march_log
为例, 一个主分片的默认值是1, 我们需要将主分片的数量设置成10
PUT /march_log_4 # 创建新的index
{
"settings": {
"number_of_shards": 10,
"number_of_replicas": 2
},
"mappings": {
"properties": {
"title":{
"type": "text"
},
"city":{
"type": "keyword"
},
"price":{
"type": "double"
}
}
}
}
POST _reindex ## 数据同步
{
"source": {
"index": "march_log",
"size": 1000 ## 每次通过数据条数, 不设置不限制
},
"dest": {
"index": "march_log_4"
}
}
POST /_aliases ## 更换映射关系
{
"actions": [
{
"remove": {
"index": "march_log",
"alias": "last_three_mothod"
}
},
{
"add": {
"index": "march_log_4",
"alias": "last_three_mothod"
}
}
]
}