天天看点

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中的方法将数据索引到新建索引。

继续阅读