上一篇:ElasticSearch(9)—Rest风格
SpringBoot项目集成ES |
一、引入依赖
首先创建一个springboot项目,并勾选下图中的一些基本依赖:
按照官方文档,springboot项目集成es首先需要导入es客户端,但是因为在创建项目的时候勾选了elasticsearch的起步依赖,查看该起步依赖发现底层已经引用了高级客户端 rest-high-level-client
依赖。
然后在springboot项目的maven依赖中查看elasticsearch使用的依赖版本是6.8.7,
为了保证我们导入的依赖版本与es版本一致,所以手动调整es依赖的版本号,在pom.xml
文件中进行调整:
二、创建客户端实例
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient restHighLevelClient = new RestHighLevelClient(
RestClient.builder(
new HttpHost("127.0.0.1", 9200, "http")));
//如果是集群,则在此处可以new 多个HttpHost
//new HttpHost("127.0.0.1", 9201, "http")));
return restHighLevelClient;
}
}
二、测试es-api的使用
1.创建一个索引
创建一个实体类,将文档数据声明在该实体类中:
package org.magic.esapi.entiy;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data//生成set get方法
@AllArgsConstructor//有参构造函数
@NoArgsConstructor//无参构造函数
public class User {
private String name;
private Integer age;
private String address;
}
2. 创建客户端实例
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
//如果是集群,则此处可以多new 几个HttpHost
// new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9200, "http")));
return client;
}
}
3. 测试api的使用
以下api操作结果可是结合elasticsearch-head
插件来查看操作的结果;
package org.magic.esapi;
import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.util.ArrayList;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.search.SearchHit;
import org.junit.jupiter.api.Test;
import org.magic.esapi.entiy.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
@SpringBootTest
class EsApiApplicationTests {
private static final String index_name = "user_info";
@Autowired
private RestHighLevelClient restHighLevelClient;
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
/**
* 创建一个索引库
*
* @throws IOException
*/
@Test
void createIndex() throws IOException {
boolean result = elasticsearchRestTemplate.createIndex("liqiang");
System.out.println(result);
/* CreateIndexRequest createIndexRequest = new CreateIndexRequest(index_name);
CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
//打印创建结果
System.out.println(createIndexResponse.isAcknowledged());*/
}
/**
* 判断索引库是否存在
*/
@Test
void searchIndex() throws IOException {
GetIndexRequest request = new GetIndexRequest(index_name);
boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
/**
* 删除索引库
*/
@Test
void removeIndex() throws IOException {
DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index_name);
AcknowledgedResponse response = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
//打印删除结果
System.out.println(response.isAcknowledged());
}
/**
* 创建文档
*/
@Test
void createDoc() throws IOException {
User user = new User("张三", 20, "北京市");
IndexRequest indexRequest = new IndexRequest(index_name);
indexRequest.id("1");
indexRequest.timeout("1s");
IndexRequest request = indexRequest.source(JSON.toJSONString(user), XContentType.JSON);
IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
System.out.println(response.status());
}
/**
* 查询文档
*/
@Test
void queryDoc() throws IOException {
GetRequest getRequest = new GetRequest(index_name, "1");
GetResponse response = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
System.out.println(response.getSource());
}
/**
* 修改文档
*/
@Test
void updateDoc() throws IOException {
UpdateRequest updateRequest = new UpdateRequest(index_name, "1");
User user = new User("李四", 55, "成都市");
updateRequest.doc(JSON.toJSONString(user), XContentType.JSON);
updateRequest.timeout("1s");
UpdateResponse response = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(response.status());
}
/**
* 删除指定文档
*/
@Test
void removeDoc() throws IOException {
DeleteRequest deleteRequest = new DeleteRequest(index_name, "1");
DeleteResponse response = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(response.status());
}
/**
* 批量插入文档
*/
@Test
void bulkCreateDoc() throws IOException {
BulkRequest bulkRequest = new BulkRequest();
bulkRequest.timeout("10s");
ArrayList<User> userList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
userList.add(new User("张三" + i, 25 + i, "成都" + i));
}
for (int i = 0; i < userList.size(); i++) {
bulkRequest.add(new IndexRequest(index_name)
.id(String.valueOf(i))
.source(JSON.toJSONString(userList.get(i)), XContentType.JSON));
}
BulkResponse response = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(response.status());
}
/**
* 批量查询文档
*/
@Test
void queryDocList() throws IOException {
SearchRequest searchRequest = new SearchRequest(index_name);
/*
//指定条件查询
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//查询年龄为25的index_info索引库中的数据
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("age", 25);
searchSourceBuilder.query(termQueryBuilder);
searchRequest.source(searchSourceBuilder);
SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
for (SearchHit hit : response.getHits()) {
System.out.println(hit.getSourceAsString());
}
*/
//查询索引库中所有的文档数据
SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
for (SearchHit hit : response.getHits()) {
System.out.println(hit.getSourceAsString());
}
}
}