Elasticsearch8.x版本中RestHighLevelClient被弃用,新版本中全新的Java客 ...

打印 上一主题 下一主题

主题 837|帖子 837|积分 2511

Es的java API客户端

在Es7.15版本之后,es官方将它的高级客户端RestHighLevelClient标记为弃用状态。同时推出了全新的java API客户端Elasticsearch Java API Client,该客户端也将在Elasticsearch8.0及以后版本中成为官方推荐使用的客户端。
Elasticsearch Java API Client支持除Vector title search API和Find structure API之外的所有Elasticsearch API。且支持所有API数据类型,而且不再有原始JSON Value属性。它是针对Elasticsearch8.0及之后版本的客户端。
感爱好的小同伴可以去官方文档看看:Elasticsearch官网8.x版本下Java客户端文档—Elasticsearch Java API Client使用
新建maven项目

maven中引入依赖坐标
  1.         <dependency>
  2.             <groupId>co.elastic.clients</groupId>
  3.             <artifactId>elasticsearch-java</artifactId>
  4.             <version>8.1.0</version>
  5.         </dependency>
  6.          <dependency>
  7.             <groupId>com.fasterxml.jackson.core</groupId>
  8.             <artifactId>jackson-databind</artifactId>
  9.             <version>2.13.1</version>
  10.         </dependency>
  11.         <dependency>
  12.             <groupId>junit</groupId>
  13.             <artifactId>junit</artifactId>
  14.             <version>4.12</version>
  15.         </dependency>
  16.         <dependency>
  17.             <groupId>org.projectlombok</groupId>
  18.             <artifactId>lombok</artifactId>
  19.             <version>1.18.22</version>
  20.             <scope>provided</scope>
  21.         </dependency>
复制代码
创建毗连

  1.     @Test
  2.     public void create() throws IOException {
  3.         // 创建低级客户端
  4.         RestClient restClient = RestClient.builder(
  5.                 new HttpHost("localhost", 9200)
  6.         ).build();
  7.         // 使用Jackson映射器创建传输层
  8.         ElasticsearchTransport transport = new RestClientTransport(
  9.                 restClient, new JacksonJsonpMapper()
  10.         );
  11.         // 创建API客户端
  12.         ElasticsearchClient client = new ElasticsearchClient(transport);
  13.         // 关闭ES客户端
  14.         transport.close();
  15.         restClient.close();
  16.     }
复制代码
索引index的基本语法

创建索引

  1.     @Test
  2.     public void create() throws IOException {
  3.         // 创建低级客户端
  4.         RestClient restClient = RestClient.builder(
  5.                 new HttpHost("localhost", 9200)
  6.         ).build();
  7.         // 使用Jackson映射器创建传输层
  8.         ElasticsearchTransport transport = new RestClientTransport(
  9.                 restClient, new JacksonJsonpMapper()
  10.         );
  11.         // 创建API客户端
  12.         ElasticsearchClient client = new ElasticsearchClient(transport);
  13.         // 创建索引
  14.         CreateIndexResponse createIndexResponse = client.indices().create(c -> c.index("user_test"));
  15.         // 响应状态
  16.         Boolean acknowledged = createIndexResponse.acknowledged();
  17.         System.out.println("索引操作 = " + acknowledged);
  18.         // 关闭ES客户端
  19.         transport.close();
  20.         restClient.close();
  21.     }
复制代码
查询索引

  1.     @Test
  2.     public void query() throws IOException {
  3.         RestClient restClient = RestClient.builder(
  4.                 new HttpHost("localhost",9200)
  5.         ).build();
  6.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  7.         ElasticsearchClient client = new ElasticsearchClient(transport);
  8.         // 查询索引
  9.         GetIndexResponse getIndexResponse = client.indices().get(e -> e.index("user_test"));
  10.         System.out.println("getIndexResponse.result() = " + getIndexResponse.result());
  11.         System.out.println("getIndexResponse.result().keySet() = " + getIndexResponse.result().keySet());
  12.         transport.close();
  13.         restClient.close();
  14.     }
复制代码

删除索引

  1.     @Test
  2.     public void delete() throws IOException {
  3.         RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
  4.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  5.         ElasticsearchClient client = new ElasticsearchClient(transport);
  6.         // 删除索引
  7.         DeleteIndexResponse deleteIndexResponse = client.indices().delete(e -> e.index("user_test"));
  8.         System.out.println("删除操作 = " + deleteIndexResponse.acknowledged());
  9.         transport.close();
  10.         restClient.close();
  11.     }
复制代码
文档document的操作

创建User对象
  1. @Data
  2. @AllArgsConstructor
  3. @NoArgsConstructor
  4. public class User {
  5.     private String name;
  6.     private String sex;
  7.     private Integer age;
  8. }
复制代码
添加document

  1.     @Test
  2.     public void addDocument() throws IOException {
  3.         RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
  4.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  5.         ElasticsearchClient client = new ElasticsearchClient(transport);
  6.         // 向user对象中添加数据
  7.         User user = new User("java客户端", "男", 18);
  8.         // 向索引中添加数据
  9.         CreateResponse createResponse = client.create(e -> e.index("user_test").id("1001").document(user));
  10.         System.out.println("createResponse.result() = " + createResponse.result());
  11.         transport.close();
  12.         restClient.close();
  13.     }
复制代码
  1. $\color{red}{注:index中参数为文档所属的索引名,id中参数为当文档的id,document为文档数据,新版本支持直接传入java对象.} $  
复制代码
查询document

  1.     @Test
  2.     public void queryDocument() throws IOException {
  3.         RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
  4.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  5.         ElasticsearchClient client = new ElasticsearchClient(transport);
  6.         // 构建请求
  7.         GetResponse<User> getResponse = client.get(e -> e.index("user_test").id("1001"), User.class);
  8.         System.out.println("getResponse.source().toString() = " + getResponse.source().toString());
  9.         transport.close();
  10.         restClient.close();
  11.     }
复制代码

修改document

  1.     @Test
  2.     public void modifyDocument() throws IOException {
  3.         RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
  4.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  5.         ElasticsearchClient client = new ElasticsearchClient(transport);
  6.         // 使用map集合封装需要修改的内容
  7.         Map<String, Object> map = new HashMap<>();
  8.         map.put("name", "java客户端aaa");
  9.         // 构建请求
  10.         UpdateResponse<User> updateResponse = client.update(e -> e.index("user_test").id("1001").doc(map), User.class);
  11.         System.out.println("updateResponse.result() = " + updateResponse.result());
  12.         transport.close();
  13.         restClient.close();
  14.     }
复制代码
删除document

  1.     @Test
  2.     public void removeDocument() throws  IOException {
  3.         RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
  4.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  5.         ElasticsearchClient client = new ElasticsearchClient(transport);
  6.         // 构建请求
  7.         DeleteResponse deleteResponse = client.delete(e -> e.index("user_test").id("1001"));
  8.         System.out.println("deleteResponse.result() = " + deleteResponse.result());
  9.         transport.close();
  10.         restClient.close();
  11.     }
复制代码
批量添加document

  1.     @Test
  2.     public void batchAddDocument() throws IOException {
  3.         RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
  4.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  5.         ElasticsearchClient client = new ElasticsearchClient(transport);
  6.         // 构建一个批量数据集合
  7.         List<BulkOperation> list = new ArrayList<>();
  8.         list.add(new BulkOperation.Builder().create(
  9.                 d -> d.document(new User("test2", "男", 19)).id("1002").index("user_test")).build());
  10.         list.add(new BulkOperation.Builder().create(
  11.                 d -> d.document(new User("test3", "男", 20)).id("1003").index("user_test")).build());
  12.         list.add(new BulkOperation.Builder().create(
  13.                 d -> d.document(new User("test4", "女", 21)).id("1004").index("user_test")).build());
  14.         // 调用bulk方法执行批量插入操作
  15.         BulkResponse bulkResponse = client.bulk(e -> e.index("user_test").operations(list));
  16.         System.out.println("bulkResponse.items() = " + bulkResponse.items());
  17.         transport.close();
  18.         restClient.close();
  19.     }
复制代码

批量删除

  1.     @Test
  2.     public void batchDeleteDocument() throws IOException {
  3.         RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
  4.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  5.         ElasticsearchClient client = new ElasticsearchClient(transport);
  6.         // 构建一个批量数据集合
  7.         List<BulkOperation> list = new ArrayList<>();
  8.         list.add(new BulkOperation.Builder().delete(
  9.                 d -> d.id("1002").index("user_test")).build());
  10.         list.add(new BulkOperation.Builder().delete(
  11.                 d -> d.id("1003").index("user_test")).build());
  12.         // 调用bulk方法执行批量插入操作
  13.         BulkResponse bulkResponse = client.bulk(e -> e.index("user_test").operations(list));
  14.         System.out.println("bulkResponse.items() = " + bulkResponse.items());
  15.         transport.close();
  16.         restClient.close();
  17.     }
复制代码
全量查询

  1.     @Test
  2.     public void queryAllDocument() throws IOException {
  3.         RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
  4.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  5.         ElasticsearchClient client = new ElasticsearchClient(transport);
  6.         // 全量查询
  7.         SearchResponse<User> searchResponse = client.search(e -> e.index("user_test").query(q -> q.matchAll(m -> m)), User.class);
  8.         HitsMetadata<User> hits = searchResponse.hits();
  9.         for (Hit<User> hit : hits.hits()) {
  10.             System.out.println("user = " + hit.source().toString());
  11.         }
  12.         System.out.println("searchResponse.hits().total().value() = " + searchResponse.hits().total().value());
  13.         transport.close();
  14.         restClient.close();
  15.     }
复制代码
分页查询

  1.     @Test
  2.     public void pagingQueryDocument() throws IOException {
  3.         RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
  4.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  5.         ElasticsearchClient client = new ElasticsearchClient(transport);
  6.         // 分页查询
  7.         SearchResponse<User> searchResponse = client.search(
  8.                 s -> s.index("user_test")
  9.                         .query(q -> q.matchAll(m -> m))
  10.                         .from(2)
  11.                         .size(2)
  12.                 , User.class);
  13.         searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
  14.         transport.close();
  15.         restClient.close();
  16.     }
复制代码

排序查询

  1.     @Test
  2.     public void sortQueryDocument() throws IOException {
  3.         RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
  4.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  5.         ElasticsearchClient client = new ElasticsearchClient(transport);
  6.         // 排序查询
  7.         SearchResponse<User> searchResponse = client.search(
  8.                 s -> s.index("user_test")
  9.                         .query(q -> q.matchAll(m -> m))
  10.                         .sort(o -> o.field(f -> f.field("age").order(SortOrder.Asc)))
  11.                 , User.class);
  12.         searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
  13.         transport.close();
  14.         restClient.close();
  15.     }
复制代码
条件查询

  1.     @Test
  2.     public void conditionQueryDocument() throws IOException {
  3.         RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
  4.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  5.         ElasticsearchClient client = new ElasticsearchClient(transport);
  6.         // 条件查询
  7.         SearchResponse<User> searchResponse = client.search(
  8.                 s -> s.index("user_test").query(q -> q.matchAll(m -> m))
  9.                         .sort(o -> o.field(f -> f.field("age").order(SortOrder.Asc)))
  10.                         .source(r -> r.filter(f -> f.includes("name", "age").excludes("")))
  11.                 , User.class);
  12.         searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
  13.         transport.close();
  14.         restClient.close();
  15.     }
复制代码

组合查询

  1.     @Test
  2.     public void combinationQueryDocument() throws IOException {
  3.         RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
  4.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  5.         ElasticsearchClient client = new ElasticsearchClient(transport);
  6.         // 组合查询
  7.         SearchResponse<User> searchResponse = client.search(
  8.                 s -> s.index("user_test").query(q -> q.bool(b -> b
  9.                         .must(m -> m.match(u -> u.field("age").query(21)))
  10.                         .must(m -> m.match(u -> u.field("sex").query("男")))
  11.                         .mustNot(m -> m.match(u -> u.field("sex").query("女")))
  12.                 ))
  13.                 , User.class);
  14.         searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
  15.         transport.close();
  16.         restClient.close();
  17.     }
复制代码
  1.     @Test
  2.     public void combinationQueryDocument2() throws IOException {
  3.         RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
  4.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  5.         ElasticsearchClient client = new ElasticsearchClient(transport);
  6.         // 组合查询
  7.         SearchResponse<User> searchResponse = client.search(
  8.                 s -> s.index("user_test").query(q -> q.bool(b -> b
  9.                         .should(h -> h.match(u -> u.field("age").query(19)))
  10.                         .should(h -> h.match(u -> u.field("sex").query("男")))
  11.                 ))
  12.                 , User.class);
  13.         searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
  14.         transport.close();
  15.         restClient.close();
  16.     }
复制代码
must是必须满足所有条件,should只要满足一个就行
范围查询

  1.     @Test
  2.     public void scopeQueryDocument2() throws IOException {
  3.         RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
  4.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  5.         ElasticsearchClient client = new ElasticsearchClient(transport);
  6.         // 范围查询,gte()表示取大于等于,gt()表示大于,lte()表示小于等于
  7.         SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").query(q -> q
  8.                         .range(r -> r.field("age").gte(JsonData.of(20)).lt(JsonData.of(21))))
  9.                 , User.class);
  10.         searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
  11.         transport.close();
  12.         restClient.close();
  13.     }
复制代码
含糊查询

  1.     @Test
  2.     public void fuzzyQueryDocument2() throws IOException {
  3.         RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
  4.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  5.         ElasticsearchClient client = new ElasticsearchClient(transport);
  6.         // 模糊查询,fuzziness表示差几个可以查询出来
  7.         SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").query(q -> q
  8.                         .fuzzy(f -> f.field("name").value("tst").fuzziness("2")))
  9.                 , User.class);
  10.         searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
  11.         transport.close();
  12.         restClient.close();
  13.     }
复制代码
高亮查询

  1.     @Test
  2.     public void highlightQueryDocument2() throws IOException {
  3.         RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
  4.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  5.         ElasticsearchClient client = new ElasticsearchClient(transport);
  6.         // 高亮查询
  7.         SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").query(q -> q
  8.                         .term(t -> t.field("name").value("test3")))
  9.                         .highlight(h -> h.fields("name", f -> f.preTags("<font color='red'>").postTags("</font>")))
  10.                 , User.class);
  11.         searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
  12.         transport.close();
  13.         restClient.close();
  14.     }
复制代码
聚合查询

  1.     @Test
  2.     public void aggregateQueryDocument2() throws IOException {
  3.         RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
  4.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  5.         ElasticsearchClient client = new ElasticsearchClient(transport);
  6.         // 聚合查询,取最大年龄
  7.         SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").aggregations("maxAge", a ->a.max(m -> m.field("age")))
  8.                 , User.class);
  9.         searchResponse.aggregations().entrySet().forEach(f -> System.out.println(f.getKey() + ":" + f.getValue().max().value()));
  10.         transport.close();
  11.         restClient.close();
  12.     }
复制代码
分组查询

  1.     @Test
  2.     public void groupQueryDocument2() throws IOException {
  3.         RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
  4.         ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
  5.         ElasticsearchClient client = new ElasticsearchClient(transport);
  6.         // 分组查询
  7.         SearchResponse<User> searchResponse = client.search(s -> s.index("user_test")
  8.                         .aggregations("ageGroup", a ->a.terms(t -> t.field("age")))
  9.                 , User.class);
  10.         searchResponse.aggregations().get("ageGroup").lterms().buckets().array().forEach(f -> System.out.println(f.key() + ":" + f.docCount()));
  11.         transport.close();
  12.         restClient.close();
  13.     }
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

tsx81429

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表