由于Elasticsearch7.x版本和8.x版本差距较大,并且在8.x版本中放弃了对旧版本中的Java REST Client(High Level Rest Client (HLRC))的支持,从而替换为推荐使用的Java API Client 8.x。
注意:springboot版本尽量不要低于2.6.4,因为jackson与springboot也需要兼容。
这里学习和记录8.10.4版本的集成和使用。
1、找到原生的依赖
<dependency>
<groupId>co.elastic.clientsgroupId>
<artifactId>elasticsearch-javaartifactId>
<version>8.10.4version>
<exclusions>
<exclusion>
<groupId>org.elasticsearch.clientgroupId>
<artifactId>elasticsearch-rest-clientartifactId>
exclusion>
exclusions>
dependency>
<dependency>
<groupId>org.elasticsearch.clientgroupId>
<artifactId>elasticsearch-rest-clientartifactId>
<version>8.10.4version>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.13.2version>
dependency>
<dependency>
<groupId>org.glassfishgroupId>
<artifactId>jakarta.jsonartifactId>
<version>2.0.1version>
dependency>
2、核心配置类
@Configuration
public class ElasticConfig {
//创造连接,并返回json格式数据
@Bean
public ElasticsearchClient elasticsearchClient(){
RestClient client = RestClient.builder(new HttpHost("localhost",9200,"http")).build();
ElasticsearchTransport transport = new RestClientTransport(client, new JacksonJsonpMapper());
return new ElasticsearchClient(transport);
}
}
3、在Test类中对索引进行增删改查测试
@Test
void testCreateIndex() throws IOException {
//创建索引
CreateIndexResponse response = client.indices().create(c -> c.index("user"));
//查询索引
GetIndexResponse getIndexResponse = client.indices().get(i -> i.index("user"));
//判断索引是否存在
BooleanResponse booleanResponse = client.indices().exists(e -> e.index("user"));
//删除索引
DeleteIndexResponse deleteIndexResponse = client.indices().delete(d -> d.index("user"));
}
4、在Test类中对document进行增删改查测试
创建实体类:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Product {
private String id;
private String SKu;
private double price;
}
document测试:
//document CRUD
@Test
void testDocumentCRUD() throws IOException {
Product product = new Product("bk-1", "City bike", 123.0);
Product product2 = new Product("bk-2", "Countryside bike", 150.0);
//插入document
IndexResponse indexResponse = client.index(i -> i.index("product").id(product.getSKu()).document(product));
System.out.println(indexResponse);
//更新document
UpdateResponse<Product> updateResponse = client.update(u -> u.index("product").id(product.getSKu()).doc(product2),Product.class);
System.out.println(updateResponse);
//判断document是否存在,返回boolean类型
BooleanResponse booleanResponse = client.exists(e -> e.index("product").id(product.getSKu()));
System.out.println(booleanResponse.value());
//查询document,返回对象
GetResponse<Product> getResponse = client.get(g -> g.index("product").id(product.getSKu()),Product.class);
System.out.println(getResponse.source());
//删除document
DeleteResponse deleteResponse = client.delete(d -> d.index("product").id(product.getSKu()));
}
5、批量插入document
//批量插入document
@Test
void batchCreate() throws IOException {
List<Product> productList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
productList.add(new Product("bk-"+i, "city bike"+i, 100+i));
}
List<BulkOperation> bulkOperations = new ArrayList<>();
for(Product product : productList){
bulkOperations.add(BulkOperation.of(o -> o.index(i -> i.id(product.getSKu()).document(product))));
}
BulkResponse response = client.bulk(b -> b.index("product").operations(bulkOperations));
}
6、复杂条件查询
// 复杂条件查询
@Test
void searchTest() throws IOException {
SearchResponse<Product> searchResponse = client.search(s -> s.index("product")
//精确查询id字段中包含bk的
.query(q -> q.term(t -> t.field("id").value(v -> v.stringValue("bk"))))
//高亮查询
.highlight(q -> q.fields("id",o -> o.matchedFields("")).preTags(""
).postTags(""))
//分页
.from(0)
.size(4)
//排序
.sort(f -> f.field(o -> o.field("price").order(SortOrder.Desc))),Product.class);
for(Hit<Product> hit : searchResponse.hits().hits()){
System.out.println(hit);
}
}
返回查询结果:
Hit: {"_index":"product","_id":"city bike4","_score":null,"highlight":{"id":["bk
-4"]},"_source":"Product(id=bk-4, SKu=city bike4, price=104.0)","sort":[104.0]}
Hit: {"_index":"product","_id":"city bike3","_score":null,"highlight":{"id":["bk
-3"]},"_source":"Product(id=bk-3, SKu=city bike3, price=103.0)","sort":[103.0]}
Hit: {"_index":"product","_id":"city bike2","_score":null,"highlight":{"id":["bk
-2"]},"_source":"Product(id=bk-2, SKu=city bike2, price=102.0)","sort":[102.0]}
Hit: {"_index":"product","_id":"city bike1","_score":null,"highlight":{"id":["bk
-1"]},"_source":"Product(id=bk-1, SKu=city bike1, price=101.0)","sort":[101.0]}