ElasticSearch学习笔记文档操作、RestHighLevelClient的使用
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
public class ElasticSearchDocumentExample {
public static void main(String[] args) throws IOException {
// 初始化RestHighLevelClient
try (RestHighLevelClient client = new RestHighLevelClient(...)) {
// 创建索引请求
IndexRequest request = new IndexRequest("posts");
// 设置索引文档的ID
String jsonString = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2023-04-07\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
request.source(jsonString, XContentType.JSON);
// 执行请求,并获取响应
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
// 打印索引操作的结果
System.out.println("索引文档成功: " + indexResponse.getResult());
}
}
}
这段代码演示了如何使用RestHighLevelClient
在Elasticsearch中创建和索引一个JSON文档。首先,创建了一个IndexRequest
对象,并指定了要索引的文档和索引名称。然后,设置了文档的ID和要索引的JSON字符串内容。最后,使用RestHighLevelClient
的index
方法执行索引操作,并打印出操作结果。
评论已关闭