// 引入必要的依赖
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;
public class ElasticsearchExample {
// 创建一个简单的Elasticsearch客户端并执行索引操作
public static void main(String[] args) {
// 初始化RestHighLevelClient,连接到Elasticsearch集群
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
// 定义要索引的文档内容
String jsonString = "{" +
"\"user\":\"kimchy\"," +
"\"postDate\":\"2013-01-30\"," +
"\"message\":\"trying out Elasticsearch\"" +
"}";
// 创建IndexRequest对象,并指定索引名称、类型和文档ID
IndexRequest indexRequest = new IndexRequest("posts")
.id("1")
.source(jsonString, XContentType.JSON);
try {
// 执行索引请求并获取响应
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();
}
}
}
}
IndexRequest
、IndexResponse
、RestHighLevelClient
等。RestHighLevelClient
连接到本地的Elasticsearch集群(假设Elasticsearch运行在localhost:9200
)。IndexRequest
对象来指定索引名称、文档ID以及文档内容。client.index()
方法执行索引操作,并获取响应结果。这段代码展示了如何使用Java与Elasticsearch进行交互,并将一个简单的文档索引到Elasticsearch中。
上一篇:java字符串数组
下一篇:java数组去重
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站