index aliases,索引別名,有點類似名稱映射,一個索引別名可以映射多個真實索引,索引別名在定義時還支持filter,構成同一個索引,不同的視圖。
思考:一個索引別名可以映射成多個索引,那如果向一個別名添加一個文檔時,會在該別名下對應的所有索引下都創建一個文檔?
1、如何創建索引別名
POST /_aliases
{
"actions" : [
{ "remove" : { "index" : "test1", "alias" : "alias1" } },
{ "add" : { "index" : "test2", "alias" : "alias1" } }
]
}
索引創建API,支持add、remove操作,當前Restfull java客戶端未封裝該方法。
爲索引創建別名,也可以在創建索引API中指定:
PUT test
{
"aliases" : {
"alias_1" : {},
"alias_2" : {
"filter" : {
"term" : {"user" : "kimchy" }
},
"routing" : "kimchy"
}
}
}
2、Filtered Aliases
帶有過濾器的別名提供了創建相同索引的不同“視圖”的簡單方法。過濾器可以使用查詢DSL定義,並應用於所有搜索、計數、按查詢刪除以及類似於此別名的操作。
其使用示例如下,假設存儲該索引:
PUT /test1
{
"mappings": {
"_doc": {
"properties": {
"user" : {
"type": "keyword"
}
}
}
}
}
爲別名設置過濾器的使用方法如下:
POST /_aliases
{
"actions" : [
{
"add" : {
"index" : "China_Provice_Index",
"alias" : "shanghai_index",
"filter" : { "term" : { "provice" : "shanghai" } }
},
"add" : {
"index" : "China_Provice_Index",
"alias" : "guangzhou_index",
"filter" : { "term" : { "provice" : "guangzhou" } }
}
}
]
}
通過爲China_Provice_Index(中國各省份人才數據庫索引)創建別名,shanghai_index、guangzhou_index,這樣從兩個別名進行數據查詢,只會查出各自省份的數據,是不是有點類似於”多租戶“,也即通過索引別名並指定過濾器,能爲同一個索引提供不同的視圖。
3、Routing
在創建別名時可以指定路由值。
POST /_aliases
{
"actions" : [
{
"add" : {
"index" : "test",
"alias" : "alias1",
"routing" : "1"
}
}
]
}
使用別名alias1查詢內容時,會自動使用該值進行路由。
也可以通過search_routing、index_routing分別來指定查詢、索引時的路由值,注意,index_routing只能指定一個值。
4、Write Index
如果一個別名只映射了一個真實索引,則可以使用別名進行index api(即索引文檔,寫文檔),但如果一個別名同一時間映射了多個索引,默認是不能直接使用別名進行索引文檔,因爲ES不知道文檔該發往哪個索引。
可以使用is_write_index屬性爲一個別名下的其中一個索引指定爲寫索引,此時則可以直接使用別名進行index api的調用。
例如:
POST /_aliases
{
"actions" : [
{
"add" : {
"index" : "test",
"alias" : "alias1",
"is_write_index" : true
}
},
{
"add" : {
"index" : "test2",
"alias" : "alias1"
}
}
]
}
es index aliases,索引別名就介紹到這裏了。
原文發佈時間爲:2019-03-14
本文作者:丁威,《RocketMQ技術內幕》作者。
本文來自中間件興趣圈,瞭解相關信息可以關注自中間件興趣圈。