elasaticsearch新版java客户端ElasticsearchClient详细教程,支持响应式编程,Lambda表达式,兼容旧版High Level Rest Client
文章目录
- 前言
- 一、引入依赖
- 二、配置连接
-
- 1.直接配置连接
- 2.从旧版High Level Rest Client迁移值新版
- 2.Lambda表达式相关api的使用
-
-
- 创建索引
- 写入单个文档
- 批量插入
- 通过id查找文档
- 搜索文档
-
- 聚合文档
-
- 总结
前言
elasaticsearch新版java客户端详细教程,支持响应式编程,Lambda表达式。兼容旧版High Level Rest Client。网上相关教程少,我在这里出一个。elasaticsearch相关安装这里不介绍了
一、引入依赖
<dependency> <groupId>co.elastic.clients</groupId> <artifactId>elasticsearch-java</artifactId> <version>8.2.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.12.3</version> </dependency> <dependency> <groupId>jakarta.json</groupId> <artifactId>jakarta.json-api</artifactId> <version>2.0.1</version> </dependency>
二、配置连接
有几种方式,这里介绍两种,如果不考虑之前旧版High Level Rest Client的客户端采用第一种就行
1.直接配置连接
//同步客户端 public ElasticsearchClient elasticsearchClient(){ ElasticsearchTransport transport = getElasticsearchTransport();// And create the API client ElasticsearchClient client = new ElasticsearchClient(transport); return client; } //elasticsearch异步客户端 public ElasticsearchAsyncClient elasticsearchAsyncClient (){ ElasticsearchTransport transport = getElasticsearchTransport();// And create the API client ElasticsearchAsyncClient client = new ElasticsearchAsyncClient(transport); return client; }//ElasticsearchTransport用于创建客户端 public ElasticsearchTransport getElasticsearchTransport(){ CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));//配置用户名密码 // Create the low-level client RestClient restClient = RestClient.builder( new HttpHost(host, port)) //配置路径 端口 .setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider)) .build();// Create the transport with a Jackson mapper ElasticsearchTransport transport = new RestClientTransport( restClient, new JacksonJsonpMapper()); return transport; }
阻塞和异步客户端
API 客户端有两种形式:阻塞和异步。异步客户端上的所有方法都返回一个标准CompletableFuture.
根据需要,两种风格可以同时使用,共享相同的传输对象。我们这里就介绍同步客户端的使用。
2.从旧版High Level Rest Client迁移值新版
两种客户端可以同时存在,自行选择使用
// 低级客户端RestClient httpClient = RestClient.builder( new HttpHost("localhost", 9200)).build();//创建旧版旧版High Level Rest ClientRestHighLevelClient hlrc = new RestHighLevelClientBuilder(httpClient) .setApiCompatibilityMode(true) .build();// 创建新版ElasticsearchClient ElasticsearchTransport transport = new RestClientTransport( httpClient, new JacksonJsonpMapper());ElasticsearchClient esClient = new ElasticsearchClient(transport);
2.Lambda表达式相关api的使用
创建索引
@Test public void createIndex() throws IOException { ElasticsearchClient client = getElasticsearchClient(); System.out.println("连接成功--------------------------"); CreateIndexResponse createIndexResponse = client.indices().create( index -> index.index("productlist").aliases("product" , aliase -> aliase.isWriteIndex(true)) ); System.out.println(createIndexResponse.toString()); }
写入单个文档
实体类
public class Product implements Serializable { private static final long serialVersionUID = 1L; private String no; private String name; private String createBy; public Product() { } public Product(String no, String name, String createBy) { this.no = no; this.name = name; this.createBy = createBy; } public String getNo() { return no; } public void setNo(String no) { this.no = no; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCreateBy() { return createBy; } public void setCreateBy(String createBy) { this.createBy = createBy; } @Override public String toString() { return "Product{" + "no='" + no + '\'' + ", name='" + name + '\'' + ", createBy='" + createBy + '\'' + '}'; }}
Product product = new Product("bk-1", "City bike", 123.0);IndexResponse response = esClient.index(i -> i .index("products") .id(product.getSku()) .document(product));
批量插入
@Test public void bulkInsertDocument() throws IOException { ElasticsearchClient client = getElasticsearchClient(); System.out.println("连接成功--------------------------"); List<Product> products = new ArrayList<>(); products.add(new Product("asdad","dasdasd","adasdasdad")); products.add(new Product("12313","453","sfsdfdsfdsf")); BulkRequest.Builder br = new BulkRequest.Builder(); for (Product product : products) { br.operations( op -> op.index(index -> index.index("productlist").document(product)) ); } BulkResponse bulk = client.bulk(br.build()); System.out.println(bulk); }
通过id查找文档
@Test public void getOne() throws IOException { ElasticsearchClient client = getElasticsearchClient(); System.out.println("连接成功--------------------------"); GetResponse<Product> response = client.get(g -> g .index("productlist") .id("7ROTUIEBMxTIVL_J85rw"), Product.class ); System.out.println(response.source()); }
搜索文档
String searchText = "bike";SearchResponse<Product> response = esClient.search(s -> s .index("productlist") .query(q -> q.match(t -> t .field("name").query(searchText) ) ), Product.class );TotalHits total = response.hits().total();boolean isExactResult = total.relation() == TotalHitsRelation.Eq;if (isExactResult) { logger.info("There are " + total.value() + " results");} else { logger.info("There are more than " + total.value() + " results");}List<Hit<Product>> hits = response.hits().hits();for (Hit<Product> hit: hits) { Product product = hit.source(); logger.info("Found product " + product.getSku() + ", score " + hit.score());}
聚合文档
String searchText = "bike";Query query = MatchQuery.of(m -> m .field("name") .query(searchText))._toQuery();SearchResponse<Void> response = esClient.search(b -> b .index("products") .size(0) .query(query) .aggregations("price-histogram", a -> a .histogram(h -> h .field("price") .interval(50.0) ) ), Void.class );
总结
以上就是这篇要讲的内容,更多详细用法参考官网文档https://www.elastic.co/guide/en/elasticsearch/client/java-api-client/current/index.html