10

ElasticSearch 数组去重

 2 years ago
source link: https://guanhonly.github.io/2021/08/29/es-distinct-array/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

ElasticSearch 数组去重

往ES某个字段中插入值时,有时候需要对结果进行去重,即需要这个字段里所有的值是互异的。而ES又没有Set这样的数据结构,所以需要在插入的时候执行脚本来实现这样的功能。

在参考了ES官方文档Script后,可以很容易写出这样的脚本,假设values字段是数组类型的,需要存储去重的值:

List values = [];
if (ctx._source.containsKey('values')) {
values.addAll(ctx._source.values);
}
values.addAll(params.values);
values = values.stream().distinct.collect(Collectors.toList());
ctx_source.values = values;

其中params.values是需要插入的值,这样每次插入时都会经过去重,保证了values字段中的值都是互异的。完整的DSL如下:

POST test_index/_update
{
"script":{
"source":"List values=[];if(ctx._source.containsKey('values')){values.addAll(ctx._source.values);}values.addAll(params.values);values = values.stream().distinct.collect(Collectors.toList());ctx_source.values = values;",
"params":{
"values":["a","b"]
}
}
}

分享到


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK