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對數據鏡像批量跟新的操作,語法熟悉了操作起來還是很簡單的。