如何在elasticsearch中创建数组运行时字段?

bakd9h0s  于 2023-01-12  发布在  ElasticSearch
关注(0)|答案(1)|浏览(138)

我有一个带有嵌套字段“roles”的elasticsearch索引:

"roles": {
    "type": "nested",
    "properties": {
        "name": {
            "type": "text",
            "fields": {
                "raw": {
                    "type": "text",
                    "analyzer": "keylower"
                }
            }
        },
        "responsibilities": {
            "properties": {
                "name": {
                    "type": "text",
                    "fields": {
                        "raw": {
                            "type": "text",
                            "analyzer": "keylower"
                        }
                    }
                }
            }
        }
    }
}

这些字段中的值是数组,例如:

"roles": [
        {
            "name": "System Analyst",
            "responsibilities": [
                {
                    "name": "Software Development"
                },
                {
                    "name": "Software Testing"
                }
            ]
        },
        {
            "name": "Data Analyst",
            "responsibilities": [
                {
                    "name": "Data analysis"
                },
                {
                    "name": "Reporting"
                }
            ]
        }
    ]

我想分别在这些字段上构建Kibana可视化。因为它是一个嵌套字段,Kibana还不支持它(?),所以我想到为每个字段创建运行时字段。
这是我对角色使用的查询:

PUT employee/_mappings
{
  "runtime": {
    "empRoles": {
      "type": "keyword",
      "script": """if (doc["roles.name.raw"].size()!=0 ) {
        String[] empRoles;
        for(int i=0; i < doc["roles.name.raw"].size(); i++) {
          empRoles[i] = doc["roles.name.raw"].value ;
          
        }
         emit(empRoles);}"""
    }
  }
}

但我得到了以下错误:

"caused_by" : {
        "type" : "class_cast_exception",
        "reason" : "Cannot cast from [java.lang.String[]] to [java.lang.String]."
      }

我怎样才能让它工作呢?最终,我想建立一个关于字段“角色”和“责任”的kibana Jmeter 板。

polhcujo

polhcujo1#

似乎没有办法将nested字段与runtime字段一起使用。
我可以按照here的建议定义一个脚本字段,从而得到想要的结果。
Index Pattern > [index pattern name] > Scripted fields tab > Add scripted field(Kibana版本7.17。对于更高版本,请将Index Patterns替换为Data Views)中添加以下脚本。
对于roles

def names = new String[params._source.roles.length];
    def i= 0;
    for( role in params._source.roles){
      if(role.name != null){
        names[i++] = role.name;
      }
    }
    return names;

对于responsibilities

def responsibilitiesLength = 0;
    for( role in params._source.roles){
        responsibilitiesLength += role.responsibilities.length;
    }
    def responsibilities = new String[responsibilitiesLength];
    def i= 0;
    for( role in params._source.roles){
        for( responsability in role.responsibilities){
          responsibilities[i++] = responsability.name
        }
    }
    return responsibilities;

(Note:脚本字段可能导致性能问题,因此已弃用)

相关问题