ES集成SpringBoot入门
环境: jdk1.8 maven es7.14.0 elasticsearch-head
添加需要依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.2</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/org.elasticsearch/elasticsearch -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.14.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.14.0</version>
</dependency>
<!-- junit单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<version>2.5.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
</dependencies>
添加YAML文件
ESConfig:
hostName: 127.0.0.1
port: 9200
scheme: http
创建配置类ESConfig
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ESConfig {
@Value("${ESConfig.hostName}")
private String hostName;
@Value("${ESConfig.port}")
private Integer port;
@Value("${ESConfig.scheme}")
private String scheme;
@Bean
public RestHighLevelClient restHighLevelClient() {
RestClientBuilder builder = RestClient.builder(
new HttpHost(hostName, port, scheme)
);
return new RestHighLevelClient(builder);
}
}
创建实体类
public class User {
private Integer uuid;
private String name;
private String age;
private String group;
private String department;
private String synopsis;
public Integer getUuid() {
return uuid;
}
public void setUuid(Integer uuid) {
this.uuid = uuid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getSynopsis() {
return synopsis;
}
public void setSynopsis(String synopsis) {
this.synopsis = synopsis;
}
@Override
public String toString() {
return "User{" +
"uuid=" + uuid +
", name='" + name + '\'' +
", age='" + age + '\'' +
", group='" + group + '\'' +
", department='" + department + '\'' +
", synopsis='" + synopsis + '\'' +
'}';
}
}
基本环境已经搭建完成了 测试
创建索引/创建文档
@Autowired
private RestHighLevelClient restHighLevelClient;
@Test
public void testCreateIndex() throws IOException {
IndexRequest request = new IndexRequest();
request.index("user_info");
User user = new User() {{
setUuid(1);
setGroup("group_1");
setDepartment("department_1");
setName("张三");
setSynopsis("我是: 张三 用户");
}};
request.source(JSON.toJSONString(user), XContentType.JSON);
restHighLevelClient.index(request, RequestOptions.DEFAULT);
}
这时候我们es(后面统一使用es代替elasticsearch)-head中就已经创建好了 数据也同时插入进来了 查看文档
@Test
public void testFindIndexData() throws IOException {
GetRequest request = new GetRequest("user_info");
request.id("qxsZVHsBEQL2UMQUpBFa");
GetResponse getResponse = restHighLevelClient.get(request, RequestOptions.DEFAULT);
User user = JSON.parseObject(getResponse.getSourceAsString(), User.class);
System.out.println(user);
}
这时候我们就能够在控制台看到我们插入的数据
删除文档
@Test
public void testDeleteIndexData() throws IOException {
DeleteRequest request = new DeleteRequest("user_info");
request.id("qxsZVHsBEQL2UMQUpBFa");
restHighLevelClient.delete(request, RequestOptions.DEFAULT);
}
当执行删除文档后,在调用上面查询的test会发现为空
ES集成SpringBoot查询
根据条件查询索引中数据
@Test
public void testSearchData() throws IOException {
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user_info");
BoolQueryBuilder query = QueryBuilders.boolQuery();
query.filter(QueryBuilders.matchAllQuery());
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(query);
searchRequest.source(sourceBuilder);
SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit : hits) {
User user = JSON.parseObject(hit.getSourceAsString(), User.class);
System.out.println(user);
}
}
根据条件匹配数据
@Test
public void testSearchData() throws IOException {
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices("user_info");
BoolQueryBuilder query = QueryBuilders.boolQuery();
query.filter(QueryBuilders.matchAllQuery());
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(query);
searchRequest.source(sourceBuilder);
SearchResponse response = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
for (SearchHit hit : hits) {
User user = JSON.parseObject(hit.getSourceAsString(), User.class);
System.out.println(user);
}
}
ES集成SpringBoot聚合查询
先为接下来查询造点数据
@Test
public void testCreateData() throws IOException {
IndexRequest request = new IndexRequest("good_pig");
String[] groups = {"le_1", "le_2", "le_3", "le_4", "le_5"};
String[] group2s = {"lv_1", "lv_2", "lv_3", "lv_4", "lv_5"};
for (int i = 1; i < 101; i++) {
int ran1 = (int) (Math.random() * (5 - 1) + 1);
int ran2 = (int) (Math.random() * (5 - 1) + 1);
int finalI = i;
User user = new User() {{
setUuid(ran1);
setGroup(groups[ran1]);
setDepartment(group2s[ran2]);
setName("user_" + finalI);
setSynopsis("我是: " + finalI + " 用户");
}};
request.source(JSON.toJSONString(user), XContentType.JSON);
restHighLevelClient.index(request, RequestOptions.DEFAULT);
}
}
实现统计各部门中各组人数
@Test
public void testSearchDataT() throws IOException {
String index = "good_pig";
String aggregationNameOne = "departmentData";
String aggregationNameTwo = "departmentData";
int showSize = 100;
BoolQueryBuilder query = QueryBuilders.boolQuery();
query.filter(QueryBuilders.matchAllQuery());
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(query);
AggregationBuilder aggregationBuilder = AggregationBuilders.terms(aggregationNameOne).field("department.keyword")
.subAggregation(AggregationBuilders.terms(aggregationNameTwo).field("group.keyword").size(showSize))
.size(showSize);
sourceBuilder.aggregation(aggregationBuilder);
SearchRequest request = new SearchRequest();
request.indices(index);
request.source(sourceBuilder);
SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
Terms terms1 = response.getAggregations().get(aggregationNameOne);
for (Terms.Bucket bucket1 : terms1.getBuckets()) {
Terms terms2 = bucket1.getAggregations().get(aggregationNameTwo);
for (Terms.Bucket bucket2 : terms2.getBuckets()) {
System.out.println("部门:" + bucket1.getKeyAsString() + " " + "组:" + bucket2.getKeyAsString() + " " + "数量" + bucket2.getDocCount());
}
}
}
|