Java连接Elasticsearch(v7.17.3)
创始人
2025-05-31 02:44:15

使用java连接elasticsearch-v7.17.3

  • 1. 前言
  • 2. 准备工作
  • 3. 添加依赖
  • 4. 连接ElasticSearch
  • 5. 操作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.clientelasticsearch-rest-high-level-client7.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

相关内容

热门资讯

2025西藏顶配答卷:团结是笔...   在雪域高原的壮阔画卷中,2025年的西藏正以昂扬姿态书写着民族团结的奋进新篇。这一年,高原儿女牢...
突传噩耗!王宗合,辞世! 【导读】鹏华基金原副总经理、基金经理王宗合逝世中国基金报记者 忆山12月30日,记者从业内获悉,鹏华...
解放军:已做好真打实打准备! 新闻荐读 12月29日开始,中国人民解放军东部战区组织陆军、海军、空军、火箭军等兵力,位台湾海峡、台...