SpringBoot 操作 ElasticSearch 详解

1.ElasticSearch简介

Elasticsearch是位于Elastic Stack核心的分布式搜索和分析引擎。Logstash和Beats有助于收集,聚合和丰富您的数据并将其存储在Elasticsearch中。使用Kibana,您可以交互式地探索,可视化和共享对数据的见解,并管理和监视堆栈。

2.Maven 引入相关依赖

pom.xml配置如下:

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
xml复制代码<?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>
<version>2.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.james</groupId>
<artifactId>elasticsearch_demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>elasticsearch_demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.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-actuator</artifactId>
</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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.4.0</version>
</dependency>

<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.7</version>
</dependency>

<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.4.0</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.2</version>
<exclusions>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</exclusion>
<exclusion>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
</exclusion>
</exclusions>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.12.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.12.2</version>
</dependency>

<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>

</project>

3.ElasticSearch 连接配置

(1) application.properties配置
1
2
3
properties复制代码elasticsearch.address=localhost:9200
elasticsearch.username=elastic
elasticsearch.password=elastic
(2) java 连接配置类
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
java复制代码@Configuration
public class ElasticsearchConfig {

@Value("${elasticsearch.address}")
private String address;

@Value("${elasticsearch.username}")
private String userName;

@Value("${elasticsearch.password}")
private String password;

@Bean(destroyMethod = "close")
public RestHighLevelClient restClient() {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials(userName, password));


// 拆分地址
List<HttpHost> hostLists = new ArrayList<>();
String[] hostList = address.split(",");
for (String addr : hostList) {
String host = addr.split(":")[0];
String port = addr.split(":")[1];
hostLists.add(new HttpHost(host, Integer.parseInt(port), "http"));
}
// 转换成 HttpHost 数组
HttpHost[] httpHost = hostLists.toArray(new HttpHost[]{});

RestClientBuilder builder = RestClient.builder(httpHost).
setHttpClientConfigCallback(httpClientBuilder ->
httpClientBuilder.setMaxConnTotal(100)
.setMaxConnPerRoute(100)
.setDefaultCredentialsProvider(credentialsProvider)).
setRequestConfigCallback(requestConfigBuilder ->
requestConfigBuilder.setConnectTimeout(10000)
.setSocketTimeout(60000));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;

}
}

4. Java 代码示例

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
java复制代码@Service
@Slf4j
public class ProfileService {


private RestHighLevelClient restClient;
private ObjectMapper objectMapper;

@Autowired
public ProfileService(RestHighLevelClient restClient, ObjectMapper objectMapper) {
this.restClient = restClient;
this.objectMapper = objectMapper;
}

public String createProfileDocument(ProfileDocument document) throws Exception {
UUID uuid = UUID.randomUUID();
document.setId(uuid.toString());
IndexRequest indexRequest = new IndexRequest(INDEX, TYPE, document.getId())
.source(convertProfileDocumentToMap(document));
IndexResponse indexResponse = restClient.index(indexRequest, RequestOptions.DEFAULT);
return indexResponse.getResult().name();
}

public List<ProfileDocument> findAll() throws Exception {
SearchRequest searchRequest = buildSearchRequest(INDEX, TYPE);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse =
restClient.search(searchRequest, RequestOptions.DEFAULT);
return getSearchResult(searchResponse);
}

private SearchRequest buildSearchRequest(String index, String type) {
SearchRequest searchRequest = new SearchRequest();
searchRequest.indices(index);
searchRequest.types(type);
return searchRequest;
}

private List<ProfileDocument> getSearchResult(SearchResponse response) {
SearchHit[] searchHit = response.getHits().getHits();
List<ProfileDocument> profileDocuments = new ArrayList<>();
for (SearchHit hit : searchHit) {
profileDocuments
.add(objectMapper
.convertValue(hit
.getSourceAsMap(), ProfileDocument.class));
}
return profileDocuments;
}

private Map<String, Object> convertProfileDocumentToMap(ProfileDocument profileDocument) {
return objectMapper.convertValue(profileDocument, Map.class);
}

private ProfileDocument convertMapToProfileDocument(Map<String, Object> map) {
return objectMapper.convertValue(map, ProfileDocument.class);
}

}

本文转载自: 掘金

开发者博客 – 和开发相关的 这里全都有

0%