java连接es代码
时间: 2024-10-13 10:15:13 浏览: 22
在Java中,要连接Elasticsearch(ES),你可以使用官方提供的Elasticsearch客户端库,即elasticsearch Java High-Level REST Client。以下是一个基本的例子,展示了如何创建连接、搜索文档以及执行其他操作:
首先,你需要在你的项目中添加依赖。如果你使用Maven,可以在pom.xml文件中加入:
```xml
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.16.0+</version> <!-- 根据实际版本替换 -->
</dependency>
```
然后,你可以编写如下的代码片段来建立连接并执行操作:
```java
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
public class ElasticsearchExample {
private static final String CLUSTER_NAME = "your-cluster-name";
private static final String INDEX_NAME = "your-index-name";
private RestHighLevelClient client;
public ElasticsearchExample() {
// 创建RestHighLevelClient实例,这里使用的是默认配置
client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http"))); // 替换为你的ES服务器地址和端口
try {
// 检查是否连接成功
client.info(RequestOptions.DEFAULT);
} catch (Exception e) {
System.err.println("Failed to connect to ES: " + e.getMessage());
return;
}
}
public void indexDocument(String id, String jsonDoc) {
IndexRequest request = new IndexRequest(INDEX_NAME).id(id).source(jsonDoc);
try {
client.index(request, RequestOptions.DEFAULT);
} catch (Exception e) {
System.err.println("Error indexing document: " + e.getMessage());
}
}
public SearchResponse searchDocuments(String query) {
SearchRequest searchRequest = new SearchRequest(INDEX_NAME);
searchRequest.source().queryBuilders.matchQuery("field", query); // 替换"field"为你需要查询的字段
try {
return client.search(searchRequest, RequestOptions.DEFAULT);
} catch (Exception e) {
System.err.println("Error searching documents: " + e.getMessage());
return null;
}
}
public void closeConnection() {
client.close();
}
}
```
记得将`your-cluster-name`和`your-index-name`替换为你的实际集群名和索引名。
阅读全文