如何使用elastic4s删除Elasticsearch数组中的指定元素
解决Elasticsearch数组元素删除问题(基于elastic4s)
首先要明确:要删除文档中数组的特定元素,不能用delete相关操作(deleteIn...是用来删除整个文档或批量删除文档的),而是要通过**更新文档(Update API)**结合Painless脚本来实现。
具体实现代码
在elastic4s中,你可以用以下代码移除members数组中的tony元素:
val updateResult = client.execute { updateInto("testindex"/"test") id 1 script { script("painless", """ctx._source.members.removeIf(item -> item == 'tony')""") } }.await
代码解释
updateInto("testindex"/"test") id 1:指定要更新的索引、类型和目标文档ID,和你插入时的目标完全匹配。script(...):使用Elasticsearch原生的Painless脚本语言修改文档内容。ctx._source代表当前文档的源数据,removeIf是Painless为数组提供的便捷方法,用来过滤移除符合条件的元素(这里精准匹配值为tony的元素)。
兼容旧版ES的写法
如果你的Elasticsearch版本不支持removeIf方法,可以用过滤后重新赋值的方式实现:
val updateResult = client.execute { updateInto("testindex"/"test") id 1 script { script("painless", """ctx._source.members = ctx._source.members.stream().filter(item -> !item.equals('tony')).collect(Collectors.toList())""") } }.await
验证操作结果
执行更新后,你可以通过get操作确认修改是否生效:
val getResult = client.execute { get("testindex"/"test") id 1 }.await println(getResult.sourceAsString)
此时输出的文档中,members数组应该不再包含tony元素。
内容的提问来源于stack exchange,提问作者ddsprasad
相关产品推荐
相关产品推荐

