基本環境
- 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,如下:
在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架構社群