// 引入必要的依赖
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
public class ElasticsearchJavaApiExample {
public static void main(String[] args) {
// 创建一个 RestHighLevelClient 实例,用于与 Elasticsearch 进行交互
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
try {
// 创建一个索引请求
IndexRequest indexRequest = new IndexRequest("testindex")
.id("1")
.source(XContentType.JSON, "field", "value");
// 执行索引请求并获取响应
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
// 输出索引响应信息
System.out.println(indexResponse.getResult());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭客户端连接
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
RestHighLevelClient 和相关类,这些类用于与 Elasticsearch 进行交互。RestHighLevelClient 创建一个客户端实例,指定 Elasticsearch 的主机和端口。IndexRequest 类创建一个索引请求,指定索引名称、文档 ID 和文档内容。client.index() 方法执行索引请求,并获取返回的 IndexResponse 对象。如果你需要更多关于如何配置依赖或运行此代码的帮助,请告诉我。
上一篇:java读取excel中的图片
下一篇:ubuntu 卸载java
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站