使用Java High Level REST Client操作ElasticSearch

使用Java High Level REST Client操作ElasticSearch

這篇介紹如何用Java High Level REST Client來操作ElasticSearch。

Maven dependency

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!-- elasticsearch -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.9.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.9.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.9.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.9</version>
</dependency>

連線資訊json

1
2
3
4
5
6
7
elk.json
--------
{
"host": "<domain>",
"username": "<username>",
"password": "<password>"
}

ELKClient sample code

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
public class ELKClient {

private static final Logger logger = LoggerFactory.getLogger(ELKClient.class.getSimpleName());

private final static int port = 9200;
public final static int SUCCESS = 1;
public final static int FAIL = 0;

private static ELKClient instance;
private static Map<?,?> elkSettings;

public static ELKClient getInstance() {
if (instance == null) {
synchronized (ELKClient.class) {
if (instance == null) {
instance = new ELKClient();
instance.initClient();
}
}
}
return instance;
}

private void initClient() {
try{
InputStream in = ELKClient.class.getResourceAsStream("/elk.json");
String json = IOUtils.toString(in, StandardCharsets.UTF_8);

elkSettings = JSONUtils.jsonToInstance(json, Map.class);
if (elkSettings.size() == 0) {
throw new RuntimeException("Exception : elk.json setting size: 0");
}

} catch (IOException e) {
e.printStackTrace();
}
}

public RestHighLevelClient getClient() {
try {
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(
AuthScope.ANY, new UsernamePasswordCredentials(getProperties("username"), getProperties("password")));
String[] host = getHost().split("://");
RestClientBuilder restClientBuilder = RestClient.builder(new HttpHost(host[1], port, host[0]))
.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider));

return new RestHighLevelClient(restClientBuilder);

} catch (Exception e) {
logger.error(e.getMessage(), e);
}
return null;
}
}

update & search method

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
public int update(String indexName, String documentId, Map<String, Object> params) {
RestHighLevelClient client = null;
try {
client = getClient();
UpdateRequest request = new UpdateRequest(indexName, documentId).doc(params);
UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
if (updateResponse.status() == RestStatus.OK) {
return SUCCESS;
}
} catch (Exception e) {
e.printStackTrace();
return FAIL;
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return FAIL;
}

public SearchResponse search(String indexName, String key, String value) {
RestHighLevelClient client = null;
try {
client = getClient();
SearchRequest searchRequest = new SearchRequest(indexName);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
QueryBuilder matchQueryBuilder = QueryBuilders.matchQuery(key, value).operator(
Operator.AND);
sourceBuilder.query(matchQueryBuilder);
searchRequest.source(sourceBuilder);
return client.search(searchRequest, RequestOptions.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (client != null) {
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}