采坑了。首先吐槽一下,下載elasticsearch的最新版本7.9.0了,配置索引模板跟原來6.X.X、6.X.X之前的都有點差別。新版的api中除了_template,又有了_index_template和_component_template,很容易混淆,讓人不知所措。好了回歸正題,我們這里使用的特指7.9.0的_template這個api。
事情是這樣的,我在logstash配置了一個output指向elasticsearch的template:
output { elasticsearch{ hosts => "localhost:9200" index => "hello-world-%{+YYYY.MM.dd}" manage_template => true template_name => "hello-world" template_overwrite => true template => "D:\elk\logstash-7.9.0\config\hello-world.json" } }
hello-world.json內容:
{ "index_patterns": ["hello-world-%{+YYYY.MM.dd}"], "order": 0, "settings": { "index.refresh_interval": "10s" }, "mappings": { "properties": { "createTime": { "type": "long" }, "sessionId": { "type": "text", "fielddata": true, "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "chart": { "type": "text", "analyzer": "ik_max_word", "search_analyzer": "ik_max_word" } } } }
結果是創建的hello-world-2020.09.09索引的mapping並非模板中所指定的,而是按動態模板來的。明眼人也許一樣就發現了問題:我把logstash的索引樣式hello-world-%{+YYYY.MM.dd}直接復制給了模板中的index_patterns賦值了。這會導致什么問題呢?讓我們來kibana中試驗一下:
1、先創建上面的索引模板,執行
PUT _template/hello-world { "index_patterns": ["hello-world-%{+YYYY.MM.dd}"], "order": 0, "settings": { "index.refresh_interval": "10s" }, "mappings": { "properties": { "createTime": { "type": "long" }, "sessionId": { "type": "text", "fielddata": true, "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "chart": { "type": "text", "analyzer": "ik_max_word", "search_analyzer": "ik_max_word" } } } }
2、創建索引並插入數據(注意新模板對老索引不生效,可以把索引刪掉重建):
POST hello-world-2020.09.10/_doc/1 { "createTime": 1599185288000, "chart": "今天天氣怎么樣", "sid":"12345" }
3、看下該索引的mapping:
GET hello-world-2020.09.10/_mapping
結果是:
{ "hello-world-2020.09.10" : { "mappings" : { "properties" : { "chart" : { "type" : "text", "fields" : { "keyword" : { "type" : "keyword", "ignore_above" : 256 } } }, "createTime" : { "type" : "long" }, "sid" : { "type" : "text", "fields" : { "keyword" : { "type" : "keyword", "ignore_above" : 256 } } } } } } }
嗯,結果是hello-world-2020.09.10索引的映射都是elasticsearch自動識別創建出來的,或者說它匹配不到我們的hello-world模板而使用了默認的mapping。模板的作用就是創建索引時能指定映射,現在模板不生效了。我嘗試了各種設置,發現不使用模板,直接給hello-world-2020.09.10索引指定mapping是沒有問題的,所以問題不在映射配置上,而在於模板本身。然后就被誤導了,改了order的優先級順序,嘗試了開篇提到的各種es版本的配置差別和其他api。最后把各種坑都采完了,才恍然發現我的索引模式可能沒匹配上。問題就出現在模板的第一行,我把index_patterns改成hello-word*,創建索引時就使用了模板了。
1、再次put模板覆蓋一下:
2、新建一個新索引:
3、看它的mapping:
我們看到新索引hello-world-2020.09.11被模板識別到了。所以,日志索引就別在模板中的index_patterns亂添樣式了,直接用日志前綴加*通配就好了。