当前位置:   article > 正文

Java(100):Java操作elasticsearch增删查(按条件查删)(RestHighLevelClient)_java根据id删除一条es的数据数据

java根据id删除一条es的数据数据

Java操作elasticsearch增删查(RestHighLevelClient)

版本:elasticsearch7.14

一、参考官网API

1、Index API | Java REST Client [7.14] | Elastic

https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.14/java-rest-high-document-index.html

搜索:

2、 Search API | Java REST Client [7.14] | Elastic

https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.14/java-rest-high-search.html

二、Java操作ES增删查(RestHighLevelClient)

2.1、引用依赖

RestHighLevelClient的maven依赖为(使用前必须添加相应依赖)

<!-- https://mvnrepository.com/artifact/org.elasticsearch.client/elasticsearch-rest-high-level-client -->
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.14.0</version>
</dependency>

注意:以上的依赖版本可以根据你使用的ES的版本来定,向下兼容,但是无法向上兼容

2.2、创建ES连接和关闭连接

  1. private RestHighLevelClient esRestClient = null;
  2. /**
  3. * 创建客户端连接
  4. */
  5. public void restClientConnect(String IP,int PORT){
  6. RestHighLevelClient restClient=null;
  7. try {
  8. RestClientBuilder builder = RestClient.builder(new HttpHost(IP, PORT, "http"));
  9. restClient= new RestHighLevelClient(builder);
  10. }catch (Exception e){
  11. log.error(e.toString());
  12. }
  13. this.esRestClient = restClient;
  14. }
  15. /**
  16. * 关闭客户端
  17. */
  18. public void closeEs() {
  19. try {
  20. if(esRestClient !=null) {
  21. esRestClient.close();
  22. }
  23. }catch (IOException e){
  24. e.printStackTrace();
  25. }
  26. }

2.3、新增数据

RestHighLevelClient 支持对ES的增删改查、批量操作

  1. /**
  2. * 往索引插入文档数据,随机id插入数据
  3. * @param indexName 索引名称
  4. * @param jsonStr Json数据
  5. */
  6. public void addData(String indexName,String jsonStr){
  7. addData(indexName,jsonStr,null);
  8. }
  9. /**
  10. * 往索引插入文档数据
  11. * @param indexName 索引名称
  12. * @param jsonStr Json数据
  13. * @param id id
  14. */
  15. public void addData(String indexName,String jsonStr,String id){
  16. IndexRequest request = new IndexRequest(indexName);
  17. if(id !=null){
  18. request.id(id);
  19. }
  20. request.source(jsonStr, XContentType.JSON);
  21. request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);//插入完成后立即强制刷新索引
  22. try {
  23. IndexResponse response = esRestClient.index(request,RequestOptions.DEFAULT);
  24. log.info("addData: "+response.getShardInfo()+" ,indexName:"+indexName);
  25. } catch (Exception e) {
  26. e.printStackTrace();
  27. }
  28. }

2.4、查询数据

查询支持直接查询和条件查询,由于ES是根据索引、文档类型和文档ID确定一个唯一的文档的,所以直接查询必须要有索引和类型还有ID。

  1. /**
  2. * 根据条件获取文档数据
  3. * @param indexName 索引名称
  4. */
  5. public void getData(String indexName) {
  6. //1 创建搜索文档请求
  7. SearchRequest searchRequest=new SearchRequest(indexName); //请求索引
  8. try{
  9. // 2 执行检索
  10. SearchResponse response = esRestClient.search(searchRequest, RequestOptions.DEFAULT);
  11. // 3 分析响应结果
  12. //System.out.println(response.toString());
  13. //遍历数据
  14. SearchHit[] hits = response.getHits().getHits();
  15. for (SearchHit hit : hits) {
  16. Map<String, Object> sourceAsMap = hit.getSourceAsMap();
  17. log.info("getData: "+sourceAsMap.toString()+" ,indexName:"+indexName);
  18. }
  19. } catch (Exception e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. /**
  24. * 根据条件获取文档数据
  25. * @param indexName 索引名称
  26. * @param key 查询字段
  27. * @param value 查询值
  28. */
  29. public void getData(String indexName,String key,String value) {
  30. //1 创建搜索文档请求
  31. SearchRequest searchRequest=new SearchRequest(indexName); //请求索引
  32. SearchSourceBuilder builder = new SearchSourceBuilder();
  33. builder.query(QueryBuilders.matchQuery(key,value));
  34. searchRequest.source(builder);
  35. try{
  36. // 2 执行检索
  37. SearchResponse response = esRestClient.search(searchRequest, RequestOptions.DEFAULT);
  38. // 3 分析响应结果
  39. log.info("getData: "+response.toString());
  40. //遍历数据
  41. SearchHit[] hits = response.getHits().getHits();
  42. for (SearchHit hit : hits) {
  43. //String sourceAsString = hit.getSourceAsString();
  44. //System.out.println(sourceAsString);
  45. Map<String, Object> sourceAsMap = hit.getSourceAsMap();
  46. log.info("getData: "+sourceAsMap+" ,indexName:"+indexName);
  47. }
  48. } catch (Exception e) {
  49. e.printStackTrace();
  50. }
  51. }

2.5、删除数据

  1. /**
  2. * 根据索引和id进行删除
  3. * @param indexName 索引名称
  4. * @param id id号
  5. */
  6. public void deleteData(String indexName,String id) {
  7. //创建删除文档请求
  8. DeleteRequest request = new DeleteRequest();
  9. //设置属性:指定要删除的索引及id值
  10. DeleteRequest delete = request.index(indexName).id(id);
  11. try {
  12. //执行删除请求
  13. DeleteResponse deleteResponse = esRestClient.delete(delete, RequestOptions.DEFAULT);
  14. if(deleteResponse.getResult().toString().equals("DELETED")){
  15. log.info("deleteData,删除成功,indexName: "+indexName+",id: "+id);
  16. }
  17. }catch (IOException e){
  18. e.printStackTrace();
  19. }
  20. }
  21. /**
  22. * 根据条件进行删除
  23. * @param indexName 索引名称
  24. * @param key 字段
  25. * @param value 值
  26. */
  27. public void deleteData(String indexName,String key,String value) {
  28. //1 设置条件
  29. //设置删除条件: key = value
  30. MatchQueryBuilder nameSelect = QueryBuilders.matchQuery(key, value);
  31. //通过QueryBuilders中的搜索逻辑
  32. BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
  33. queryBuilder.should(nameSelect);
  34. //2 通过DeleteByQueryRequest来构建删除请求,setQuery来装载条件,indices来指定索引
  35. DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
  36. deleteByQueryRequest.setQuery(queryBuilder);
  37. deleteByQueryRequest.indices(indexName); //指定删除索引
  38. try {
  39. //3 通过deleteByQuery来发起删除请求
  40. BulkByScrollResponse deleteResponse=esRestClient.deleteByQuery(deleteByQueryRequest , RequestOptions.DEFAULT);
  41. if(deleteResponse.getDeleted() >=1){
  42. log.info("deleteData,删除成功,删除文档条数: "+deleteResponse.getDeleted()+" ,indexName:"+indexName);
  43. }
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. }
  47. }

三、代码示例

  1. package elasticsearch;
  2. import org.apache.http.HttpHost;
  3. import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
  4. import org.elasticsearch.client.indices.CreateIndexRequest;
  5. import org.elasticsearch.client.indices.CreateIndexResponse;
  6. import org.elasticsearch.action.admin.indices.get.GetIndexRequest;
  7. import org.elasticsearch.action.delete.DeleteRequest;
  8. import org.elasticsearch.action.delete.DeleteResponse;
  9. import org.elasticsearch.action.index.IndexRequest;
  10. import org.elasticsearch.action.index.IndexResponse;
  11. import org.elasticsearch.action.search.SearchRequest;
  12. import org.elasticsearch.action.search.SearchResponse;
  13. import org.elasticsearch.action.support.WriteRequest;
  14. import org.elasticsearch.action.support.master.AcknowledgedResponse;
  15. import org.elasticsearch.client.*;
  16. import org.elasticsearch.common.xcontent.XContentType;
  17. import org.elasticsearch.index.query.BoolQueryBuilder;
  18. import org.elasticsearch.index.query.MatchQueryBuilder;
  19. import org.elasticsearch.index.query.QueryBuilders;
  20. import org.elasticsearch.index.reindex.BulkByScrollResponse;
  21. import org.elasticsearch.index.reindex.DeleteByQueryRequest;
  22. import org.elasticsearch.search.SearchHit;
  23. import org.elasticsearch.search.builder.SearchSourceBuilder;
  24. import org.slf4j.Logger;
  25. import org.slf4j.LoggerFactory;
  26. import java.io.IOException;
  27. import java.util.Map;
  28. /**
  29. * ClassName EsTest
  30. * description EsTest
  31. *
  32. * @author : HMF
  33. * date: 2022/8/18 9:35
  34. **/
  35. public class EsTest {
  36. protected static Logger log = LoggerFactory.getLogger(EsTest.class);
  37. private RestHighLevelClient esRestClient = null;
  38. /**
  39. * 创建客户端
  40. */
  41. public void restClientConnect(String IP,int PORT){
  42. RestHighLevelClient restClient=null;
  43. try {
  44. RestClientBuilder builder = RestClient.builder(new HttpHost(IP, PORT, "http"));
  45. restClient= new RestHighLevelClient(builder);
  46. }catch (Exception e){
  47. log.error(e.toString());
  48. }
  49. this.esRestClient = restClient;
  50. }
  51. /**
  52. * 往索引插入文档数据,随机id插入数据
  53. * @param indexName 索引名称
  54. * @param jsonStr Json数据
  55. */
  56. public void addData(String indexName,String jsonStr){
  57. addData(indexName,jsonStr,null);
  58. }
  59. /**
  60. * 往索引插入文档数据
  61. * @param indexName 索引名称
  62. * @param jsonStr Json数据
  63. * @param id id
  64. */
  65. public void addData(String indexName,String jsonStr,String id){
  66. IndexRequest request = new IndexRequest(indexName);
  67. if(id !=null){
  68. request.id(id);
  69. }
  70. request.source(jsonStr, XContentType.JSON);
  71. request.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);//插入完成后立即强制刷新索引
  72. try {
  73. IndexResponse response = esRestClient.index(request,RequestOptions.DEFAULT);
  74. log.info("addData: "+response.getShardInfo()+" ,indexName:"+indexName);
  75. } catch (Exception e) {
  76. e.printStackTrace();
  77. }
  78. }
  79. /**
  80. * 根据条件获取文档数据
  81. * @param indexName 索引名称
  82. */
  83. public void getData(String indexName) {
  84. //1 创建搜索文档请求
  85. SearchRequest searchRequest=new SearchRequest(indexName); //请求索引
  86. try{
  87. // 2 执行检索
  88. SearchResponse response = esRestClient.search(searchRequest, RequestOptions.DEFAULT);
  89. // 3 分析响应结果
  90. //System.out.println(response.toString());
  91. //遍历数据
  92. SearchHit[] hits = response.getHits().getHits();
  93. for (SearchHit hit : hits) {
  94. Map<String, Object> sourceAsMap = hit.getSourceAsMap();
  95. log.info("getData: "+sourceAsMap.toString()+" ,indexName:"+indexName);
  96. }
  97. } catch (Exception e) {
  98. e.printStackTrace();
  99. }
  100. }
  101. /**
  102. * 根据条件获取文档数据
  103. * @param indexName 索引名称
  104. * @param key 查询字段
  105. * @param value 查询值
  106. */
  107. public void getData(String indexName,String key,String value) {
  108. //1 创建搜索文档请求
  109. SearchRequest searchRequest=new SearchRequest(indexName); //请求索引
  110. SearchSourceBuilder builder = new SearchSourceBuilder();
  111. builder.query(QueryBuilders.matchQuery(key,value));
  112. searchRequest.source(builder);
  113. try{
  114. // 2 执行检索
  115. SearchResponse response = esRestClient.search(searchRequest, RequestOptions.DEFAULT);
  116. // 3 分析响应结果
  117. log.info("getData: "+response.toString());
  118. //遍历数据
  119. SearchHit[] hits = response.getHits().getHits();
  120. for (SearchHit hit : hits) {
  121. //String sourceAsString = hit.getSourceAsString();
  122. //System.out.println(sourceAsString);
  123. Map<String, Object> sourceAsMap = hit.getSourceAsMap();
  124. log.info("getData: "+sourceAsMap+" ,indexName:"+indexName);
  125. }
  126. } catch (Exception e) {
  127. e.printStackTrace();
  128. }
  129. }
  130. /**
  131. * 根据索引和id进行删除
  132. * @param indexName 索引名称
  133. * @param id id号
  134. */
  135. public void deleteData(String indexName,String id) {
  136. //创建删除文档请求
  137. DeleteRequest request = new DeleteRequest();
  138. //设置属性:指定要删除的索引及id值
  139. DeleteRequest delete = request.index(indexName).id(id);
  140. try {
  141. //执行删除请求
  142. DeleteResponse deleteResponse = esRestClient.delete(delete, RequestOptions.DEFAULT);
  143. if(deleteResponse.getResult().toString().equals("DELETED")){
  144. log.info("deleteData,删除成功,indexName: "+indexName+",id: "+id);
  145. }
  146. }catch (IOException e){
  147. e.printStackTrace();
  148. }
  149. }
  150. /**
  151. * 根据条件进行删除
  152. * @param indexName 索引名称
  153. * @param key 字段
  154. * @param value 值
  155. */
  156. public void deleteData(String indexName,String key,String value) {
  157. //1 设置条件
  158. //设置删除条件: key = value
  159. MatchQueryBuilder nameSelect = QueryBuilders.matchQuery(key, value);
  160. //通过QueryBuilders中的搜索逻辑
  161. BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
  162. queryBuilder.should(nameSelect);
  163. //2 通过DeleteByQueryRequest来构建删除请求,setQuery来装载条件,indices来指定索引
  164. DeleteByQueryRequest deleteByQueryRequest = new DeleteByQueryRequest();
  165. deleteByQueryRequest.setQuery(queryBuilder);
  166. deleteByQueryRequest.indices(indexName); //指定删除索引
  167. try {
  168. //3 通过deleteByQuery来发起删除请求
  169. BulkByScrollResponse deleteResponse=esRestClient.deleteByQuery(deleteByQueryRequest , RequestOptions.DEFAULT);
  170. if(deleteResponse.getDeleted() >=1){
  171. log.info("deleteData,删除成功,删除文档条数: "+deleteResponse.getDeleted()+" ,indexName:"+indexName);
  172. }
  173. } catch (IOException e) {
  174. e.printStackTrace();
  175. }
  176. }
  177. /**
  178. * 关闭客户端
  179. */
  180. public void closeEs() {
  181. try {
  182. if(esRestClient !=null) {
  183. esRestClient.close();
  184. }
  185. }catch (IOException e){
  186. e.printStackTrace();
  187. }
  188. }
  189. }

调用:

  1. public static void main(String[] args){
  2. EsTest es=new EsTest();
  3. es.restClientConnect("10.1.1.196",9200); //创建客户端连接ES
  4. String indexName="autotest_java";
  5. String jsonStr=" {\n" +
  6. " \"aoeId\": \"1\",\n" +
  7. " \"aoeAes\": \"李四\",\n" +
  8. " \"aoeSm4\": \"Beijing Refining Network Technology Co.Ltd.\",\n" +
  9. " \"aoeSm4A\": \"硬件开发工程师\",\n" +
  10. " \"aoeEmail\": \"qianxiulan@yahoo.com\",\n" +
  11. " \"aoePhone\": \"15652996964\",\n" +
  12. " \"aoeIdCard\": \"210302199608124861\",\n" +
  13. " \"aoeOfficerCard\": \"武水电字第3632734号\",\n" +
  14. " \"aoePassport\": \"BWP018930705\",\n" +
  15. " \"aoeGeneralIdCard\": \"0299233902\",\n" +
  16. " \"aoeCreditCard\": \"6212262502009182455\",\n" +
  17. " \"aoeString\":\"北京市海淀区恒润国际大厦710\"\n" +
  18. "}";
  19. es.addData(indexName,jsonStr);
  20. String key="aoeAes";
  21. String value="李四";
  22. es.getData(indexName,key,value);
  23. es.deleteData(indexName,key,value);
  24. //es.addData(indexName,jsonStr,"1");
  25. //es.getData(indexName);
  26. //es.deleteData(indexName,"1");
  27. es.closeEs();
  28. }

执行结果:

 参考:

https://www.jianshu.com/p/48f8911849cb

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/68704
推荐阅读
相关标签
  

闽ICP备14008679号