在Java代码中怎么使用API操作Elasticsearch
时间: 2024-02-24 18:56:18 浏览: 78
要在Java代码中使用API操作Elasticsearch,你需要使用Elasticsearch提供的Java客户端库。以下是使用Java客户端库进行常见的操作示例:
1. 创建连接:
```
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
```
2. 创建索引:
```
CreateIndexRequest request = new CreateIndexRequest("index_name");
client.indices().create(request, RequestOptions.DEFAULT);
```
3. 添加文档:
```
IndexRequest request = new IndexRequest("index_name");
request.id("document_id");
String jsonString = "{"name":"John Doe","age":25}";
request.source(jsonString, XContentType.JSON);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
```
4. 搜索文档:
```
SearchRequest searchRequest = new SearchRequest("index_name");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("name", "john"));
searchRequest.source(searchSourceBuilder);
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
```
以上只是一些基本的操作示例,你可以查看Elasticsearch Java客户端库的官方文档了解更多的API操作。
阅读全文