opensearch java实例_Elasticsearch Client(JAVA API) JAVA实例
时间: 2024-03-01 16:49:47 浏览: 184
JAVA实现ElasticSearch的简单实例
以下是一个简单的 Elasticsearch Client(JAVA API) 的 JAVA 实例,使用的是 Elasticsearch 7.x 版本的 API:
1. 添加 Maven 依赖
```xml
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.10.1</version>
</dependency>
```
2. 创建 Elasticsearch 客户端连接
```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");
request.id("1");
String jsonString = "{" +
"\"name\":\"John\"," +
"\"age\":30," +
"\"city\":\"New York\"" +
"}";
request.source(jsonString, XContentType.JSON);
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
```
5. 搜索文档
```java
SearchRequest searchRequest = new SearchRequest("my_index");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("name", "John"));
searchRequest.source(searchSourceBuilder);
SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);
```
6. 关闭客户端连接
```java
client.close();
```
阅读全文