天天看點

elasticsearch可視化kibana中索引字段不顯示

一 、問題描述

索引結構如下圖所示:

elasticsearch可視化kibana中索引字段不顯示

其中ipcid對應的是資料采集裝置的編号,我想要在kibana中統計各個裝置下的資料量并通過餅圖展示。于是,根據kibana操作流程:

1.首先建立visualize,選擇餅狀圖。如下圖所示:

elasticsearch可視化kibana中索引字段不顯示

2.選擇需要操作的index

elasticsearch可視化kibana中索引字段不顯示

3.選擇索引後,界面會自動跳到如下界面:

elasticsearch可視化kibana中索引字段不顯示

4.接下來就是選擇需要統計的字段,就是前面所說的ipcid。點選Split slices->Aggregation->terms->Filed->ipcid,結果嘔吼,在Field裡面根本找不到ipcid字段,怎麼回事呢?趕緊試試其他的,下面是選擇eleglasses字段畫出來的圖,一切正常:

elasticsearch可視化kibana中索引字段不顯示

二、問題分析

這是為啥呢?在索引中存在的字段,這裡卻不顯示了。回到第一張圖仔細檢視發現ipcid字段不支援aggregation操作,原來是這個原因。

問題雖然找到了。這裡就有點想不通了,為什麼有些字段支援aggregation,而有些字段不支援呢?于是對比了兩者的差別,發現可能是字段的資料類型不一樣。查到索引mapping結構,發現ipcid對應的數劇類型是text,而text天生是不支援aggregation操作的。

那麼當初為什麼要使用text?首先是因為es高版本開始已經去除了string類型,替代的資料類型為text或者keyword。對于大段的文字或者需要進行分詞的字段當然應該選擇text類型,但是對于不需要進行分詞,就應該選擇keyword。

es官網的原文解釋:

Text datatype edit

A field to index full-text values, such as the body of an email or the description of a product. These fields are analyzed, that is they are passed through an analyzer to convert the string into a list of individual terms before being indexed. The analysis process allows Elasticsearch to search for individual words within each full text field. Text fields are not used for sorting and seldom used for aggregations (although the significant text aggregation is a notable exception).

If you need to index structured content such as email addresses, hostnames, status codes, or tags, it is likely that you should rather use a keyword field.
           

三、解決辦法

既然知道問題的原因,也就等于找到了解決問題的方向,不就是修改索引結構mapping中對應字段的資料類型嗎?這麼想沒錯,在mapping中增加字段是可以的,但是es卻不支援對mapping進行修改或者删除操作。

雖然修改mapping臣妾做不到,但是官網也給出了曲線救國的路線:

Updating existing field mappingsedit

Other than where documented, existing field mappings cannot be updated. Changing the mapping would mean invalidating already indexed documents. Instead, you should create a new index with the correct mappings and reindex your data into that index.
           

簡單說就是你隻能重新建立一個正确的索引,并對資料進行重索引來實作。那就這麼辦吧,說動手就動手,具體操作如下:

1.重新建立一個索引,在mapping結構中使用正确的資料結構,将原來ipcid的資料類型由text改為keyword。

2.将原來索引中的資料遷移到建立的索引,官網給出的reindex方法(有人采用client APIS,未免太笨重):

The most basic form of _reindex just copies documents from one index to another. This will copy documents from the twitter index into the new_twitter index:

POST _reindex
{
  "source": {
    "index": "twitter"
  },
  "dest": {
    "index": "new_twitter"
  }
}
           

好了,到此你已經建立新的索引并且所有的資料也已經能夠通過新的索引查詢到。是以接下來你可能需要修改自己的程式代碼,更新es索引名。如果你不願意這樣做,那就将原來的索引删除掉,然後建立一個和原來索引同名的索引,使用正确的資料類型,然後再通過2中的方法将資料索引到建立索引。

繼續閱讀