Elasticsearch脚本查询

news2024/10/7 10:13:35

Elasticsearch脚本查询

什么/为什么

Scripting是Elasticsearch支持的一种专门用于复杂场景下支持自定义编程的强大的脚本功能,ES支持多种脚本语言,如painless,其语法类似于Java,也有注释、关键字、类型、变量、函数等,其就要相对于其他脚本高出几倍的性能,并且安全可靠,可以用于内联和存储脚本。

核心就是解决复杂的查询以及兼顾性能.

ES支持的一些脚本语言

  1. LanguageSandboxedRequired pluginPurpose
    painlessYesBuilt-inPurpose-built for Elasticsearch
    expressionYesBuilt-inFast custom ranking and sorting
    mustacheYesBuilt-inTemplates
    javaNoYou write it!Expert API

语法格式

官网文档:https://www.elastic.co/guide/en/elasticsearch/reference/7.17/modules-scripting.html

## ctx._source<.field_name>
## ctx只的是hit到的source数据这里的数据都可支持修改,但是元数据不要修改,修改完数据就变了,最好修改_source内的

GET test_idx_aggs/_doc/1
POST test_idx_aggs/_doc/1
{
  "script": {
    "source": "ctx._id+=1"
  }
}
GET test_idx_aggs/_doc/1
POST test_idx_aggs/_doc/1
{
  "script": {
    "source": "ctx._source.price+=1"
  }
}

不要修改元数据

修改元数据前后

{
  "_index" : "test_idx_aggs",
  "_type" : "_doc",
  "_id" : "2",
  "_version" : 1,
  "_seq_no" : 1,
  "_primary_term" : 1,
  "found" : true,
  "_source" : {
    "name" : "小米NFC手机",
    "desc" : "支持全功能NFC,手机中的滑翔机",
    "price" : 4999,
    "lv" : "旗舰机",
    "type" : "手机",
    "createtime" : "2020-05-21T08:00:00Z",
    "tags" : [
      "性价比",
      "发烧",
      "公交卡"
    ]
  }
}

# POST test_idx_aggs/_doc/2
#! Elasticsearch built-in security features are not enabled. Without authentication, your cluster could be accessible to anyone. See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/security-minimal-setup.html to enable security.
{
  "_index" : "test_idx_aggs",
  "_type" : "_doc",
  "_id" : "2",
  "_version" : 2,
  "result" : "updated",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 15,
  "_primary_term" : 3
}

# GET test_idx_aggs/_doc/2
#! Elasticsearch built-in security features are not enabled. Without authentication, your cluster could be accessible to anyone. See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/security-minimal-setup.html to enable security.
{
  "_index" : "test_idx_aggs",
  "_type" : "_doc",
  "_id" : "2",
  "_version" : 2,
  "_seq_no" : 15,
  "_primary_term" : 3,
  "found" : true,
  "_source" : {
    "script" : {
      "source" : "ctx._seq_no+=1"
    }
  }
}

修改数据

GET test_idx_aggs/_doc/3
POST test_idx_aggs/_update/3
{
  "script": {
    "lang": "painless",
    // 注意add方法得看数据具体类型,这里如果是数组链表类似的结构可以执行add,如果源数据是一个字符串则报错
    "source": "ctx._source.tags.add('NFC')"
  }
}
GET test_idx_aggs/_doc/3

删除数据

脚本

GET test_idx_aggs/_doc/1
POST test_idx_aggs/_update/1
{
  "script": {
    "lang": "painless",
    "source": "ctx.op='delete'"
  }
}
GET test_idx_aggs/_doc/1

结果

# GET test_idx_aggs/_doc/1
#! Elasticsearch built-in security features are not enabled. Without authentication, your cluster could be accessible to anyone. See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/security-minimal-setup.html to enable security.
{
  "_index" : "test_idx_aggs",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 5,
  "_seq_no" : 14,
  "_primary_term" : 3,
  "found" : true,
  "_source" : {
    "script" : {
      "source" : "ctx._id+=1"
    }
  }
}

# POST test_idx_aggs/_update/1
#! Elasticsearch built-in security features are not enabled. Without authentication, your cluster could be accessible to anyone. See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/security-minimal-setup.html to enable security.
{
  "_index" : "test_idx_aggs",
  "_type" : "_doc",
  "_id" : "1",
  "_version" : 6,
  "result" : "deleted",
  "_shards" : {
    "total" : 2,
    "successful" : 1,
    "failed" : 0
  },
  "_seq_no" : 17,
  "_primary_term" : 3
}

# GET test_idx_aggs/_doc/1
#! Elasticsearch built-in security features are not enabled. Without authentication, your cluster could be accessible to anyone. See https://www.elastic.co/guide/en/elasticsearch/reference/7.17/security-minimal-setup.html to enable security.
{
  "_index" : "test_idx_aggs",
  "_type" : "_doc",
  "_id" : "1",
  "found" : false
}

查询验证

GET test_idx_aggs/_search
{
  "query": {
    "match": {
      "_id": 1
    }
  }
}

upsert

有则更新无则插入

GET test_idx_aggs/_doc/1
POST test_idx_aggs/_update/1
{
  "script": {
    "lang": "painless",
    "source": "ctx._source.price+=99"
  }
  , "upsert": {
        "name" : "小米NFC手机",
    "desc" : "支持全功能NFC,手机中的滑翔机",
    "price" : 4999,
    "lv" : "旗舰机",
    "type" : "手机",
    "createtime" : "2020-05-21T08:00:00Z",
    "tags" : [
      "性价比",
      "发烧",
      "公交卡"
    ]
  }
}
GET test_idx_aggs/_doc/1

其他

GET test_idx_aggs/_search
{
  "script_fields": {
    // 查询结果存储的字段名称
    "my_col_name_result": {
      "script": {
        // 可以改为expression语言,区别是什么? 结果一样语法不一样
        "lang": "painless",
        // 查询时不用ctx对象了使用doc来获取
        "source": "doc['price'].value*1.1"
      }
    }
  }
}

更新语句

POST test_idx_aggs/_update/6
{
 "doc": {
   "price": 9999
 }
}

参数化查询

POST test_idx_aggs/_update/6
{
  "script": {
    "lang": "painless",
    //tag_new:下边参数名称
    "source": "ctx._source.tags.add(params.tag_new)",
    // 编译脚本,缓存到缓冲区,参数可以传递没有硬编码
    "params": {
      "tag_new": "new"
    }
  }
}

脚本模板

/_script/{script_template_id}

创建并使用脚本模板

DELETE _scripts/calculate_score
## calculate_score:模板id
POST _scripts/calculate_score
{
  "script": {
    "lang": "painless",
    // my_modifier:定义的参数名称
    "source": "Math.log(_score * 2) + params['my_modifier']"
  }
}

GET _scripts/calculate_score

## 索引名称
GET test_idx_aggs/_search
{
  "query": {
    "script_score": {
      "query": {
        "match_all": {}
      },
      "script": {
        "id": "calculate_score",
        "params": {
          "my_modifier": 2
        }
      }
    }
  }
}

函数式编程

POST test_idx_aggs/_update/1
{
  "script": {
    "lang": "painless",
    // 可以写复杂的脚本
    "source": """
    ctx._source.tags.add(params.param_name1);
    ctx._source.price -= 1;
    """,
    "params": {
      "param_name1": "new",
      "param_name2": 2
    }
  }
}

GET test_idx_aggs/_doc/1
POST test_idx_aggs/_update/1
{
  "script": {
    "lang": "painless",
    "source": """
    // 正则匹配然后 给name增加点内容; ==~表示匹配的意思; /[\s\S]*小米[\s\S]*/相当于 %小米%
        if(ctx._source.name ==~ /[\s\S]*小米[\s\S]*/) {
          ctx._source.name+="xxxxxxxxxxxxxx"
        }
        """
  }
}

GET test_idx_aggs/_doc/1
PUT test_index/_bulk?refresh 
{"index":{"_id":1}} 
{"ajbh": "12345","ajmc": "立案案件","lasj": "2020/05/21 13:25:23","jsbax_sjjh2_xz_ryjbxx_cleaning": [{"XM": "张三","NL": "30","SF": "男"},{"XM": "李四","NL": "31","SF": "男"},{"XM": "王五","NL": "30","SF": "女"},{"XM": "赵六","NL": "23","SF": "男"}]} 
{"index":{"_id":2}} 
{"ajbh": "563245","ajmc": "结案案件","lasj": "2020/05/21 13:25:23","jsbax_sjjh2_xz_ryjbxx_cleaning": [{"XM": "张三2","NL": "30","SF": "男"},{"XM": "李四2","NL": "31","SF": "男"},{"XM": "王五2","NL": "30","SF": "女"},{"XM": "赵六2","NL": "23","SF": "女"}]} 
{"index":{"_id":3}} 
{"ajbh": "12345","ajmc": "立案案件","lasj": "2020/05/21 13:25:23","jsbax_sjjh2_xz_ryjbxx_cleaning": [{"XM": "张三3","NL": "30","SF": "男"},{"XM": "李四3","NL": "31","SF": "男"},{"XM": "王五3","NL": "30","SF": "女"},{"XM": "赵六3","NL": "23","SF": "男"}]}


GET test_index/_search


GET test_index/_search
{
  "aggs": {
    "agg_NAME": {
      "sum": {
        "script": {
          "lang": "painless",
          "source": """
          int total = 0;
          for(int i = 0; i<params['_source']['jsbax_sjjh2_xz_ryjbxx_cleaning'].length; i++){
            if(params['_source']['jsbax_sjjh2_xz_ryjbxx_cleaning'][i]['SF']=='男'){
            total+=1;
            }
          }
          return total;
          """
        }
      }
    }
  }
}

doc和 _source访问属性区别

doc[<field>].value和params['_source'][<field>]

  • doc只适用简单类型,复杂类型会报错
  • doc会加载到内存,性能高,内存占用也高
  • 只有在非分析或单个词条的基础上有意义

  • _source方式每次都要解析比较慢

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/720473.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

AI绘画:Stable Diffusion 终极炼丹宝典:从入门到精通

本文收集于教程合集&#xff1a;AIGC从入门到精通教程汇总 我是小梦&#xff0c;以浅显易懂的方式&#xff0c;与大家分享那些实实在在可行之宝藏。 历经耗时数十个小时&#xff0c;总算将这份Stable Diffusion的使用教程整理妥当。 从最初的安装与配置&#xff0c;细至界面…

fdisk和df -h的区别以及如何看懂和提取信息

前几天要查看linux系统磁盘大小&#xff0c;但是发现fdisk和df -h出来的大小和信息不一样&#xff0c;了解了一下linux的磁盘分区和内存大小&#xff0c;查阅了相关资料&#xff0c;总结以下信息&#xff1a; 一、相关理念 在计算机中&#xff0c;存放信息的主要存储设备就是…

天猫数据分析工具(天猫实时数据)

后疫情时代&#xff0c;聚会、聚餐与送礼热度上涨&#xff0c;酒类产品既作为送礼首选又作为佐餐饮品的热门选手也受此影响迎来消费小高峰。在此背景下&#xff0c;白酒市场也开始复苏并不断加快速度。 根据鲸参谋电商数据分析平台的相关数据显示&#xff0c;2023年1月份至4月…

小程序 事件委托给父元素scrollview 获取不到子元素view的绑定的dataset值

点击事件委托到父元素&#xff1a;scrollview 减少多次循环绑定 &#xff1a; 通过点击事件的dataset判断了点击哪个子元素。 常能见到e.target或者e.currentTarget。 简单来说&#xff0c;currentTarget就是当前对象&#xff0c;target就是整个对象&#xff08;包含子元素&…

如何实现移动端侧边目录栏收缩,并监听点击目录栏以外则自动收缩

父组件&#xff0c;index界面&#xff0c;注意此时expend按钮在父组件中 <template><el-container><el-aside class"Aside"><MAside expendClick"expendClick" :message"message" /></el-aside><div class&qu…

2、CCesium二次开发环境搭建

CCesium是使用c和opengl实现的桌面三维地球&#xff0c;所以进行二次开发需要搭建c的开发环境。 在windows系统上c开发可以使用vs或cmake和mingw clion开发。本人使用mingwclion&#xff0c;如果使用其他ide那我也帮不了你。cmake是构建项目的&#xff0c;clion使用2020.1版本…

Lesson3-1:OpenCV图像处理---几何变换

几何变换 学习目标 掌握图像的缩放&#xff0c;平移&#xff0c;旋转等了解数字图像的仿射变换和透射变换 1 图像缩放 缩放是对图像的大小进行调整&#xff0c;即使图像放大或缩小。 API cv2.resize(src,dsize,fx0,fy0,interpolationcv2.INTER_LINEAR)参数&#xff1a; s…

数据结构 | 二叉排序树

一、数据结构定义 /* 二叉排序树 */ typedef int TreeType; typedef struct BSTNode {TreeType data;struct BSTNode* lchild, * rchild; }*BSTree, BSTNode;二、方法概览 BSTNode* CreateTreeNode(TreeType data); // 创建二叉树结点 BSTNode* InsertTree(TreeType data, BS…

Vulnhub靶机PWNLAB:INIT writeup

靶机介绍 靶机下载&#xff1a;https://www.vulnhub.com/entry/matrix-2,279/ ​ 个人微信公众号&#xff1a;网络安全学习爱好者 信息搜集 arp扫描存活主机 ​​​ 根据MAC地址比较靶机IP为​192.168.30.131 ​​ nmap扫描全端口及端口服、版本 ​​​ 目录扫描123…

通信相关知识(三) 接入网

接入网的定界 接入网的功能 用户口功能、业务口功能、核心功能、传送功能、接入网系统管理功能。 ADSL 非对称数字用户线路&#xff08;ADSL&#xff0c;Asymmetric Digital Subscriber Line&#xff09;是数字用户线路&#xff08;xDSL&#xff0c;Digital Subscriber Lin…

【Java从入门到大牛】Java基础语法

&#x1f525; 本文由 程序喵正在路上 原创&#xff0c;CSDN首发&#xff01; &#x1f496; 系列专栏&#xff1a;Java从入门到大牛 &#x1f320; 首发时间&#xff1a;2023年7月5日 &#x1f98b; 欢迎关注&#x1f5b1;点赞&#x1f44d;收藏&#x1f31f;留言&#x1f43e…

黑客(自学笔记)

黑客&#xff0c;对很多人来说充满诱惑力。很多人可以发现这门领域如同任何一门领域&#xff0c;越深入越敬畏&#xff0c;知识如海洋&#xff0c;黑客也存在一些等级&#xff0c;参考知道创宇 CEO ic&#xff08;世界顶级黑客团队 0x557 成员&#xff09;的分享如下&#xff1…

第一章:项目架构演变

1、在设计系统时&#xff0c;应该多思考 墨菲定律 1. 任何事都没有表面上看起来那么简单。 2. 所有的事做起来都会比你预计的时间长。 3. 可能出错的事总会出错。 4. 如果你担心某种情况发生&#xff0c;那么它就更有可能发生。 2、在划分时&#xff0c;也要思考康威定律。…

centos7安装zookeeper的环境变量配置导致用户登录不了系统

废话不多说&#xff0c;我修改的/etc/profile,如果这个文件改错会造成所有用户都登录不了系统。 第一步&#xff1a;解决进不了系统 1.在登陆界面按&#xff1a;alt ctrlf2进入命令模式&#xff0c;输入密码登录后再输入&#xff1a; /usr/bin/sudo /usr/bin/vi /etc/profile …

Apache Doris 在拈花云科的统一数据中台实践,One Size Fits All

作者&#xff5c;NearFar X Lab 团队 洪守伟、陈超、周志银、左益、武超 整理&#xff5c;SelectDB 内容团队 导读&#xff1a; 无锡拈花云科技服务有限公司&#xff08;以下简称拈花云科&#xff09;是由中国创意文旅集成商拈花湾文旅和北京滴普科技有限公司共同孵化组建的。…

微信小程序Vant组件配置及使用

Vant Weapp 官网文档&#xff1a;介绍 - Vant Weapp (gitee.io) Vant Weapp GitHub地址&#xff1a;youzan/vant-weapp: 轻量、可靠的小程序 UI 组件库 (github.com) 本教程使用下载代码方式引入vant组件 1. 下载vant组件源码 通过git下载vant源码 git clone https://github…

【适配器模式】—— 每天一点小知识

&#x1f4a7; 适配器模式 \color{#FF1493}{适配器模式} 适配器模式&#x1f4a7; &#x1f337; 仰望天空&#xff0c;妳我亦是行人.✨ &#x1f984; 个人主页——微风撞见云的博客&#x1f390; &#x1f433; 《数据结构与算法》专栏的文章图文并茂&#x1f995;…

Kafka学习笔记(基础篇)

目录 Kafka简介 消息队列 Kafka的应用场景 消息队列的两种模型 Kafka集群搭建 Kafka的生产者/消费者/工具 Kafka的基准测试工具 Kafka Java API开发 生产者程序开发 消费者程序开发 生产者使用异步方式生产消息 Kafka中的重要概念 消费者组 幂等性 事务编程 Ka…

英文单词的3σ值

最近做log的nlp&#xff0c;发现日志当中有一些很长的但是无意义的词汇&#xff0c;很影响训练模型&#xff0c;这边想通过单次长度去排除那些无意义词汇&#xff0c;去查了gpt英文单次的3σ值&#xff0c;记录下

谷歌浏览器中的谷歌翻译失效了?如何解决谷歌翻译不响应问题?

1 原因分析 因为谷歌把国内的服务器关了。 2 下载软件 &#xff08;1&#xff09;Mac OS https://github.com/Ponderfly/GoogleTranslateIpCheck/releases/download/1.6/GoogleTranslateIpCheck-mac-x64.zip&#xff08;2&#xff09;Windows https://github.com/Ponderfl…