Java连接Elasticsearch(v7.17.3) |
您所在的位置:网站首页 › 关闭elasticsearch › Java连接Elasticsearch(v7.17.3) |
使用java连接elasticsearch-v7.17.3
1. 前言2. 准备工作3. 添加依赖4. 连接ElasticSearch5. 操作ElasticSearch 5.1 创建索引 5.2 删除索引 5.3 添加文档 5.4 更新文档: 5.5 删除文档 5.6 关闭连接
1. 前言
ElasticSearch是一个基于Lucene的搜索服务器,它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。ElasticSearch是用Java开发的,因此Java API是与ElasticSearch交互的主要方式。本文将介绍如何使用Java API连接ElasticSearch7.17.3。 2. 准备工作在开始之前,需要确保已经安装了ElasticSearch7.17.3,并且已经启动了ElasticSearch服务。 3. 添加依赖在项目的pom.xml文件中添加以下依赖: org.elasticsearch.client elasticsearch-rest-high-level-client 7.17.3 4. 连接ElasticSearch使用以下代码连接ElasticSearch: RestHighLevelClient client = new RestHighLevelClient( RestClient.builder( new HttpHost("localhost", 9200, "http")));其中,localhost是ElasticSearch所在的主机名,9200是ElasticSearch的HTTP端口号。 5. 操作ElasticSearch连接成功后,就可以使用Java API操作ElasticSearch了。以下是一些常用的操作: 5.1 创建索引 CreateIndexRequest request = new CreateIndexRequest("index_name"); client.indices().create(request, RequestOptions.DEFAULT);其中,index_name是索引的名称。 5.2 删除索引 DeleteIndexRequest request = new DeleteIndexRequest("index_name"); client.indices().delete(request, RequestOptions.DEFAULT); 5.3 添加文档 IndexRequest request = new IndexRequest("index_name"); request.id("document_id"); request.source("field1", "value1", "field2", "value2", "field3", "value3"); client.index(request, RequestOptions.DEFAULT); 5.4 更新文档: UpdateRequest request = new UpdateRequest("index_name", "document_id"); request.doc("field1", "new_value1", "field2", "new_value2"); client.update(request, RequestOptions.DEFAULT); 5.5 删除文档 DeleteRequest request = new DeleteRequest("index_name", "document_id"); client.delete(request, RequestOptions.DEFAULT); 5.6 关闭连接 client.close();本文在此基本结束了,下一章节主要讲解如何使用springboot连接elasticsearch |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |