Es的java API客戶端
在Es7.15版本之后怯屉,es官方將它的高級客戶端RestHighLevelClient標(biāo)記為棄用狀態(tài)贼陶。同時推出了全新的java API客戶端Elasticsearch Java API Client,該客戶端也將在Elasticsearch8.0及以后版本中成為官方推薦使用的客戶端孩灯。
Elasticsearch Java API Client支持除Vector title search API和Find structure API之外的所有Elasticsearch API闺金。且支持所有API數(shù)據(jù)類型,并且不再有原始JSON Value屬性峰档。它是針對Elasticsearch8.0及之后版本的客戶端败匹。
感興趣的小伙伴可以去官方文檔看看:Elasticsearch官網(wǎng)8.x版本下Java客戶端文檔---Elasticsearch Java API Client使用
新建maven項(xiàng)目
maven中引入依賴坐標(biāo)
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.1.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
<scope>provided</scope>
</dependency>
創(chuàng)建連接
@Test
public void create() throws IOException {
// 創(chuàng)建低級客戶端
RestClient restClient = RestClient.builder(
new HttpHost("localhost", 9200)
).build();
// 使用Jackson映射器創(chuàng)建傳輸層
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper()
);
// 創(chuàng)建API客戶端
ElasticsearchClient client = new ElasticsearchClient(transport);
// 關(guān)閉ES客戶端
transport.close();
restClient.close();
}
索引index的基本語法
創(chuàng)建索引
@Test
public void create() throws IOException {
// 創(chuàng)建低級客戶端
RestClient restClient = RestClient.builder(
new HttpHost("localhost", 9200)
).build();
// 使用Jackson映射器創(chuàng)建傳輸層
ElasticsearchTransport transport = new RestClientTransport(
restClient, new JacksonJsonpMapper()
);
// 創(chuàng)建API客戶端
ElasticsearchClient client = new ElasticsearchClient(transport);
// 創(chuàng)建索引
CreateIndexResponse createIndexResponse = client.indices().create(c -> c.index("user_test"));
// 響應(yīng)狀態(tài)
Boolean acknowledged = createIndexResponse.acknowledged();
System.out.println("索引操作 = " + acknowledged);
// 關(guān)閉ES客戶端
transport.close();
restClient.close();
}
查詢索引
@Test
public void query() throws IOException {
RestClient restClient = RestClient.builder(
new HttpHost("localhost",9200)
).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 查詢索引
GetIndexResponse getIndexResponse = client.indices().get(e -> e.index("user_test"));
System.out.println("getIndexResponse.result() = " + getIndexResponse.result());
System.out.println("getIndexResponse.result().keySet() = " + getIndexResponse.result().keySet());
transport.close();
restClient.close();
}
刪除索引
@Test
public void delete() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 刪除索引
DeleteIndexResponse deleteIndexResponse = client.indices().delete(e -> e.index("user_test"));
System.out.println("刪除操作 = " + deleteIndexResponse.acknowledged());
transport.close();
restClient.close();
}
文檔document的操作
創(chuàng)建User對象
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private String sex;
private Integer age;
}
添加document
@Test
public void addDocument() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 向user對象中添加數(shù)據(jù)
User user = new User("java客戶端", "男", 18);
// 向索引中添加數(shù)據(jù)
CreateResponse createResponse = client.create(e -> e.index("user_test").id("1001").document(user));
System.out.println("createResponse.result() = " + createResponse.result());
transport.close();
restClient.close();
}
$\color{red}{注:index中參數(shù)為文檔所屬的索引名,id中參數(shù)為當(dāng)文檔的id讥巡,document為文檔數(shù)據(jù)掀亩,新版本支持直接傳入java對象.} $
查詢document
@Test
public void queryDocument() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 構(gòu)建請求
GetResponse<User> getResponse = client.get(e -> e.index("user_test").id("1001"), User.class);
System.out.println("getResponse.source().toString() = " + getResponse.source().toString());
transport.close();
restClient.close();
}
修改document
@Test
public void modifyDocument() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 使用map集合封裝需要修改的內(nèi)容
Map<String, Object> map = new HashMap<>();
map.put("name", "java客戶端aaa");
// 構(gòu)建請求
UpdateResponse<User> updateResponse = client.update(e -> e.index("user_test").id("1001").doc(map), User.class);
System.out.println("updateResponse.result() = " + updateResponse.result());
transport.close();
restClient.close();
}
刪除document
@Test
public void removeDocument() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 構(gòu)建請求
DeleteResponse deleteResponse = client.delete(e -> e.index("user_test").id("1001"));
System.out.println("deleteResponse.result() = " + deleteResponse.result());
transport.close();
restClient.close();
}
批量添加document
@Test
public void batchAddDocument() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 構(gòu)建一個批量數(shù)據(jù)集合
List<BulkOperation> list = new ArrayList<>();
list.add(new BulkOperation.Builder().create(
d -> d.document(new User("test2", "男", 19)).id("1002").index("user_test")).build());
list.add(new BulkOperation.Builder().create(
d -> d.document(new User("test3", "男", 20)).id("1003").index("user_test")).build());
list.add(new BulkOperation.Builder().create(
d -> d.document(new User("test4", "女", 21)).id("1004").index("user_test")).build());
// 調(diào)用bulk方法執(zhí)行批量插入操作
BulkResponse bulkResponse = client.bulk(e -> e.index("user_test").operations(list));
System.out.println("bulkResponse.items() = " + bulkResponse.items());
transport.close();
restClient.close();
}
批量刪除
@Test
public void batchDeleteDocument() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 構(gòu)建一個批量數(shù)據(jù)集合
List<BulkOperation> list = new ArrayList<>();
list.add(new BulkOperation.Builder().delete(
d -> d.id("1002").index("user_test")).build());
list.add(new BulkOperation.Builder().delete(
d -> d.id("1003").index("user_test")).build());
// 調(diào)用bulk方法執(zhí)行批量插入操作
BulkResponse bulkResponse = client.bulk(e -> e.index("user_test").operations(list));
System.out.println("bulkResponse.items() = " + bulkResponse.items());
transport.close();
restClient.close();
}
全量查詢
@Test
public void queryAllDocument() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 全量查詢
SearchResponse<User> searchResponse = client.search(e -> e.index("user_test").query(q -> q.matchAll(m -> m)), User.class);
HitsMetadata<User> hits = searchResponse.hits();
for (Hit<User> hit : hits.hits()) {
System.out.println("user = " + hit.source().toString());
}
System.out.println("searchResponse.hits().total().value() = " + searchResponse.hits().total().value());
transport.close();
restClient.close();
}
分頁查詢
@Test
public void pagingQueryDocument() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 分頁查詢
SearchResponse<User> searchResponse = client.search(
s -> s.index("user_test")
.query(q -> q.matchAll(m -> m))
.from(2)
.size(2)
, User.class);
searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
transport.close();
restClient.close();
}
排序查詢
@Test
public void sortQueryDocument() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 排序查詢
SearchResponse<User> searchResponse = client.search(
s -> s.index("user_test")
.query(q -> q.matchAll(m -> m))
.sort(o -> o.field(f -> f.field("age").order(SortOrder.Asc)))
, User.class);
searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
transport.close();
restClient.close();
}
條件查詢
@Test
public void conditionQueryDocument() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 條件查詢
SearchResponse<User> searchResponse = client.search(
s -> s.index("user_test").query(q -> q.matchAll(m -> m))
.sort(o -> o.field(f -> f.field("age").order(SortOrder.Asc)))
.source(r -> r.filter(f -> f.includes("name", "age").excludes("")))
, User.class);
searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
transport.close();
restClient.close();
}
組合查詢
@Test
public void combinationQueryDocument() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 組合查詢
SearchResponse<User> searchResponse = client.search(
s -> s.index("user_test").query(q -> q.bool(b -> b
.must(m -> m.match(u -> u.field("age").query(21)))
.must(m -> m.match(u -> u.field("sex").query("男")))
.mustNot(m -> m.match(u -> u.field("sex").query("女")))
))
, User.class);
searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
transport.close();
restClient.close();
}
@Test
public void combinationQueryDocument2() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 組合查詢
SearchResponse<User> searchResponse = client.search(
s -> s.index("user_test").query(q -> q.bool(b -> b
.should(h -> h.match(u -> u.field("age").query(19)))
.should(h -> h.match(u -> u.field("sex").query("男")))
))
, User.class);
searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
transport.close();
restClient.close();
}
must是必須滿足所有條件,should只要滿足一個就行
范圍查詢
@Test
public void scopeQueryDocument2() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 范圍查詢怎爵,gte()表示取大于等于特石,gt()表示大于,lte()表示小于等于
SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").query(q -> q
.range(r -> r.field("age").gte(JsonData.of(20)).lt(JsonData.of(21))))
, User.class);
searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
transport.close();
restClient.close();
}
模糊查詢
@Test
public void fuzzyQueryDocument2() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 模糊查詢鳖链,fuzziness表示差幾個可以查詢出來
SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").query(q -> q
.fuzzy(f -> f.field("name").value("tst").fuzziness("2")))
, User.class);
searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
transport.close();
restClient.close();
}
高亮查詢
@Test
public void highlightQueryDocument2() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 高亮查詢
SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").query(q -> q
.term(t -> t.field("name").value("test3")))
.highlight(h -> h.fields("name", f -> f.preTags("<font color='red'>").postTags("</font>")))
, User.class);
searchResponse.hits().hits().forEach(h -> System.out.println(h.source().toString()));
transport.close();
restClient.close();
}
聚合查詢
@Test
public void aggregateQueryDocument2() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 聚合查詢姆蘸,取最大年齡
SearchResponse<User> searchResponse = client.search(s -> s.index("user_test").aggregations("maxAge", a ->a.max(m -> m.field("age")))
, User.class);
searchResponse.aggregations().entrySet().forEach(f -> System.out.println(f.getKey() + ":" + f.getValue().max().value()));
transport.close();
restClient.close();
}
分組查詢
@Test
public void groupQueryDocument2() throws IOException {
RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
// 分組查詢
SearchResponse<User> searchResponse = client.search(s -> s.index("user_test")
.aggregations("ageGroup", a ->a.terms(t -> t.field("age")))
, User.class);
searchResponse.aggregations().get("ageGroup").lterms().buckets().array().forEach(f -> System.out.println(f.key() + ":" + f.docCount()));
transport.close();
restClient.close();
}