当前位置: 首页 > news >正文

SpringBoot集成Elasticsearch8.x(9)|(RestClient实现Elasticsearch DSL操作)

SpringBoot集成Elasticsearch8.x(9)|(RestClient curl实现Elasticsearch DSL的操作)


文章目录

  • SpringBoot集成Elasticsearch8.x(9)|(RestClient curl实现Elasticsearch DSL的操作)
    • @[TOC]
  • 前言
  • 一、DSL 介绍
  • 二、初始化客户端
  • 三、封装RestClient dsl执行
  • 三、更新
    • 1.实用script更新es中数据
  • 总结

章节
第一章链接: SpringBoot集成Elasticsearch7.x(1)|(增删改查功能实现)
第二章链接: SpringBoot集成Elasticsearch7.x(2)|(复杂查询)
第三章链接: SpringBoot集成Elasticsearch7.x(3)|(aggregations之指标聚合查询)
第四章链接: SpringBoot集成Elasticsearch7.x(4)|(aggregations之分桶聚合查询)
第五章链接: SpringBoot集成Elasticsearch7.x(5)|(term、match、match_phrase区别)
第六章链接: SpringBoot集成Elasticsearch8.x(6)|(新版本Java API Client使用)
第七章链接: SpringBoot集成Elasticsearch8.x(7)|(新版本Java API Client使用完整示例)
第八章链接:SpringBoot集成Elasticsearch8.x(8)|(新版本Java API Client的Painless语言脚本script使用)
第九章链接:SpringBoot集成Elasticsearch8.x(9)|(RestClient实现Elasticsearch的操作)

前言

Elasticsearch curl命令
-XGET一种请求方法
-d 标识以post形式传入参数 ,写在请求正文里面
?pretty=true 以格式的形式显示结果
curl -XGET http://localhost:9200/_cluster/health?pretty --查询elasticsearch的健康信息
curl -XGET http://localhost:9200/ --查询实例的相关信息
curl -XGET http://localhost:9200/_cluster/nodes/ --得到集群中节点的相关信息
curl -XPOST http://localhost:9200/_cluster/nodes/_shutdown --关闭整个集群
curl -XPOST http://localhost:9200/_cluster/nodes/aaaa/_shutdown --关闭集群中指定节点
curl -XPOST http://localhost:9200/test --创建名为test的索引
curl -XDELETE http://localhost:9200/test --删除名为test的索引
curl -XGET ‘http://10.10.110.2:19200/benlaitest/_search?pretty=true’ -d ‘{“query”:{“multi_match”:{“query”:“法国”,“fields”:[“firstname”,“lastname”]}}}’ --查询数据(匹配firstname和lastname)
curl http://10.10.110.160:9200/benlaitest/_analyze?analyzer=standard -d 我爱你中国
postman执行请求API:
http://10.10.110.160:9200/_cat/indices?v – Get请求 查看有多少索引
http://10.10.110.160:9200/benlaitest/_analyze?analyzer=standard --查看分词结果

一、DSL 介绍

Elasticsearch提供丰富且灵活的查询语言叫做DSL查询(Query DSL),它允许你构建更加复杂、强大的查询。DSL(Domain Specific Language特定领域语言)以JSON请求体的形式出现。

简单实用

//查询所有的商品
GET /product_index/product/_search
{"query": {"match_all": {}
}
//查询商品名称包含 milk 的商品,同时按照价格降序排序
GET /product_index/product/_search
{"query": {"match": {"product_name": "milk"}},"sort": [{"price": "desc"}]
}

二、初始化客户端

简单实用

    @Beanprivate RestClient buildClient(EsClientProperties properties, HttpHost[] hostList) {int timeout = properties.getTimeout() == 0 ? 5000 : properties.getTimeout();String authorization = String.format("Basic %s", Base64.getEncoder().encodeToString(String.format("%s:%s", properties.getUser(), properties.getPwd()).getBytes(StandardCharsets.UTF_8)));Header[] headers = new Header[]{new BasicHeader("Authorization", authorization)};return RestClient.builder(hostList).setDefaultHeaders(headers).setRequestConfigCallback((rc) -> {return rc.setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout);}).build();}

三、封装RestClient dsl执行

  /*** 查询所有的索引信息*/@Testpublic void searchIndices() {RestClient client = EsConfig.initClient();Request request = new Request("GET", "/_cat/indices?v");try {Response response = client.performRequest(request);System.out.println(EntityUtils.toString(response.getEntity()));} catch (IOException exception) {LOGGER.info(exception.getMessage());} finally {try {client.close();} catch (IOException exception) {LOGGER.info(exception.getMessage());}}}/*** 根据索引id查询索引信息*/@Testpublic void searchIndexById() {RestClient client = EsConfig.initClient();Request request = new Request("Get", "/20220325001/");try {Response response = client.performRequest(request);System.out.println(EntityUtils.toString(response.getEntity()));} catch (IOException exception) {LOGGER.info(exception.getMessage());} finally {try {client.close();} catch (IOException exception) {LOGGER.info(exception.getMessage());}}}/*** 根据条件查询*/public void queryMatch() throws IOException {RestClient client = EsConfig.initClient();Request request = new Request("POST", "/20220325001/_search?filter_path=hits");request.setJsonEntity(" {\n" +"    \"query\":{\n" +"        \"match_all\":{\n" +"            \n" +"        }\n" +"    }\n" +"}");Response response = client.performRequest(request);System.out.println(EntityUtils.toString(response.getEntity()));client.close();}

三、更新

1.实用script更新es中数据

模板数据

{"script": {"source": "ctx._source.props.versionList.add(params.newElement)","lang": "painless","params": {"newElement": "NEW_VERSION"}},"query": {"bool": {"must": [{"terms": {"props.versionList": ["FROM_VERSION"]}},{"term": {"dbName": "DB_NAME"}}]}}
}{"script": {"source": "ctx._source.props.versionList.removeAll(Collections.singleton(params.valueToRemove))","lang": "painless","params": {"valueToRemove": "TARGET_VERSION"}},"query": {"terms": {"_id": "VECTOR_ID_LIST"}}
}

scritp模板使用

    private String buildDeleteVersionDsl(List<String> vectorIds, Integer version) {return versionDelDslTemplate.replaceAll("\"VECTOR_ID_LIST\"", JSONObject.toJSONString(vectorIds)) //.replaceAll("\"TARGET_VERSION\"", version.toString());}

统一调用方法

private String performRequest(String method, String path, String jsonParam) throws IOException {Request request = new Request(method, path);if (StringUtils.isNotBlank(jsonParam)) {request.setEntity(new NStringEntity(jsonParam, ContentType.APPLICATION_JSON));}LOGGER.debug("es request: method:{}, path:{}, param:{}", new Object[]{method, path, jsonParam});Response response;try {response = this.restClient.performRequest(request);} catch (IOException var8) {LOGGER.error("es server exception:{}.\n dsl:{}\n", var8.getMessage(), jsonParam);throw new RuntimeException(var8);}LOGGER.debug("es response:{}", response);int statusCode = response.getStatusLine().getStatusCode();String msg;if (statusCode >= 200 && statusCode < 300) {msg = EntityUtils.toString(response.getEntity());LOGGER.debug("es response content:{}", msg);return msg;} else {msg = String.format("Error when request:%s, response:%s ", request, response);LOGGER.error("es server error:{}.\n, dsl:{}\n", msg, jsonParam);throw new RestException(statusCode, msg);}}

总结

以上就是elasticsearch RestClient 中使用script对数据镜像批量跟新的操作,语法熟悉了操作起来还是很简单的。

相关文章:

  • deepface:实现人脸的识别和分析
  • 3GPP标准查看、下载和几个UE相关系列标准
  • Transformer源码(带注释)
  • 机器学习中Fine-tuning应用实例
  • nginx配置正向代理支持https
  • 判断上三角矩阵
  • ORACLE使用Mybatis-plus批量插入
  • 12月12日作业
  • 2024年AI云计算专题研究报告:智算带来的变化
  • 黑客应该从小抓起
  • linux 中crontab 定时任务计划创建时间文件夹示例
  • C语言leetcode集训一:数组
  • Centos7、Mysql8.0 load_file函数返回为空的终极解决方法--暨selinux的深入理解
  • AI工具导航网站(包含写作、翻译、设计、论文润色去重的AI工具集)
  • Command ‘npm‘ not found, but can be installed with:sudo apt install npm 解决方案
  • php的引用
  • 《用数据讲故事》作者Cole N. Knaflic:消除一切无效的图表
  • 【笔记】你不知道的JS读书笔记——Promise
  • Debian下无root权限使用Python访问Oracle
  • HTTP--网络协议分层,http历史(二)
  • javascript数组去重/查找/插入/删除
  • Netty源码解析1-Buffer
  • nodejs实现webservice问题总结
  • Python socket服务器端、客户端传送信息
  • Shell编程
  • vue-router 实现分析
  • 深度学习中的信息论知识详解
  • 一个6年java程序员的工作感悟,写给还在迷茫的你
  • Salesforce和SAP Netweaver里数据库表的元数据设计
  • #100天计划# 2013年9月29日
  • #微信小程序(布局、渲染层基础知识)
  • (+3)1.3敏捷宣言与敏捷过程的特点
  • (1)(1.8) MSP(MultiWii 串行协议)(4.1 版)
  • (C语言)输入一个序列,判断是否为奇偶交叉数
  • (Matlab)使用竞争神经网络实现数据聚类
  • (zz)子曾经曰过:先有司,赦小过,举贤才
  • (搬运以学习)flask 上下文的实现
  • (二)pulsar安装在独立的docker中,python测试
  • (附源码)ssm高校社团管理系统 毕业设计 234162
  • (附源码)ssm码农论坛 毕业设计 231126
  • (一)Java算法:二分查找
  • *++p:p先自+,然后*p,最终为3 ++*p:先*p,即arr[0]=1,然后再++,最终为2 *p++:值为arr[0],即1,该语句执行完毕后,p指向arr[1]
  • .NET Standard 的管理策略
  • .NET 线程 Thread 进程 Process、线程池 pool、Invoke、begininvoke、异步回调
  • .NET基础篇——反射的奥妙
  • .NET开源全面方便的第三方登录组件集合 - MrHuo.OAuth
  • .net使用excel的cells对象没有value方法——学习.net的Excel工作表问题
  • .net专家(张羿专栏)
  • [ C++ ] STL---string类的使用指南
  • [120_移动开发Android]008_android开发之Pull操作xml文件
  • [Android]Android P(9) WIFI学习笔记 - 扫描 (1)
  • [Android]一个简单使用Handler做Timer的例子
  • [BUUCTF 2018]Online Tool
  • [BZOJ1877][SDOI2009]晨跑[最大流+费用流]
  • [C#]C# winform实现imagecaption图像生成描述图文描述生成