Elasticsearch Java API 怎么用
时间: 2024-02-29 19:25:38 浏览: 87
Elasticsearch Java API 是 Elasticsearch 提供的 Java 客户端 API,可以通过 Java 代码操作 Elasticsearch。
使用 Elasticsearch Java API 可以进行以下操作:
1. 创建索引
2. 删除索引
3. 添加文档
4. 更新文档
5. 删除文档
6. 查询文档
使用 Elasticsearch Java API 的步骤如下:
1. 添加 Maven 依赖
```xml
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.14.0</version>
</dependency>
```
2. 创建客户端
```java
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")));
```
3. 创建索引
```java
CreateIndexRequest request = new CreateIndexRequest("my_index");
client.indices().create(request, RequestOptions.DEFAULT);
```
4. 添加文档
```java
IndexRequest request = new IndexRequest("my_index");
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("user", "kimchy");
jsonMap.put("postDate", new Date());
jsonMap.put("message", "trying out Elasticsearch");
request.source(jsonMap);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
```
5. 查询文档
```java
SearchRequest searchRequest = new SearchRequest("my_index");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("message", "Elasticsearch"));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
```
6. 关闭客户端
```java
client.close();
```
阅读全文