以下是一个详细的Java结合Elasticsearch的操作案例,涵盖了从环境准备到具体操作的多个方面,帮助你在Java环境中使用Elasticsearch进行索引的创建、文档的增删改查以及数据查询等操作。
一、环境准备
1. 安装 Elasticsearch
- 下载 Elasticsearch:访问 Elasticsearch 官网 下载适合你操作系统的 Elasticsearch 7.x 版本。
- 配置 Elasticsearch:
- 解压安装包,并进入配置文件
elasticsearch.yml
。 - 配置集群名称、节点名称、网络地址和端口等。
- 启动 Elasticsearch 服务,通过运行
./bin/elasticsearch
启动服务。
- 解压安装包,并进入配置文件
2. 安装 Java 开发环境
- Java 环境:确保已经安装了 JDK 1.8 或更高版本,并配置好
JAVA_HOME
环境变量。
3. 添加 Elasticsearch 客户端依赖
在你的 Java 项目中,添加 Elasticsearch High Level REST Client 依赖。
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.x.x</version> <!-- 替换为实际使用的版本号 -->
</dependency>
二、Java 操作 Elasticsearch 案例
1. 初始化 Elasticsearch 客户端
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
public class ElasticsearchClient {
private static final String HOSTNAME = "localhost";
private static final int PORT = 9200;
private static final String SCHEME = "http";
public static RestHighLevelClient createClient() {
return new RestHighLevelClient(
RestClient.builder(new HttpHost(HOSTNAME, PORT, SCHEME)));
}
}
2. 创建索引
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
public class IndexExample {
public static void createIndex(RestHighLevelClient client) throws IOException {
CreateIndexRequest request = new CreateIndexRequest("users");
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
boolean acknowledged = createIndexResponse.isAcknowledged();
System.out.println("Index created: " + acknowledged);
}
public static void main(String[] args) throws IOException {
RestHighLevelClient client = ElasticsearchClient.createClient();
createIndex(client);
client.close();
}
}
3. 删除索引
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
public class DeleteIndex {
public static void deleteIndex(RestHighLevelClient client) throws IOException {
DeleteIndexRequest request = new DeleteIndexRequest("users");
DeleteIndexResponse deleteIndexResponse = client.indices().delete(request, RequestOptions.DEFAULT);
System.out.println("Index deleted: " + deleteIndexResponse.isAcknowledged());
}
public static void main(String[] args) throws IOException {
RestHighLevelClient client = ElasticsearchClient.createClient();
deleteIndex(client);
client.close();
}
}
4. 插入文档
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class AddDocument {
public static void addDocument(RestHighLevelClient client) throws IOException {
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("name", "John Doe");
jsonMap.put("age", 30);
jsonMap.put("email", "john.doe@example.com");
IndexRequest request = new IndexRequest("users")
.id("1")
.source(jsonMap, XContentType.JSON);
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
System.out.println("Document added with ID: " + indexResponse.getId());
}
public static void main(String[] args) throws IOException {
RestHighLevelClient client = ElasticsearchClient.createClient();
addDocument(client);
client.close();
}
}
5. 搜索文档
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import java.io.IOException;
public class SearchDocument {
public static void searchDocument(RestHighLevelClient client) throws IOException {
SearchRequest searchRequest = new SearchRequest("users");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("name", "John"));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println("Search results: " + searchResponse.getHits().getTotalHits().value);
}
public static void main(String[] args) throws IOException {
RestHighLevelClient client = ElasticsearchClient.createClient();
searchDocument(client);
client.close();
}
}
6. 更新文档
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
public class UpdateDocument {
public static void updateDocument(RestHighLevelClient client) throws IOException {
String jsonString = "{" +
"\"name\":\"John Updated\"," +
"\"age\":31," +
"\"email\":\"john.updated@example.com\"" +
"}";
UpdateRequest request = new UpdateRequest("users", "1")
.doc(jsonString, XContentType.JSON);
UpdateResponse updateResponse = client.update(request, RequestOptions.DEFAULT);
System.out.println("Document updated with ID: " + updateResponse.getId());
}
public static void main(String[] args) throws IOException {
RestHighLevelClient client = ElasticsearchClient.createClient();
updateDocument(client);
client.close();
}
}
7. 删除文档
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import java.io.IOException;
public class DeleteDocumentExample {
public static void deleteDocument(RestHighLevelClient client) throws IOException {
DeleteRequest request = new DeleteRequest("users", "1");
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
System.out.println("Document deleted with ID: " + response.getId());
}
public static void main(String[] args) throws IOException {
RestHighLevelClient client = ElasticsearchClient.createClient();
deleteDocument(client);
client.close();
}
}
8. 关闭客户端
在操作完成后,确保关闭客户端以释放资源:
client.close();
9. 异常处理
在实际开发中,处理各种异常(如网络错误、Elasticsearch集群问题等)是必要的。在每个操作中,应使用 try-catch
块来捕获并处理异常。
结论
以上是一个基于Java的Elasticsearch操作案例,涵盖了从初始化客户端、创建和删除索引、文档的增删改查操作等内容。通过这些示例,你可以在实际项目中轻松集成Elasticsearch,并根据业务需求进行定制化开发。