Elasticsearch 7.x入门学习-Java API操作
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.common.xcontent.XContentType;
public class ElasticsearchExample {
public static void main(String[] args) {
// 初始化Elasticsearch客户端
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "http"));
RestHighLevelClient client = new RestHighLevelClient(builder);
try {
// 创建索引请求
IndexRequest request = new IndexRequest("posts");
// 设置索引数据
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("索引创建成功!");
System.out.println("文档索引: " + indexResponse.getIndex());
System.out.println("文档ID: " + indexResponse.getId());
System.out.println("版本号: " + indexResponse.getVersion());
System.out.println("结果: " + indexResponse.getResult());
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭客户端
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
这段代码展示了如何使用Java High Level REST Client在Elasticsearch中创建一个索引。首先,我们初始化了一个RestHighLevelClient
客户端,然后创建了一个IndexRequest
对象,并设置了要索引的数据。接着,我们执行了这个请求并打印了响应结果。最后,在操作完成后关闭了客户端以释放资源。
评论已关闭