SpringBoot整合ES
# SpringBoot集成ES
# 集成开发步骤
# 1.导入坐标
<!--processor-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<!--lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!--整合es-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!--es-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.6.1</version>
</dependency>
<!--fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.80</version>
</dependency>
# 2.配置Elasticsearch
创建一个配置类,导入Elasticsearch的插件。
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
return client;
}
}
# 3.导入Bean使用
使用测试类,使用@Autowired
注解,自动装配。
@SpringBootTest
class ElasticSearchApiApplicationTests {
@Autowired
private RestHighLevelClient restHighLevelClient;
}
# 具体API测试
# 1、创建索引
// 测试索引的创建
@Test
void testCreateIndex() throws IOException {
// 1.创建索引请求
CreateIndexRequest request = new CreateIndexRequest("kuang_index");
// 2.执行创建请求,请求后获得响应createIndexResponse
CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
System.out.println(createIndexResponse);
}
# 2、判断索引是否存在
// 测试获取索引,只能判断其是否存在
@Test
void testExistIndex() throws IOException {
// 1.创建索引请求
GetIndexRequest request = new GetIndexRequest("kuang_index");
// 2.获取索引,是否存在
boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
# 3、删除索引
// 测试删除索引
@Test
void testDeleteIndex() throws IOException {
// 1.创建删除索引请求
DeleteIndexRequest request = new DeleteIndexRequest("kuang_index");
// 2.获取删除状态
AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}
# 4、添加文档
// 测试添加文档
@Test
void testAddDocument() throws IOException {
// 1.创建对象
User user = new User("狂神说",3);
// 2.创建请求
IndexRequest request = new IndexRequest("kuang_index");
// 3.规则 put /kuang_index/_doc/1
request.id("1");
request.timeout(TimeValue.timeValueSeconds(1));// 或者 request.timeout("1s");
// 4.把数据放入请求 json
IndexRequest source = request.source(JSON.toJSONString(user), XContentType.JSON);
// 5.客户端发送请求,获取响应结果
IndexResponse indexResponse = restHighLevelClient.index(request, RequestOptions.DEFAULT);
System.out.println(indexResponse.toString());// 结果的json
System.out.println(indexResponse.status());// 对应我们命令返回的状态 created
}
# 5、判断文档是否存在
// 获取文档信息,判断是否存在 get /index/_doc/1
@Test
void testIsExists() throws IOException {
GetRequest getRequest = new GetRequest("kuang_index", "1");
// 不获取返回_source的上下文了
getRequest.fetchSourceContext(new FetchSourceContext(false));
getRequest.storedFields("_none_");
boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
System.out.println(exists);
}
# 6、获取文档的信息
// 获取文档的信息
@Test
void testGetDocument() throws IOException {
GetRequest getRequest = new GetRequest("kuang_index", "1");
GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
System.out.println(getResponse.getSourceAsString());// 打印文档的内容
System.out.println(getResponse);// 返回的全部内容和密令一样
}
# 7、更新文档的信息
// 更新文档的信息
@Test
void testUpdateDocument() throws IOException {
UpdateRequest updateRequest = new UpdateRequest("kuang_index", "1");
updateRequest.timeout("1s");
User user = new User("狂神说Java", 18);
updateRequest.doc(JSON.toJSONString(user),XContentType.JSON);
UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(update.status());
}
# 8、删除文档信息
// 删除文档记录
@Test
void testDeleteRequest() throws IOException {
DeleteRequest deleteRequest = new DeleteRequest("kuang_index","1");
deleteRequest.timeout("1s");
DeleteResponse deleteResponse = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(deleteResponse.status());
}
# 9、批量插入数据
特殊的,真实的项目一般都会批量插入数据。
// 特殊的,真实的项目一般都会批量插入数据
@Test
void testBulkRequest() throws IOException {
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("1s");
ArrayList<User> users = new ArrayList<>();
users.add(new User("kuangshen1",3));
users.add(new User("kuangshen2",3));
users.add(new User("kuangshen3",3));
users.add(new User("qinjiang1",3));
users.add(new User("qinjiang1",3));
users.add(new User("qinjiang1",3));
for (int i = 0; i < users.size(); i++) {
bulkRequest.add(new IndexRequest("kuang_index")
.id(""+(i+1))// 不设置id,则会生成默认id
.source(JSON.toJSONString(users.get(i)),XContentType.JSON));
}
BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(bulkResponse.hasFailures());// 是否失败,返回false代表成功
}
@Test
void testCreateDoc() throws IOException{
// 首先我这里是直接从数据库获取到的信息装载进Book实体类
List<Book> books = bookDao.selectList(null);
// 创建批量添加文档
BulkRequest bulkRequest = new BulkRequest();
// 使用循环遍历批量添加
for (Book book : books) {
// 调用索引请求 id直接使用book获取的id即可 由于Book实体类的id是Integer类型所以要转换
IndexRequest request = new IndexRequest("books").id(book.getId().toString());
// 直接将book的实体类转换成JSON的格式数据
String json = JSON.toJSONString(book);
// 将request的请求源添加为JSON即可
request.source(json,XContentType.JSON);
// 调用批量创建文档的接口传入request
bulkRequest.add(request);
}
restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);
}
# 10、查询
// 查询
// SearchRequest 搜索请求
// SearchSourceBuilder 条件构造
// HighlightBuilder 构建高亮
// TermQueryBuilder精确查询
// MatchALLQueryBuilder
// xxx QueryBuilder 对应我们刚才看到的命令!
@Test
void testSearch() throws IOException {
// 创建请求
SearchRequest searchRequest = new SearchRequest("kuang_index");
// 构建搜索条件
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
// 查询条件,我们可以使用 QueryBuilders 工具来实现
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "qinjiang1");// 精确
//MatchAllQueryBuilder matchAllQueryBuilder = QueryBuilders.matchAllQuery();// 匹配所有
sourceBuilder.query(termQueryBuilder);
sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
searchRequest.source(sourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(JSON.toJSONString(searchResponse.getHits()));
System.out.println("=============");
for (SearchHit hit : searchResponse.getHits().getHits()) {
System.out.println(hit.getSourceAsMap());
}
}
上次更新: 2023/11/28, 22:03:59