You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elasticsearch如何按条件获取指定字段并实现数据单位转换?

解决方案

一、提取指定语言的字段值

要保留所有目标ID的文档,同时只返回functionalNames数组中languageCode为de-DE的value,不能用查询条件过滤文档,得用script_fields在返回结果阶段做数组过滤:

  • 用Painless脚本遍历functionalNames数组,匹配符合语言编码的元素,提取对应value
  • 没有匹配到的文档,该字段会返回空数组或者null,不会被过滤掉

二、单位转换实现

你推测的script_fields完全可行,直接在脚本里对数值字段做单位换算即可,比如厘米转米、克转千克。

完整查询示例

{
  "query": {
    "ids": {
      "values": ["id1", "id2", "id3", "id4"]
    }
  },
  "script_fields": {
    "de_functional_name": {
      "script": {
        "source": """
          def result = [];
          for (def item : doc['functionalNames']) {
            if (item.languageCode == 'de-DE') {
              result.add(item.value);
            }
          }
          return result;
        """
      }
    },
    "JSONAttributePath1": {
      "script": "return doc['JSONAttributePath1'].value;"
    },
    "JSONAttributePath2": {
      "script": "return doc['JSONAttributePath2'].value;"
    },
    // 示例:厘米转米的单位转换
    "length_m": {
      "script": "return doc['length_cm'].value / 100;"
    },
    // 示例:克转千克的单位转换
    "weight_kg": {
      "script": "return doc['weight_g'].value / 1000;"
    }
  },
  "_source": false
}

补充说明

  • 如果你的functionalNames是嵌套类型(nested field),脚本需要调整为用_source遍历,因为doc值对嵌套数组的处理不同:
    "de_functional_name": {
      "script": {
        "source": """
          def result = [];
          def names = params._source.functionalNames;
          if (names != null) {
            for (def item : names) {
              if (item.languageCode == 'de-DE') {
                result.add(item.value);
              }
            }
          }
          return result;
        """
      }
    }
    
  • 脚本里可以添加默认值处理,比如没有匹配到语言时返回指定字符串(比如return result.isEmpty() ? ['无德语名称'] : result;)

内容的提问来源于stack exchange,提问作者Bogdan Boglea

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 08:57:37