【ElasticSearch8】SpringBoot集成ElasticSearch8.x 基本应用 CRUD操作
ElasticSearch的大版本之间改动还是比较大的,es官方已经放弃对旧版本中的Java REST Client (High Level Rest Client (HLRC))的支持,从而替换为推荐使用的Java API Client 8.x,在查找诸多资料后,整理出以下代码片段,以下代码本人全部测试过,可以直接使用
1.版本说明
springboot:2.7.1
ElasticSearch: 8.2.3(非集群)
JDK: 1.8
2.maven依赖
直接使用官方推荐的maven依赖包
<dependency>
<groupId>co.elastic.clients</groupId>
<artifactId>elasticsearch-java</artifactId>
<version>8.2.3</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>8.2.3</version>
</dependency>
<dependency>
<groupId>org.glassfish</groupId>
<artifactId>jakarta.json</artifactId>
<version>2.0.1</version>
</dependency>
3.配置文件
@Configuration
public class ElasticSearchConfig {
@Bean
public ElasticsearchClient elasticsearchClient(){
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
//设置账号密码
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user", "password"));
RestClient restClient = RestClient.builder(new HttpHost("127.0.0.1", 9200,"http"))
.setHttpClientConfigCallback(httpClientBuilder->httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)).build();
ElasticsearchTransport transport = new RestClientTransport(restClient,new JacksonJsonpMapper());
return new ElasticsearchClient(transport);
}
}
4.测试类
@SpringBootTest
class ElasticApplicationTests {
@Autowired
ElasticsearchClient client;
/**
* 增加index
* @throws IOException
*/
@Test
public void createTest() throws IOException {
CreateIndexResponse indexResponse = client.indices().create(c -> c.index("user"));
System.out.println(indexResponse);
}
/**
* 查询Index
* @throws IOException
*/
@Test
public void queryTest() throws IOException {
GetIndexResponse getIndexResponse = client.indices().get(i -> i.index("user"));
System.out.println(getIndexResponse);
}
/**
* 判断index是否存在
* @throws IOException
*/
@Test
public void existsTest() throws IOException {
BooleanResponse booleanResponse = client.indices().exists(e -> e.index("user"));
System.out.println(booleanResponse.value());
}
/**
* 删除index
* @throws IOException
*/
@Test
public void deleteTest() throws IOException {
DeleteIndexResponse deleteIndexResponse = client.indices().delete(d -> d.index("user"));
System.out.println(deleteIndexResponse.acknowledged());
}
}
5.demo
- User类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private String name;
private int age;
}
- 业务测试类
@SpringBootTest
class CRUDTests {
@Autowired
ElasticsearchClient client;
/**
* 插入document
*
* @throws IOException
*/
@Test
public void addDocumentTest() throws IOException {
User user = new User("user1", 10);
IndexResponse indexResponse = client.index(i -> i
.index("user")
//设置id
.id("1")
//传入user对象
.document(user));
System.out.println(indexResponse);
}
/**
* 更新Document
*
* @throws IOException
*/
@Test
public void updateDocumentTest() throws IOException {
UpdateResponse<User> updateResponse = client.update(u -> u
.index("user")
.id("1")
.doc(new User("user2", 13))
, User.class);
System.out.println(updateResponse);
}
/**
* 判断Document是否存在
*
* @throws IOException
*/
@Test
public void existDocumentTest() throws IOException {
BooleanResponse indexResponse = client.exists(e -> e.index("user").id("1"));
System.out.println(indexResponse.value());
}
/**
* 查询Document
*
* @throws IOException
*/
@Test
public void getDocumentTest() throws IOException {
GetResponse<User> getResponse = client.get(g -> g
.index("user")
.id("1")
, User.class
);
System.out.println(getResponse.source());
}
/**
* 删除Document
*
* @throws IOException
*/
@Test
public void deleteDocumentTest() throws IOException {
DeleteResponse deleteResponse = client.delete(d -> d
.index("user")
.id("1")
);
System.out.println(deleteResponse.id());
}
/**
* 批量插入Document
*
* @throws IOException
*/
@Test
public void bulkTest() throws IOException {
List<User> userList = new ArrayList<>();
userList.add(new User("hello world", 11));
userList.add(new User("hello java", 12));
userList.add(new User("hello es", 13));
userList.add(new User("hello spring", 14));
userList.add(new User("user", 15));
List<BulkOperation> bulkOperationArrayList = new ArrayList<>();
//遍历添加到bulk中
for (User user : userList) {
bulkOperationArrayList.add(BulkOperation.of(o -> o.index(i -> i.document(user))));
}
BulkResponse bulkResponse = client.bulk(b -> b.index("user")
.operations(bulkOperationArrayList));
System.out.println(bulkResponse);
}
/**
*查询
* @throws IOException
*/
@Test
public void searchTest() throws IOException {
SearchResponse<User> search = client.search(s -> s
.index("user")
//查询name字段包含hello的document(不使用分词器精确查找)
.query(q -> q
.term(t -> t
.field("name")
.value(v -> v.stringValue("hello"))
))
//分页查询,从第0页开始查询3个document
.from(0)
.size(3)
//按age降序排序
.sort(f -> f.field(o -> o.field("age").order(SortOrder.Desc))), User.class
);
for (Hit<User> hit : search.hits().hits()) {
System.out.println(hit.source());
}
}
}
参考:
\