基本環境
- elasticsearch版本:6.3.1
- 客戶端環境:kibana 6.3.4、Java8應用程式模塊,
其中kibana主要用于資料查詢診斷和查閱日志,Java8為主要的客戶端,資料插入和查詢都是由Java實作的,
案例介紹
使用elasticsearch存盤訂單的主要資訊,document內的field,基本上是long或keyword,創建索引的order.json檔案如下:
{
"doc": {
"properties": {
"id": {
"type": "keyword",
"index": true
},
"status": {
"type": "byte",
"index": true
},
"createTime": {
"type": "long",
"index": true
},
"uid": {
"type": "long",
"index": true
},
"payment": {
"type": "keyword",
"index": true
},
"commentStatus": {
"type": "byte",
"index": true
},
"refundStatus": {
"type": "byte",
"index": true
}
}
}
}
某天發現有個查詢功能(單獨使用payment欄位查詢)沒有資料出來,最近未修改此部分代碼,對比研發環境,研發環境是正常的,同樣的代碼在測驗環境下無資料回傳,
問題定位
- 程式中使用該欄位用的是termQuery,如下:
QueryBuilders.termQuery("payment", req.getFilter().getOrder().getPayment())
在kibana上用命令診斷查詢資料,同樣沒有結果回傳,查詢命令如下:
GET /order/doc/_search
{
"query": {
"bool": {
"must": [
{"term": {
"payment": "Alipay"
}}
]
}
}
}
- 查詢mapping資訊,看是否為keyword:
GET /order/_mapping/doc
回應回傳(只展示payment欄位):
{
"order": {
"mappings": {
"doc": {
"properties": {
"payment": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
}
}
問題原因
按照mapping回傳結果來看,欄位payment原定義的型別是keyword,現在變成text了,這個是payment欄位使用termQuery查詢導致沒有資料的原因,
text與keyword的區別
keyword對保存的內容不分詞,也不改變大小寫,原樣存盤,默認可索引,
text對內容進行分詞,并且全部小寫存盤,同時會增加一個text.keyword欄位,為keyword型別,超過256字符后不索引,
由于payment欄位變成text了,原有的程式使用term查詢,用的"Alipay",而text存盤的是"alipay",所以查不到資料了,
嘗試排錯方法
- payment的值改成小寫
GET /order/doc/_search
{
"query": {
"bool": {
"must": [
{"term": {
"payment": "alipay"
}}
]
}
}
}
- 或將term查詢改成match查詢
GET /order/doc/_search
{
"query": {
"bool": {
"must": [
{
"match": {
"payment": "alipay"
}
}
]
}
}
}
查詢有資料輸出,并且符合預期,嘗試方法有效,
問題追溯
明明order.json的對payment欄位定義的型別是keyword,怎么變成text了?
由于出現此問題的環境是測驗環境,有重刪索引資料,然后再全部匯入的操作(有點不規范,但僅限于測驗環境,生產環境不會這么做),重新匯入索引document資料的功能,es創建索引自動mapping時,payment欄位的string內容,會變成text,
解決辦法:
1.洗掉索引
DELETE /order
2.按照order.json重建索引
PUT /order
{
"mappings": {
"doc": {
"properties": {
"id": {
"type": "keyword",
"index": true
},
"status": {
"type": "byte",
"index": true
},
"createTime": {
"type": "long",
"index": true
},
"uid": {
"type": "long",
"index": true
},
"payment": {
"type": "keyword",
"index": true
},
"commentStatus": {
"type": "byte",
"index": true
},
"refundStatus": {
"type": "byte",
"index": true
}
}
}
}
}
3.觸發程式灌資料(也可以用bulk)
小結
問題雖小,但一定要追溯源頭,比如此次測驗環境的不規范操作,后期如果有洗掉索引的操作,應該先手動建立索引后,再灌資料,而不是直接讓其自動mapping建立索引,自動mapping建立的欄位型別,可能不是我們期望的,
專注Java高并發、分布式架構,更多技術干貨分享與心得,請關注公眾號:Java架構社區

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/233432.html
標籤:其他
上一篇:SQL Server GROUP BY中的WITH CUBE、WITH ROLLUP原理測驗及GROUPING應用
