Java操作ElasticSearch
在Java中操作ElasticSearch,你可以使用ElasticSearch的Java Rest Client。以下是一个简单的例子,展示了如何使用Java Rest Client连接到ElasticSearch并执行基本的CRUD操作。
首先,确保你的项目中包含了ElasticSearch的Java Rest Client依赖。如果你使用Maven,可以添加如下依赖:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.10.0</version>
</dependency>
以下是一个简单的Java程序,演示了如何连接到ElasticSearch,创建索引,添加文档,搜索文档,更新文档,和删除文档。
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.SearchHit;
public class ElasticSearchExample {
public static void main(String[] args) throws IOException {
// 初始化RestHighLevelClient
try (RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(new HttpHost("localhost", 9200, "http")))) {
// 创建索引
CreateIndexRequest createIndexRequest = new CreateIndexRequest("test_index");
client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
// 添加文档
IndexRequest indexRequest = new IndexRequest("test_index");
indexRequest.id("1");
indexRequest.source("field1", "value1");
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
// 搜索文档
SearchRequest searchRequest = new SearchRequest("test_index");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("field1", "value1"));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
SearchHit[] searchHits = searchResponse.getHits()
评论已关闭