java es API如何使用Elastic? 索引和doc使用
时间: 2023-12-16 20:02:41 浏览: 89
java api 检索elasticsearch数据
Java中使用Elastic主要通过Elasticsearch Java API来实现,该API封装了Elastic的REST API,可以通过Java代码实现索引、文档的增删改查等操作。
以下是一个简单的示例:
1. 创建索引:
```
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
CreateIndexRequest request = new CreateIndexRequest("my_index");
client.indices().create(request, RequestOptions.DEFAULT);
```
2. 创建文档:
```
IndexRequest request = new IndexRequest("my_index");
request.id("1");
String jsonString = "{" +
"\"title\":\"hello world\"," +
"\"content\":\"this is my first document\"" +
"}";
request.source(jsonString, XContentType.JSON);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
```
3. 查询文档:
```
GetRequest getRequest = new GetRequest("my_index", "1");
GetResponse response = client.get(getRequest, RequestOptions.DEFAULT);
```
4. 更新文档:
```
UpdateRequest request = new UpdateRequest("my_index", "1");
request.doc("content", "this is my updated document");
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
```
5. 删除文档:
```
DeleteRequest request = new DeleteRequest("my_index", "1");
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
```
在实际应用中,还可以使用Elasticsearch的QueryBuilder来构建复杂的查询条件,如范围查询、模糊查询等。
需要注意的是,使用Elasticsearch Java API需要导入相应的依赖,如elasticsearch和elasticsearch-rest-high-level-client等。另外,建议使用连接池来管理连接,以提高性能和稳定性。
阅读全文