Elasticsearch Java High Level API 演示(一)- 简单文档操作

本系列文章旨在演示如何通过 Elasticsearch 官方的 Java 客户端连接,操作 Elasticsearch 服务,目标是让相关的Java开发人员快速上手,所以本文不会涉及 Elasticsearch 的相关理论。

环境准备

本文使用 Elasticsearch 服务的 7.5.2 版本,搭建的过程可以参考 在MacOS中安装Elasticsearch

Java 的版本是: JDK8

Elasticsearch 的Java客户端使用: Java High Level API 7.5

项目依赖及设置

在 IEDA 或 Eclipse 中新建一个 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
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.5.2</version>
</dependency>

<!-- For Log -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
<version>2.11.1</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.24</version>
</dependency>

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.21</version>
</dependency>

并添加对 JDK8 的编译支持

1
2
3
4
5
6
7
8
9
10
11
12
13
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>

初始化链接

使用默认的 Elasticsearch 服务配置链接服务器

1
2
3
4
5
6
7
8
9
public static RestHighLevelClient connnect() {

RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http")));

return client;
}

同步调用风格

建立单个文档(Index)

使用在connect方法中返回的连接

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
public static void createIndexSync(RestHighLevelClient client) {

try {

IndexRequest request = new IndexRequest("posts");
request.id("1");
String jsonString = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2013-01-31\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
request.source(jsonString, XContentType.JSON);

IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);

LOG.info("Complete the creation index: {}", indexResponse.status());

} catch(Exception e) {

LOG.error("Error when create index: ", e);

} finally {
if (client != null) {
try {
client.close();
} catch(IOException e) { }
}
}

}

获取单个文档

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
public static void getIndexSync(RestHighLevelClient client) {

try {

GetRequest getRequest = new GetRequest(
"posts",
"1");

GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);

if (getResponse.isExists()) {

LOG.info("Get Index: {}", getResponse.getSourceAsString());
}


} catch(Exception e) {

LOG.error("Error when get index: ", e);

} finally {
if (client != null) {
try {
client.close();
} catch(IOException e) { }
}
}
}

判断是否存在指定文档

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
public static void existSync(RestHighLevelClient client) {

try {
GetRequest getRequest = new GetRequest(
"posts",
"1");
getRequest.fetchSourceContext(new FetchSourceContext(false));
getRequest.storedFields("_none_");

boolean exists = client.exists(getRequest, RequestOptions.DEFAULT);

LOG.info("Exist: {}", exists);

} catch(Exception e) {

LOG.error("Error when exist: ", e);

} finally {
if (client != null) {
try {
client.close();
} catch(IOException e) { }
}
}

}

删除单个文档

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
public static void deleteIndexSync(RestHighLevelClient client) {

try {
DeleteRequest request = new DeleteRequest(
"posts",
"1");

DeleteResponse deleteResponse = client.delete(
request, RequestOptions.DEFAULT);

if (deleteResponse.status() == RestStatus.OK) {

LOG.info("Deleted: {}", deleteResponse.getId());
}

} catch(Exception e) {

LOG.error("Error when exist: ", e);

} finally {
if (client != null) {
try {
client.close();
} catch(IOException e) { }
}
}

}

更新单个文档

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
public static void updateSync(RestHighLevelClient client) {

try {

UpdateRequest request = new UpdateRequest(
"posts",
"1")
.doc("updated", new Date(),
"reason", "daily update");

UpdateResponse updateResponse = client.update(
request, RequestOptions.DEFAULT);

if (updateResponse.status() == RestStatus.OK) {

LOG.info("Update: {}", updateResponse.getId());
}

} catch(Exception e) {

LOG.error("Error when update: ", e);

} finally {
if (client != null) {
try {
client.close();
} catch(IOException e) { }
}
}
}

获取文档的结构和统计信息

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
public static void getTermVectorsSync(RestHighLevelClient client) {

try {

TermVectorsRequest request = new TermVectorsRequest("posts", "1");
request.setFields("user");

TermVectorsResponse response =
client.termvectors(request, RequestOptions.DEFAULT);

if (response.getFound()) {
for (TermVectorsResponse.TermVector tv : response.getTermVectorsList()) {
String fieldname = tv.getFieldName();
int docCount = tv.getFieldStatistics().getDocCount();
long sumTotalTermFreq =
tv.getFieldStatistics().getSumTotalTermFreq();
long sumDocFreq = tv.getFieldStatistics().getSumDocFreq();

LOG.info("fieldName = {}, docCount = {}, sumTotalTermFreq = {}", fieldname, sumTotalTermFreq, sumDocFreq);
}
}

} catch(Exception e) {

LOG.error("Error when Get Term Vectors: ", e);

} finally {
if (client != null) {
try {
client.close();
} catch(IOException e) { }
}
}
}

如果对 Elasticsearch 的功能感兴趣,又希望能快速上手,可以试试 ElasticSearch教程

本文标题:Elasticsearch Java High Level API 演示(一)- 简单文档操作

文章作者:Morning Star

发布时间:2020年02月09日 - 10:02

最后更新:2021年04月16日 - 15:04

原始链接:https://www.mls-tech.info/microservice/elasticsearch/es-java-high-level-api-01/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。