import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
public class ElasticsearchExample {
public static void main(String[] args) {
// 创建一个 RestHighLevelClient 实例,用于与 Elasticsearch 进行交互
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
// 创建一个 IndexRequest 对象,指定索引名称和文档类型
IndexRequest indexRequest = new IndexRequest("test-index")
.id("1")
.source(XContentType.JSON, "field", "value");
try {
// 执行索引操作,并获取响应结果
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
System.out.println("Document indexed with ID: " + indexResponse.getId());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
// 关闭客户端连接
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
RestHighLevelClient:这是 Elasticsearch 提供的高级 REST 客户端,用于与 Elasticsearch 集群进行交互。它封装了常见的操作,如索引、搜索、更新等。
IndexRequest:用于创建一个新的文档或更新现有文档。在这个例子中,我们指定了索引名称为 test-index,文档 ID 为 1,并且通过 source 方法指定了文档的内容。
XContentType.JSON:表示文档内容的格式为 JSON。
client.index():执行索引操作,并返回一个 IndexResponse 对象,其中包含了操作的结果信息。
client.close():在完成所有操作后,关闭客户端连接以释放资源。
异常处理:使用 try-catch 块来捕获并处理可能发生的 IOException 异常。
如果你需要更多关于 Elasticsearch Java API 的示例代码或详细说明,请查阅官方文档。
上一篇:java cloneable
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站