Elasticsearch连续剧之实战篇Java操作es
在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.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
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("example");
client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
// 插入文档
IndexRequest indexRequest = new IndexRequest("example").id("1");
indexRequest.source(XContentType.JSON, "field", "value");
IndexResponse indexResponse = client.index(indexRequest, RequestOptions.DEFAULT);
// 搜索文档
SearchRequest searchRequest = new SearchRequest("example");
searchRequest.source().query(QueryBuilders.matchAllQuery());
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
// 更新文档
UpdateRequest updateRe
评论已关闭