文章目录
- 介绍
- 在springboot项目集成ES
- 操作步骤
介绍
Elasticsearch 是一个分布式、RESTful 风格的搜索和数据分析引擎,它能够快速地存储、搜索和分析大量的数据。Elasticsearch 常用于全文搜索、结构化搜索、日志分析、实时应用监控等场景。
在springboot项目集成ES
操作步骤
1.创建boot项目
引入入Web(Spring Web)NoSQl(Spring Data Elasticsearch(Access+Driver))
2.引入依赖
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.6.1</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.83</version> <!-- 确认版本 --></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>
3.编写配置类
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 ElasticSearchConfig {@Beanpublic RestHighLevelClient restHighLevelClient() {RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1", 9200, "http")));return client;}
}
4.启动ES,编写测试类
创建索引
@Autowired@Qualifier("restHighLevelClient")private RestHighLevelClient client;/*** 创建索引*/@Testvoid testCreateIndex() throws IOException {CreateIndexRequest request = new CreateIndexRequest("zyy_index");CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);// 查看是否创建成功boolean acknowledged = createIndexResponse.isAcknowledged();System.out.println(acknowledged);client.close();}
查询索引
@Testvoid testGetIndex() throws IOException {GetIndexRequest request = new GetIndexRequest("zyy_index");// 索引是否存在boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);System.out.println(exists);client.close();}
删除索引
@Testvoid testDeleteIndex() throws IOException {DeleteIndexRequest request = new DeleteIndexRequest("zyy_index");AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);// 是否删除成功boolean acknowledged = delete.isAcknowledged();System.out.println(acknowledged);client.close();}
文档的添加
@Testvoid testAddDoc() throws IOException {User user = new User("zyy", 18);IndexRequest indexRequest = new IndexRequest("zyy_index");//类似PUT /zyy_index/_doc/1indexRequest.id("1");indexRequest.timeout(TimeValue.timeValueMillis(1000));indexRequest.source(JSON.toJSONString(user), XContentType.JSON);IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);// 返回状态CREATEDSystem.out.println(indexResponse.status());//IndexResponse[index=zyy_index,type=_doc,id=1,version=1,result=created,seqNo=0,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]System.out.println(indexResponse);}
文档信息的获取
@Testvoid testGetDoc() throws IOException {// 类似GET /zyy_index/_doc/1GetRequest request = new GetRequest("zyy_index", "1");GetResponse response = client.get(request, RequestOptions.DEFAULT);System.out.println(response.getSourceAsString());}
文档的获取,并判断其是否存在
@Testvoid testDocIsExits() throws IOException {// 类似GET /zyy_index/_doc/1GetRequest request = new GetRequest("zyy_index", "1");// 不获取返回的 _source的上下文了request.fetchSourceContext(new FetchSourceContext(false));request.storedFields("_none_");boolean exists = client.exists(request, RequestOptions.DEFAULT);System.out.println(exists);}
文档的更新
@Testvoid testUpdateDoc() throws IOException {User user = new User("zyy", 19);UpdateRequest request = new UpdateRequest("zyy_index", "1");request.doc(JSON.toJSONString(user), XContentType.JSON);UpdateResponse response = client.update(request, RequestOptions.DEFAULT);System.out.println(response.status());System.out.println(response);}
文档的删除
@Testvoid testDeleteDoc() throws IOException {DeleteRequest request = new DeleteRequest("zyy_index", "1");DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);System.out.println(response.status());System.out.println(response);}
文档的查询
@Testvoid testSearch() throws IOException {//精确查询TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "zyy");TermQueryBuilder termQueryBuilder1 = QueryBuilders.termQuery("_index", "zyy_index");//匹配查询
// MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "zyy");//构建查询条件SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();sourceBuilder.query(termQueryBuilder);sourceBuilder.query(termQueryBuilder1);//设置高亮sourceBuilder.highlighter(new HighlightBuilder());//设置分页
// sourceBuilder.from(0);
// sourceBuilder.size(10);//请求对象SearchRequest request = new SearchRequest();request.source(sourceBuilder);SearchResponse response = client.search(request, RequestOptions.DEFAULT);//查看返回SearchHits hits = response.getHits();System.out.println(JSON.toJSONString(hits));System.out.println("========================");for (SearchHit hit : hits.getHits()) {System.out.println(hit.getSourceAsMap());}System.out.println("========================");}
批量添加数据
@Testvoid testBulk() throws IOException {List<User> userList = new ArrayList<>();userList.add(new User("zyy1", 1));userList.add(new User("zyy2", 2));userList.add(new User("zyy3", 3));userList.add(new User("zyy4", 4));userList.add(new User("zyy5", 5));userList.add(new User("zyy6", 6));BulkRequest request = new BulkRequest();request.timeout("10s");for (int i = 0; i < userList.size(); i++) {User user = userList.get(i);IndexRequest indexRequest = new IndexRequest("zyy_index");indexRequest.id("" + i);indexRequest.source(JSON.toJSONString(user), XContentType.JSON);request.add(indexRequest);}BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);System.out.println(responses.status());}