欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

ElasticSearch 考试准备 -- 通过查询更新

最编程 2024-10-04 07:03:57
...

一、题目

有个索引task,里面的文档长这样

现在需要添加一个字段all,这个字段的值是以下 a、b、c、d字段的值连在一起

二、思考

需要把四个字段拼接到一起,组成一个新的字段,这个就需要脚本,

这里有两种方案,

方案一:可以使用ingest painless脚本,在通过update by query,查询所有数据对索引中文档进行更新

方案二:使用ingest pianless 脚本,然后通过reindex 索引

三、解题

 初始化索引和数据

DELETE task
PUT task
POST task/_bulk
{"create":{"_id":1}}
{"a":"key","b":"mom","c":"mom","d":1}
{"create":{"_id":2}}
{"a":"key","b":"cake mix","c":"mom","d":2}
{"create":{"_id":3}}
{"a":"key","b":"mom","c":"cake mix","d":3}
{"create":{"_id":4}}
{"a":"cake mix","b":"mom","c":"mom","d":4}

方案一:ingest painless

Step 1、创建 ingest pianless 脚本

  • 脚本可以通过类似python中""" 三引号的方式编写
  • 创建新的字段,需要ctx['xx']指定
  • lang 可以不写,默认为pianless
PUT _ingest/pipeline/add_all
{
  "description": "add a+b+c+d = all",
  "processors": [
    {
      "script": {
        "lang": "painless", 
        "source": """ 
          ctx['all'] = ctx['a'] +" "+  ctx['b'] +" "+ ctx['c'] + " "+ ctx['d']
        """ 
      }
    }
  ]
}

Step 2、通过update by query 更新文档

update by query 后面如果要使用pianles脚本需要加?并指定脚本的名称

POST task/_update_by_query?pipeline=add_all

方案二:ingest painless + reindex

Step 1、创建 ingest pianless 脚本

PUT _ingest/pipeline/add_all
{
  "description": "add a+b+c+d = all",
  "processors": [
    {
      "script": {
        "lang": "painless", 
        "source": """ 
          ctx['all'] = ctx['a'] +" "+  ctx['b'] +" "+ ctx['c'] + " "+ ctx['d']
        """ 
      }
    }
  ]
}

Step 2、使用reindex

这个再创建一个新索引,并将数据导入。 注意:pipeline 是写在dest中

POST _reindex
{
  "source": {
    "index": "task"
  },
  "dest": {
    "index": "task_new",
    "pipeline": "add_all"
  }
}

四、总结

update by query 通常用于批量更新,可以结合painless 使用

创建脚本后一般都会成功,需要再结合update by query进行验证运行时,是否存在错误。


参考资料

  • Update By Query API | Elasticsearch Guide [8.1] | Elastic
  • Ingest pipelines | Elasticsearch Guide [8.1] | Elastic

送一波福利:

福利一

有需要内推JD的同学,可以私信或留言,我帮您内推,流程快!!!

有需要内推JD的同学,可以私信或留言,我帮您内推,流程快!!!

有需要内推JD的同学,可以私信或留言,我帮您内推,流程快!!!

福利二

福利三

推荐阅读