resthighlevelclient 添加文档
时间: 2023-09-11 14:04:55 浏览: 75
使用 Elasticsearch 的 Java 客户端 resthighlevelclient 添加文档的步骤如下:
1. 创建 Elasticsearch 客户端连接
```java
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
```
2. 准备文档数据
```java
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("user", "kimchy");
jsonMap.put("age", 30);
jsonMap.put("postDate", new Date());
jsonMap.put("message", "trying out Elasticsearch");
```
3. 创建索引请求
```java
IndexRequest request = new IndexRequest("posts")
.id("1")
.source(jsonMap);
```
4. 发送索引请求
```java
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
```
5. 处理响应结果
```java
if (response.getResult() == DocWriteResponse.Result.CREATED) {
System.out.println("文档创建成功");
} else if (response.getResult() == DocWriteResponse.Result.UPDATED) {
System.out.println("文档更新成功");
}
```
完整的示例代码:
```java
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("user", "kimchy");
jsonMap.put("age", 30);
jsonMap.put("postDate", new Date());
jsonMap.put("message", "trying out Elasticsearch");
IndexRequest request = new IndexRequest("posts")
.id("1")
.source(jsonMap);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
if (response.getResult() == DocWriteResponse.Result.CREATED) {
System.out.println("文档创建成功");
} else if (response.getResult() == DocWriteResponse.Result.UPDATED) {
System.out.println("文档更新成功");
}
client.close();
```
阅读全文