Kibana对索引动态加字段显示

本文介绍Kibana对索引动态加字段显示。在实际业务数据存入Elasticsearch索引时会有一些枚举值,这些枚举值的意义不直观,也没必要在存索引时特意加一个用于显示的字段。这种场景只需在Kibana对查出的所有做一个脚本映射,新生成一个字段,不影响原Elasticsearch索引。

本文使用的Elasticsearch和Kibana版本都是7.9.0,Docker部署。先在Elasticsearch中存入一批数据,索引是一个简化过的订单数据,例子如下

{
    "_index":"es-syc-demo-order-2020.09",
    "_type":"_doc",
    "_id":"2020091822382704930",
    "_version":1,
    "_score":1,
    "_source":{
        "_class":"com.mingo.es.sync.document.OrderEntity",
        "id":"2020091822382704930",
        "tradeNo":"2020091822382704930",
        "buyerId":9527,
        "sellerId":18899,
        "type":1,
        "status":1,
        "amount":1,
        "discountAmount":0,
        "originAmount":1,
        "createTime":1600439907049,
        "lines":[
            {
                "tradeNo":"2020091822382704930",
                "lineNo":"1",
                "itemCode":"6352678819",
                "itemName":"泡椒凤爪",
                "unitCode":"DAI",
                "unitName":"袋",
                "type":1,
                "itemPrice":1,
                "price":1,
                "discountPrice":0,
                "itemQty":1,
                "totalPrice":1,
                "paidPrice":1,
                "createTime":1600439907049
            }
        ]
    }
}

1. 创建索引匹配

也就是Kibana中“Create index pattern”,也就是在Kibana中创建一个ES查询入口,所有图表的制作都是基于该pattern。

创建

创建好的pattern

在Discover中查看

2. 在pattern直接映射原字段

这种方式修改了字段的“Format”,在索引展示时会覆盖原值展示,只是做了一个展示映射。

将“Format”改为“Static lookup”,就可以在下发写入映射值。

在Discover中查看

3. 在pattern中使用脚本动态添加新字段

添加新字段“order-type”

编辑脚本

def map = ['t1': '官方商城', 't2': '传统零售']; 
def key = 't' + doc['type'].value; 
def type = map[key]; 
if (type == null) { return "其他"; } 
return type;

在Discover中可以看到,查询时多了一个“order-type”字段

同理,还可以添加其他字段,比如再添加一个“order-status”字段

def map = ['t1': '待支付', 't3': '待发货', 't5': '待收货', 't7': '已收货']; 
def key = 't' + doc['status'].value; 
def status = map[key]; 
if (status == null) { return "其他"; } 
return status;

在Discover中用“order-type”字段过滤,这里最终查询过滤时会转化为“type”原值搜索

4. 最后

动态新加的字段在显示时不影响原字段,在制作一些图表时相当有用。

原创 Doflamingo https://www.cnblogs.com/doflamingo
原文地址:https://www.cnblogs.com/doflamingo/p/13701208.html