MST
星途 面试题库

面试题:ElasticSearch中使用script更新时如何处理复杂逻辑

在ElasticSearch使用script更新时,假设需要根据文档中的多个字段进行复杂的条件判断,并基于判断结果更新另一个字段,应该如何编写script?请举例说明,例如文档中有'price'字段和'discount'字段,当'price'大于100且'discount'小于0.8时,将'new_price'字段更新为'price'乘以'discount'。
41.8万 热度难度
数据库ElasticSearch

知识考点

AI 面试

面试题答案

一键面试

在Elasticsearch中,可以使用Painless脚本语言来实现上述需求。以下是示例:

POST /your_index_name/_update_by_query
{
  "script": {
    "source": "if (ctx._source.price > 100 && ctx._source.discount < 0.8) { ctx._source.new_price = ctx._source.price * ctx._source.discount; }",
    "lang": "painless"
  }
}

在上述示例中:

  1. ctx._source 表示当前文档的源数据。
  2. 通过 if 语句进行条件判断,判断 price 是否大于100且 discount 是否小于0.8。
  3. 如果条件满足,则更新 new_price 字段为 price 乘以 discount
  4. lang 指定脚本语言为Painless,这是Elasticsearch推荐的脚本语言。

请将 your_index_name 替换为实际的索引名称。