SpringBoot整合ElasticSearch7.4.2,简单而详细
SpringBoot整合ElasticSearch7.4.2,简单而详细
这篇博客是给刚刚接触ElasticSearch的小伙伴看的,主要的目的是想让刚安装了es的小伙伴,可以通过咱们java程序来操作ElasticSearch,好了闲话少说,开始正题。
1、创建一个SpringBoot项目
先打开idea,创建一个springboot项目
选择spring Initializr
填写相关的包名和java版本的信息
开始选则一些依赖项,这里我只选择spring web
最后确认一下项目保存的地址就可以点击完成了
2、导入相关的坐标,写入pom文件
这里必须要注意,由于我的elasticsearch的版本为7.4.2,所以我们选择以来的版本的时候,也要和你的elasticsearch版本相对应。
重要的事情说三遍,版本一定要对应,版本一定要对应,版本一定要对应!!!
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<!-- 这里我的springboot的版本使用是2.3.2 -->
<version>2.3.2.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.xiao</groupId>
<artifactId>estest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>estest</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<!-- 这里必须要填写,因为springboot2.3.2默认的elasticsearch版本为7.6.2,我们使用的是7.4.2,不更改会产生版本不兼容等问题 -->
<elasticsearch.version>7.4.2</elasticsearch.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- 这里我使用的是elasticsearch的high-level-client 版本要和你的elasticsearch版本对应-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3、创建一个配置类,用于配置Elasticsearch的集群信息
现在我们EstestApplication这个springboot启动类的同级目录下创建一个config目录,然后编写配置类
在这里插入图片描述
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;
/**
* 给容器中注入一个RestHighLevelClient
*/
@Configuration
public class ElasticSearchConfig {
@Bean
public RestHighLevelClient esRestClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
//在这里配置你的elasticsearch的情况
new HttpHost("127.0.0.1", 9200, "http")
)
);
return client;
}
}
4、编写配置文件
编写resources目录下的application.properties
server.port=8111
spring.application.name=elastic
5、向elasticsearch中存入测试数据
es官方数据 https://github.com/elastic/elasticsearch/blob/master/docs/src/test/resources/accounts.json?raw=true
打开这个网站以后是一堆json数据 不过没关系,我们复制一下这段json数据
然后我们打开kibana,输入如下命令,将数据保存进去
POST /bank/account/_bulk
//这里把刚才网站的json数据复制进来
执行完毕后,执行以下这个代码
GET /bank/_search
{
"query": {
"match_all": {}
}
}
6、编写测试controller
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.AvgAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/search")
public class EsController {
@Autowired
private RestHighLevelClient client;
@RequestMapping("/test")
void contextLoads() throws IOException {
//1、创建查询请求,规定查询的索引
SearchRequest request = new SearchRequest("bank");
//2、创建条件构造
SearchSourceBuilder builder = new SearchSourceBuilder();
//3、构造条件
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("address", "Lane");
builder.query(matchQueryBuilder);
//聚合年龄分布
TermsAggregationBuilder ageAgg = AggregationBuilders.terms("ageAgg").field("age");
builder.aggregation(ageAgg);
//聚合平均年龄
AvgAggregationBuilder balanceAvg = AggregationBuilders.avg("balanceAvg").field("balance");
builder.aggregation(balanceAvg);
//4、将构造好的条件放入请求中
request.source(builder);
//5、开始执行发送request请求
SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
//6、开始处理返回的数据
SearchHit[] hits = searchResponse.getHits().getHits();
List<String> list = new ArrayList<String>();
for (SearchHit hit : hits) {
String hitString = hit.getSourceAsString();
System.out.println(hitString);
list.add(hitString);
}
}
}
上面这段代码其实执行的QueryDSL语句为
GET /bank/_search
{
"query": {
"match": {
"address": "Lane"
}
},
"aggs": {
"ageAgg": {
"terms": {
"field": "age"
}
},
"balanceAvg":{
"avg": {
"field": "balance"
}
}
}
}
7、启动服务,并使用postman发送请求
测试结果如下