通过官方文档高效学习ElasticSearch的JavaAPI实现!

本文涉及的产品
Elasticsearch Serverless通用抵扣包,测试体验金 200元
简介: 有人说学习一项技术最好的资料是官方文档,对大部分技术来说确实是这样的。但是官方文档不一定适合每个人去看,比如一个初学者,直接让他看Spring的官方文档,其实是不合适的。今天我会结合ElasticSearch的一个客户端官方文档介绍ES在Java中的API应用。

听说微信搜索《Java鱼仔》会变更强!


本文收录于JavaStarter ,里面有我完整的Java系列文章,学习或面试都可以看看!


(一)概述


有人说学习一项技术最好的资料是官方文档,对大部分技术来说确实是这样的。但是官方文档不一定适合每个人去看,比如一个初学者,直接让他看Spring的官方文档,其实是不合适的。今天我会结合ElasticSearch的一个客户端官方文档介绍ES在Java中的API应用。


官方文档不一定好找,这里直接给出地址:


www.elastic.co/guide/en/el…


你可以选择自己对应版本的文档来参考,我这里选择的是7.6版本,选用的是Java High Level REST Client。


网络异常,图片无法展示
|


(二)项目搭建


2.1 引入依赖


首先需要创建一个项目,创建项目就不介绍了,引入ES核心依赖:


<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency>

为了防止版本问题导致服务器客户端冲突,尽量将ES的版本设置的和自己安装的服务器端版本一致:

<properties><java.version>1.8</java.version><elasticsearch.version>7.6.1</elasticsearch.version></properties>

后续还会用一些json和web以及测试的操作,引入这些依赖:

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.76</version></dependency>

2.2 项目基本配置


编写个配置类注入restHighLevelClient对象:

@ConfigurationpublicclassElasticSearchConfig {
@BeanpublicRestHighLevelClientrestHighLevelClient(){
RestHighLevelClientclient=newRestHighLevelClient(
RestClient.builder(
newHttpHost("192.168.78.128",9200,"http")
                )
        );
returnclient;
    }
}

后续会用到实体类,这里先提供了:

@Data@AllArgsConstructorpublicclassUser {
privateStringname;
privateStringaddress;
}

接下来的操作都在SpringBootTest中进行,首先通过@Autowired注入

RestHighLevelClient对象@SpringBootTestclassElasticsearchdemoApplicationTests {
@AutowiredprivateRestHighLevelClientrestHighLevelClient;
}

(三)索引API


还是按照学习ES语法的顺序学习语法,找到索引API ,API中的操作很多,我主要选一些重要的讲一下


网络异常,图片无法展示
|


3.1 创建索引


创建索引的主要对象是CreateIndexRequest

@TestpublicvoidtestCreateIndex() throwsIOException {
//创建索引CreateIndexRequestrequest=newCreateIndexRequest("test_index");
CreateIndexResponsecreateIndexResponse=restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
System.out.println(createIndexResponse.isAcknowledged());
}

创建CreateIndexRequest对象,设置相关属性,比如切片数,副本数,超时时间等等,然后通过restHighLevelClient创建索引,获得一个结果响应。

//设置分片和副本request.settings(Settings.builder() 
    .put("index.number_of_shards", 3)
    .put("index.number_of_replicas", 2)
);

3.2 获取索引


获取一个索引,主要对象是GetIndexRequest


@TestpublicvoidtestGetIndex() throwsIOException {
//获取索引GetIndexRequestrequest=newGetIndexRequest("test_index");
GetIndexResponsegetIndexResponse=restHighLevelClient.indices().get(request, RequestOptions.DEFAULT);
System.out.println(getIndexResponse);
}

3.3 判断索引是否存在


用的也是GetIndexRequest


@TestpublicvoidtestExistsIndex() throwsIOException {
//获取索引GetIndexRequestrequest=newGetIndexRequest("test_index");
booleanexists=restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}

3.4 删除索引


删除索引的请求对象是DeleteIndexRequest

@TestpublicvoidtestDeleteIndex() throwsIOException {
DeleteIndexRequestrequest=newDeleteIndexRequest("test_index");
AcknowledgedResponsedelete=restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}

对索引的操作可以通过图形化界面来实现,了解增删改即可。


(四)文档API


文档的API分为单个文档处理和批量文档处理,我会介绍单个文档的增删改查和一个批量文档API


网络异常,图片无法展示
|


4.1 创建文档


在用语法创建文档的时候,是这样的:


PUThttp://ip:port/索引名/类型名/文档id{
"name":"javayz",
"address":"hz"}

使用代码是这样的:请求对象为IndexRequest

@TestpublicvoidtestCreateDoc() throwsIOException {
// PUT http://ip:port/索引名/类型名/文档idUseruser=newUser("javayz","hz");
IndexRequestrequest=newIndexRequest("text_index");
request.id("1");
request.source(JSON.toJSONString(user), XContentType.JSON);
IndexResponseindex=restHighLevelClient.index(request, RequestOptions.DEFAULT);
System.out.println(index.status());
}

其实两者十分相似,这也是学技术要先学基础的原因。有了基础一看就懂。


4.2 获取文档


获取文档和判断是否存在这里放在一起写,请求对象都是GetRequest :


@TestpublicvoidtestGetDoc() throwsIOException{
GetRequestrequest=newGetRequest("text_index");
request.id("1");
booleanexists=restHighLevelClient.exists(request, RequestOptions.DEFAULT);
if (exists){
GetResponsedocumentFields=restHighLevelClient.get(request, RequestOptions.DEFAULT);
StringsourceAsString=documentFields.getSourceAsString();
System.out.println(sourceAsString);
    }else{
System.out.println(exists);
    }
}

4.3 更新文档


更新文档的请求对象是UpdateRequest

@TestpublicvoidtestUpdateDoc() throwsIOException{
UpdateRequestrequest=newUpdateRequest("text_index","1");
Useruser=newUser("javayz2","hz");
request.doc(JSON.toJSONString(user),XContentType.JSON);
UpdateResponseresponse=restHighLevelClient.update(request, RequestOptions.DEFAULT);
System.out.println(response.status());
}

4.4 删除文档


删除文档的请求对象是DeleteRequest

@TestpublicvoidtestDeleteDoc() throwsIOException{
DeleteRequestrequest=newDeleteRequest("text_index","1");
DeleteResponsedeleteResponse=restHighLevelClient.delete(request, RequestOptions.DEFAULT);
System.out.println(deleteResponse.status());
}

4.5 批量创建文档


批量创建文档用到了BulkRequest ,具体的使用方式和单体很相似,只不过是把多个请求聚合到一个bulk中一起提交。

@TestpublicvoidtestBulkRequest() throwsIOException{
BulkRequestrequest=newBulkRequest();
request.timeout("10s");
ArrayList<User>list=newArrayList<>();
list.add(newUser("javayz1","hz"));
list.add(newUser("javayz2","hz"));
//往BulkRequest对象中add文档list.stream().forEach(x->{
request.add(newIndexRequest("text_index").source(JSON.toJSONString(x),XContentType.JSON));
    });
BulkResponsebulk=restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
System.out.println(bulk.status());
}

(五)查询API


网络异常,图片无法展示
|


查询操作用最常用的就是match(模糊查询)和term(精确查询),介绍最常用的查询方式:


(六)总结


从上面的用法中可以看出,ES对API的封装使用还算是比较容易,并且官方文档写的也比较清除。下一篇文章我会用上面的这些API实现一个博客系统的搜索功能,我是鱼仔,我们下期再见!

相关实践学习
以电商场景为例搭建AI语义搜索应用
本实验旨在通过阿里云Elasticsearch结合阿里云搜索开发工作台AI模型服务,构建一个高效、精准的语义搜索系统,模拟电商场景,深入理解AI搜索技术原理并掌握其实现过程。
ElasticSearch 最新快速入门教程
本课程由千锋教育提供。全文搜索的需求非常大。而开源的解决办法Elasricsearch(Elastic)就是一个非常好的工具。目前是全文搜索引擎的首选。本系列教程由浅入深讲解了在CentOS7系统下如何搭建ElasticSearch,如何使用Kibana实现各种方式的搜索并详细分析了搜索的原理,最后讲解了在Java应用中如何集成ElasticSearch并实现搜索。 &nbsp;
相关文章
|
自然语言处理 Java 网络架构
elasticsearch学习三:elasticsearch-ik分词器的自定义配置 分词内容
这篇文章是关于如何自定义Elasticsearch的ik分词器配置以满足特定的中文分词需求。
608 0
elasticsearch学习三:elasticsearch-ik分词器的自定义配置 分词内容
|
JSON Java 网络架构
elasticsearch学习四:使用springboot整合 rest 进行搭建elasticsearch服务
这篇文章介绍了如何使用Spring Boot整合REST方式来搭建和操作Elasticsearch服务。
352 4
elasticsearch学习四:使用springboot整合 rest 进行搭建elasticsearch服务
|
自然语言处理 搜索推荐 关系型数据库
elasticsearch学习六:学习 全文搜索引擎 elasticsearch的语法,使用kibana进行模拟测试(持续更新学习)
这篇文章是关于Elasticsearch全文搜索引擎的学习指南,涵盖了基本概念、命令风格、索引操作、分词器使用,以及数据的增加、修改、删除和查询等操作。
296 0
elasticsearch学习六:学习 全文搜索引擎 elasticsearch的语法,使用kibana进行模拟测试(持续更新学习)
|
Web App开发 JavaScript Java
elasticsearch学习五:springboot整合 rest 操作elasticsearch的 实际案例操作,编写搜索的前后端,爬取京东数据到elasticsearch中。
这篇文章是关于如何使用Spring Boot整合Elasticsearch,并通过REST客户端操作Elasticsearch,实现一个简单的搜索前后端,以及如何爬取京东数据到Elasticsearch的案例教程。
809 0
elasticsearch学习五:springboot整合 rest 操作elasticsearch的 实际案例操作,编写搜索的前后端,爬取京东数据到elasticsearch中。
|
自然语言处理 Java Maven
elasticsearch学习二:使用springboot整合TransportClient 进行搭建elasticsearch服务
这篇博客介绍了如何使用Spring Boot整合TransportClient搭建Elasticsearch服务,包括项目创建、Maven依赖、业务代码和测试示例。
592 0
elasticsearch学习二:使用springboot整合TransportClient 进行搭建elasticsearch服务
|
存储 JSON Java
elasticsearch学习一:了解 ES,版本之间的对应。安装elasticsearch,kibana,head插件、elasticsearch-ik分词器。
这篇文章是关于Elasticsearch的学习指南,包括了解Elasticsearch、版本对应、安装运行Elasticsearch和Kibana、安装head插件和elasticsearch-ik分词器的步骤。
1175 0
elasticsearch学习一:了解 ES,版本之间的对应。安装elasticsearch,kibana,head插件、elasticsearch-ik分词器。
|
SQL JSON 自然语言处理
Elasticsearch学习随笔与Scrapy中Elasticsearch的应用
Elasticsearch学习随笔与Scrapy中Elasticsearch的应用
186 0
ElasticSearch6.6.2详解JavaApi
ElasticSearch6.6.2详解JavaApi
69 2
|
存储 缓存 自然语言处理
Elasticsearch框架学习的难点和重点有哪些
Elasticsearch是基于Lucene的开源搜索引擎,广泛应用于全文检索和日志分析。学习重点包括理解节点、集群、索引、分片和副本等基本概念,掌握数据索引、查询DSL、聚合和性能优化。倒排索引和分词器是全文搜索的核心,集群管理和监控对于稳定性至关重要。实践中需根据数据量和查询模式优化分片策略,利用缓存提升搜索性能。学习Elasticsearch要结合实际项目,关注官方文档和社区资源。【5月更文挑战第6天】
168 0
|
人工智能 架构师 开发者
大模型时代,该如何更好的学习 Elasticsearch?
大模型时代,该如何更好的学习 Elasticsearch?

热门文章

最新文章