ElasticSearch是一个基于Lucene的搜索服务器,它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。ElasticSearch是用Java开发的,因此Java API是与ElasticSearch交互的主要方式。本文将介绍如何使用Java API连接ElasticSearch7.17.3。
在开始之前,需要确保已经安装了ElasticSearch7.17.3,并且已经启动了ElasticSearch服务。
在项目的pom.xml文件中添加以下依赖:
org.elasticsearch.client elasticsearch-rest-high-level-client 7.17.3
使用以下代码连接ElasticSearch:
RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
其中,localhost是ElasticSearch所在的主机名,9200是ElasticSearch的HTTP端口号。
连接成功后,就可以使用Java API操作ElasticSearch了。以下是一些常用的操作:
CreateIndexRequest request = new CreateIndexRequest("index_name");
client.indices().create(request, RequestOptions.DEFAULT);
其中,index_name是索引的名称。
DeleteIndexRequest request = new DeleteIndexRequest("index_name");
client.indices().delete(request, RequestOptions.DEFAULT);
IndexRequest request = new IndexRequest("index_name");
request.id("document_id");
request.source("field1", "value1","field2", "value2","field3", "value3");
client.index(request, RequestOptions.DEFAULT);
UpdateRequest request = new UpdateRequest("index_name", "document_id");
request.doc("field1", "new_value1","field2", "new_value2");
client.update(request, RequestOptions.DEFAULT);
DeleteRequest request = new DeleteRequest("index_name", "document_id");
client.delete(request, RequestOptions.DEFAULT);
client.close();
本文在此基本结束了,下一章节主要讲解如何使用springboot连接elasticsearch
上一篇:二叉搜索树:AVL平衡