// 引入必要的依赖
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 ElasticsearchExample {
// 创建一个简单的Elasticsearch文档索引示例
public static void main(String[] args) {
// 创建RestHighLevelClient实例,用于与Elasticsearch集群通信
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
try {
// 创建一个IndexRequest对象,指定索引名称和文档类型
IndexRequest request = new IndexRequest("posts")
.id("1") // 设置文档ID
.source(XContentType.JSON, "title", "Elasticsearch Java Example", "content", "This is a simple example.");
// 执行索引操作并获取响应
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
// 输出响应结果
System.out.println(response.getResult());
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭客户端连接
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
posts
的索引,并添加了一个具有特定ID的文档。IndexResponse
对象。如果需要更详细的配置或其他功能(如查询、删除等),可以根据需求进一步扩展代码。
上一篇:java linkedlist
下一篇:java线程池的工作原理
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站