将弹性搜索字段转换为数组 [英] Converting Elastic Search field to Array

查看:94
本文介绍了将弹性搜索字段转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在弹性搜索中,如果您的文档具有预先存在的数组

 电影:[
回到未来
]

然后你更新它添加更多的电影,如这样

  {
script:ctx._source.movi​​es + = tag,
params:{
tag:纸浆小说
}
}

然后将该值添加到该字段。这很好,但是如果这个领域不是一个开始,而是看起来像这样



电影:回到未来



如果您运行相同的脚本,您将获得以下结果



电影:回到未来制表



所以我的问题是如何采取这个现有的字段和转换到一个数组来告诉弹性搜索,我想把它看作一个数组?

解决方案

可以改用这个脚本。它检查电影是否是一个数组,如果不是它创建一个

  {
script:if(ctx._source.movi​​es.getClass()。isArray()){ctx._source.movi​​es + = tag} else {ctx._source.movi​​es = [ctx._source.movi​​es ,标签]},
params:{
标签:纸浆小说
}
}
pre>

另一种较短的方法是始终分配一个数组,然后使用Groovy的 Collection.flatten() 方法

  {
script:ctx._source.movi​​es = [ctx._source.movi​​es,tag ] .flatten()},
params:{
tag:纸浆小说
}
}


In elastic search if you have document that has a pre-existing array

"movies": [
     "Back to the Future"
]

And then you update it to add more movies like such

{
  "script" : "ctx._source.movies += tag",
  "params" : {
    "tag" : "Pulp Fiction"
  }      
}

Then the value is added to the field. That works great... but what if the field isn't an arry to start with and instead looks like this

"movies": "Back to the Future"

If you run the same script you will get the following result

"movies":"Back to the FuturePulpFiction"

So my question is how do I take this existing field and "convert" it to an array to tell elastic search that I want to think of it as an array?

解决方案

You can use this script instead. It checks whether movies is an array and if not it creates one

{
  "script" : "if (ctx._source.movies.getClass().isArray()) { ctx._source.movies += tag } else { ctx._source.movies = [ctx._source.movies, tag] }",
  "params" : {
    "tag" : "Pulp Fiction"
  }      
}

Another shorter way of doing it is to always assign an array and then "flatten" it using Groovy's Collection.flatten() method

{
  "script" : "ctx._source.movies = [ctx._source.movies, tag].flatten()}",
  "params" : {
    "tag" : "Pulp Fiction"
  }      
}

这篇关于将弹性搜索字段转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆