SpringBoot入门:SpringBoot2.x整合Elasticsearch7.9.2(RestHighLevelClient)

elasticsearch7.9.2安装及使用可参考博文:Elasticsearch7.9.2+Kibana7.9.2安装使用

现在来介绍下SpringBoot项目中使用Elasticsearch,应该说是集成RestHighLevelClient的使用。

1、引入依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/>
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
<es.version>7.9.2</es.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>

<!-- high client-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>${es.version}</version>
</dependency>

<!-- rest-high-level-client 依赖如下2个jar -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${es.version}</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>${es.version}</version>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.31</version>
</dependency>
</dependencies>

2、SpringBoot中配置elasticsearch

2.1、编写ElasticConfig

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Configuration
public class ElasticConfig {

@Value("${es.host}")
public String host;
@Value("${es.port}")
public int port;
@Value("${es.scheme}")
public String scheme;

@Bean(destroyMethod = "close")
public RestHighLevelClient restHighLevelClient() {
return new RestHighLevelClient(RestClient.builder(
new HttpHost(host, port, scheme)));
}
}

2.2、application.properties配置

application.properties文件中新增如下配置:

1
2
3
4
5
6
7
# 指定服务端口
server.port=8888

# es配置
es.host=localhost
es.port=9200
es.scheme=http

2.3、启动类ElasticSearchApplication

1
2
3
4
5
6
7
@SpringBootApplication
public class ElasticSearchApplication {

public static void main(String[] args){
SpringApplication.run(ElasticSearchApplication.class, args);
}
}

2.4、Junit测试类

测试类如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
@RunWith(SpringRunner.class)
@SpringBootTest
public class ElasticsearchClientTest {
@Autowired
private RestHighLevelClient client;

String index = "users";

/**
* 创建索引
*
* @throws IOException
*/
@Test
public void createIndex() throws IOException {
CreateIndexRequest indexRequest = new CreateIndexRequest(index);
CreateIndexResponse response = client.indices()
.create(indexRequest, RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged());
}

/**
* 判断索引是否存在
*
* @throws IOException
*/
@Test
public void indexExists() throws IOException {
GetIndexRequest request = new GetIndexRequest(index);
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}

/**
* 添加文档
*
* @throws IOException
*/
@Test
public void addDoc() throws IOException {
IndexRequest request = new IndexRequest(index);
String source = JSONObject.toJSONString(new Users(10000, "逍遥", 30));
// 手动设置id
// request.id("10000");
request.source(source, XContentType.JSON);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
System.out.println(response.getResult());
}


/**
* 批量添加文档
*/
@Test
public void batchAddDoc() throws IOException {
BulkRequest bulkRequest = new BulkRequest();
List<IndexRequest> requests = generateRequests();
for (IndexRequest indexRequest : requests) {
bulkRequest.add(indexRequest);
}
BulkResponse responses = client.bulk(bulkRequest, RequestOptions.DEFAULT);
System.out.println(!responses.hasFailures());
}

public List<IndexRequest> generateRequests() {
List<IndexRequest> requests = new ArrayList<>();
requests.add(generateNewsRequest(1, "小明", 22));
requests.add(generateNewsRequest(2, "隔壁老王", 30));
requests.add(generateNewsRequest(3, "lily", 25));
return requests;
}

public IndexRequest generateNewsRequest(Integer id, String name, Integer age) {
IndexRequest indexRequest = new IndexRequest(index);
String source = JSONObject.toJSONString(new Users(id, name, age));
indexRequest.source(source, XContentType.JSON);
return indexRequest;
}

/**
* 更新文档
*
* @throws IOException
*/
@Test
public void updateDoc() throws IOException {
UpdateRequest updateRequest = new UpdateRequest(index, "o01wWHUB2WFtIWtB_nqQ");
Map<String, Object> params = new HashMap<>();
params.put("id", "1");
params.put("name", "逍遥");
params.put("age", 33);
params.put("hobby", "唱歌,跳舞,网上冲浪,看电影,旅行");
updateRequest.doc(params);
UpdateResponse response = client.update(updateRequest, RequestOptions.DEFAULT);
System.out.println(response.getResult());
}

/**
* 搜索
*
* @throws IOException
*/
@Test
public void search() throws IOException {
SearchRequest request = new SearchRequest(index);
SearchSourceBuilder builder = new SearchSourceBuilder();
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
boolQueryBuilder
.must(new RangeQueryBuilder("age").from(20).to(30))
.must(new TermQueryBuilder("id", 3));
builder.query(boolQueryBuilder);
request.source(builder);
System.out.println("搜索语句为: " + request.source().toString());
SearchResponse search = client.search(request, RequestOptions.DEFAULT);
System.out.println(search);
SearchHits hits = search.getHits();
SearchHit[] hitsArr = hits.getHits();
for (SearchHit documentFields : hitsArr) {
System.out.println(documentFields.getSourceAsString());
}
}


@Test
public void search2() {
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.from(0);
sourceBuilder.size(10);
sourceBuilder.fetchSource(new String[]{"name", "age"}, new String[]{});
MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("hobby", "唱歌");
TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name", "逍遥");
RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("age");
rangeQueryBuilder.gte(20);
rangeQueryBuilder.lte(40);
BoolQueryBuilder boolBuilder = QueryBuilders.boolQuery();
boolBuilder.must(matchQueryBuilder);
boolBuilder.must(termQueryBuilder);
boolBuilder.must(rangeQueryBuilder);
sourceBuilder.query(boolBuilder);
SearchRequest searchRequest = new SearchRequest(index);
searchRequest.source(sourceBuilder);
try {
System.out.println("搜索语句为: " + searchRequest.source().toString());
SearchResponse search = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(search);
SearchHits hits = search.getHits();
SearchHit[] hitsArr = hits.getHits();
for (SearchHit documentFields : hitsArr) {
System.out.println(documentFields.getSourceAsString());
}
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 删除文档
* @throws IOException
*/
@Test
public void deleteDoc() throws IOException {
DeleteRequest deleteRequest = new DeleteRequest(index, "vk11WHUB2WFtIWtBQHqR");
DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);
System.out.println(response.getResult());
}

/**
* 删除索引
* @throws IOException
*/
@Test
public void deleteIndex() throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest(index);
AcknowledgedResponse response = client.indices()
.delete(request, RequestOptions.DEFAULT);
System.out.println(response.isAcknowledged());
}

}

Users类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public class Users {

private Integer id;

private String name;

private Integer age;

public Users() {
}

public Users(Integer id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}
}

执行JUnit测试用例,数据查看可通过Kibana或者elasticsearch-head, 这2个工具的使用,相关博文中已列出。

与springboot集成的话也可直接使用ElasticsearchRestTemplate,也是基于RestHighLevelClient的模板封装,有兴趣的可以去研究下。


SpringBoot入门:SpringBoot2.x整合Elasticsearch7.9.2(RestHighLevelClient)
https://river106.cn/posts/fe2d61e8.html
作者
river106
发布于
2020年10月24日
许可协议