SpringBoot集成Elasticsearch8.x(9)|(RestClient curl实现Elasticsearch DSL的操作)
文章目录
- SpringBoot集成Elasticsearch8.x(9)|(RestClient curl实现Elasticsearch DSL的操作)
- @[TOC]
- 前言
- 一、DSL 介绍
- 二、初始化客户端
- 三、封装RestClient dsl执行
- 三、更新
- 1.实用script更新es中数据
- 总结
文章目录
- 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对数据镜像批量跟新的操作,语法熟悉了操作起来还是很简单的。