0
  • 聊天消息
  • 系统消息
  • 评论与回复
登录后你可以
  • 下载海量资料
  • 学习在线课程
  • 观看技术视频
  • 写文章/发帖/加入社区
创作中心

完善资料让更多小伙伴认识你,还能领取20积分哦,立即完善>

3天内不再提示

SpringBoot+ElasticSearch实现模糊查询功能

jf_ro2CN3Fa 来源:CSDN 2022-12-30 14:00 次阅读

一、导入elasticsearch依赖

在pom.xml里加入如下依赖


org.springframework.boot
spring-boot-starter-data-elasticsearch

非常重要:检查依赖版本是否与你当前所用的版本是否一致,如果不一致,会连接失败!

31132bd4-77af-11ed-8abf-dac502259ad0.png

基于 Spring Boot + MyBatis Plus + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

项目地址:https://github.com/YunaiV/ruoyi-vue-pro

视频教程:https://doc.iocoder.cn/video/

二、创建高级客户端

importorg.apache.http.HttpHost;
importorg.elasticsearch.client.RestClient;
importorg.elasticsearch.client.RestHighLevelClient;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;

@Configuration
publicclassElasticSearchClientConfig{
@Bean
publicRestHighLevelClientrestHighLevelClient(){
RestHighLevelClientclient=newRestHighLevelClient(
RestClient.builder(
newHttpHost("服务器IP",9200,"http")));
returnclient;
}
}

基于 Spring Cloud Alibaba + Gateway + Nacos + RocketMQ + Vue & Element 实现的后台管理系统 + 用户小程序,支持 RBAC 动态权限、多租户、数据权限、工作流、三方登录、支付、短信、商城等功能

项目地址:https://github.com/YunaiV/yudao-cloud

视频教程:https://doc.iocoder.cn/video/

三、基本用法

1.创建、判断存在、删除索引

importorg.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
importorg.elasticsearch.action.support.master.AcknowledgedResponse;
importorg.elasticsearch.client.RequestOptions;
importorg.elasticsearch.client.RestHighLevelClient;
importorg.elasticsearch.client.indices.CreateIndexRequest;
importorg.elasticsearch.client.indices.CreateIndexResponse;
importorg.elasticsearch.client.indices.GetIndexRequest;
importorg.junit.jupiter.api.Test;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.boot.test.context.SpringBootTest;

importjava.io.IOException;

@SpringBootTest
classElasticsearchApplicationTests{

@Autowired
privateRestHighLevelClientrestHighLevelClient;

@Test
voidtestCreateIndex()throwsIOException{
//1.创建索引请求
CreateIndexRequestrequest=newCreateIndexRequest("ljx666");
//2.客户端执行请求IndicesClient,执行create方法创建索引,请求后获得响应
CreateIndexResponseresponse=
restHighLevelClient.indices().create(request,RequestOptions.DEFAULT);
System.out.println(response);
}

@Test
voidtestExistIndex()throwsIOException{
//1.查询索引请求
GetIndexRequestrequest=newGetIndexRequest("ljx666");
//2.执行exists方法判断是否存在
booleanexists=restHighLevelClient.indices().exists(request,RequestOptions.DEFAULT);
System.out.println(exists);
}

@Test
voidtestDeleteIndex()throwsIOException{
//1.删除索引请求
DeleteIndexRequestrequest=newDeleteIndexRequest("ljx666");
//执行delete方法删除指定索引
AcknowledgedResponsedelete=restHighLevelClient.indices().delete(request,RequestOptions.DEFAULT);
System.out.println(delete.isAcknowledged());
}

}

2.对文档的CRUD

创建文档:

注意:如果添加时不指定文档ID,他就会随机生成一个ID,ID唯一。

创建文档时若该ID已存在,发送创建文档请求后会更新文档中的数据。

@Test
voidtestAddUser()throwsIOException{
//1.创建对象
Useruser=newUser("Go",21,newString[]{"内卷","吃饭"});
//2.创建请求
IndexRequestrequest=newIndexRequest("ljx666");
//3.设置规则PUT/ljx666/_doc/1
//设置文档id=6,设置超时=1s等,不设置会使用默认的
//同时支持链式编程如request.id("6").timeout("1s");
request.id("6");
request.timeout("1s");

//4.将数据放入请求,要将对象转化为json格式
//XContentType.JSON,告诉它传的数据是JSON类型
request.source(JSONValue.toJSONString(user),XContentType.JSON);

//5.客户端发送请求,获取响应结果
IndexResponseindexResponse=restHighLevelClient.index(request,RequestOptions.DEFAULT);
System.out.println(indexResponse.toString());
System.out.println(indexResponse.status());
}

获取文档中的数据:

@Test
voidtestGetUser()throwsIOException{
//1.创建请求,指定索引、文档id
GetRequestrequest=newGetRequest("ljx666","1");
GetResponsegetResponse=restHighLevelClient.get(request,RequestOptions.DEFAULT);

System.out.println(getResponse);//获取响应结果
//getResponse.getSource()返回的是Map集合
System.out.println(getResponse.getSourceAsString());//获取响应结果source中内容,转化为字符串

}

更新文档数据:

注意:需要将User对象中的属性全部指定值,不然会被设置为空,如User只设置了名称,那么只有名称会被修改成功,其他会被修改为null。

@Test
voidtestUpdateUser()throwsIOException{
//1.创建请求,指定索引、文档id
UpdateRequestrequest=newUpdateRequest("ljx666","6");

Useruser=newUser("GoGo",21,newString[]{"内卷","吃饭"});
//将创建的对象放入文档中
request.doc(JSONValue.toJSONString(user),XContentType.JSON);

UpdateResponseupdateResponse=restHighLevelClient.update(request,RequestOptions.DEFAULT);
System.out.println(updateResponse.status());//更新成功返回OK
}

删除文档:

@Test
voidtestDeleteUser()throwsIOException{
//创建删除请求,指定要删除的索引与文档ID
DeleteRequestrequest=newDeleteRequest("ljx666","6");

DeleteResponseupdateResponse=restHighLevelClient.delete(request,RequestOptions.DEFAULT);
System.out.println(updateResponse.status());//删除成功返回OK,没有找到返回NOT_FOUND
}

3.批量CRUD数据

这里只列出了批量插入数据,其他与此类似

注意:hasFailures()方法是返回是否失败,即它的值为false时说明上传成功

@Test
voidtestBulkAddUser()throwsIOException{
BulkRequestbulkRequest=newBulkRequest();
//设置超时
bulkRequest.timeout("10s");

ArrayListlist=newArrayList<>();
list.add(newUser("Java",25,newString[]{"内卷"}));
list.add(newUser("Go",18,newString[]{"内卷"}));
list.add(newUser("C",30,newString[]{"内卷"}));
list.add(newUser("C++",26,newString[]{"内卷"}));
list.add(newUser("Python",20,newString[]{"内卷"}));

intid=1;
//批量处理请求
for(Useru:list){
//不设置id会生成随机id
bulkRequest.add(newIndexRequest("ljx666")
.id(""+(id++))
.source(JSONValue.toJSONString(u),XContentType.JSON));
}

BulkResponsebulkResponse=restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);
System.out.println(bulkResponse.hasFailures());//是否执行失败,false为执行成功
}

4.查询所有、模糊查询、分页查询、排序、高亮显示

@Test
voidtestSearch()throwsIOException{
SearchRequestsearchRequest=newSearchRequest("ljx666");//里面可以放多个索引
SearchSourceBuildersourceBuilder=newSearchSourceBuilder();//构造搜索条件

//此处可以使用QueryBuilders工具类中的方法
//1.查询所有
sourceBuilder.query(QueryBuilders.matchAllQuery());
//2.查询name中含有Java的
sourceBuilder.query(QueryBuilders.multiMatchQuery("java","name"));
//3.分页查询
sourceBuilder.from(0).size(5);

//4.按照score正序排列
//sourceBuilder.sort(SortBuilders.scoreSort().order(SortOrder.ASC));
//5.按照id倒序排列(score会失效返回NaN)
//sourceBuilder.sort(SortBuilders.fieldSort("_id").order(SortOrder.DESC));

//6.给指定字段加上指定高亮样式
HighlightBuilderhighlightBuilder=newHighlightBuilder();
highlightBuilder.field("name").preTags("").postTags("");
sourceBuilder.highlighter(highlightBuilder);

searchRequest.source(sourceBuilder);
SearchResponsesearchResponse=restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);

//获取总条数
System.out.println(searchResponse.getHits().getTotalHits().value);
//输出结果数据(如果不设置返回条数,大于10条默认只返回10条)
SearchHit[]hits=searchResponse.getHits().getHits();
for(SearchHithit:hits){
System.out.println("分数:"+hit.getScore());
Mapsource=hit.getSourceAsMap();
System.out.println("index->"+hit.getIndex());
System.out.println("id->"+hit.getId());
for(Map.Entrys:source.entrySet()){
System.out.println(s.getKey()+"--"+s.getValue());
}
}
}

四、总结

1.大致流程

创建对应的请求 --> 设置请求(添加规则,添加数据等) --> 执行对应的方法(传入请求,默认请求选项)–> 接收响应结果(执行方法返回值)–> 输出响应结果中需要的数据(source,status等)

2.注意事项

如果不指定id,会自动生成一个随机id

正常情况下,不应该这样使用new IndexRequest(“ljx777”),如果索引发生改变了,那么代码都需要修改,可以定义一个枚举类或者一个专门存放常量的类,将变量用final static等进行修饰,并指定索引值。其他地方引用该常量即可,需要修改也只需修改该类即可。

elasticsearch相关的东西,版本都必须一致,不然会报错

elasticsearch很消耗内存,建议在内存较大的服务器上运行elasticsearch,否则会因为内存不足导致elasticsearch自动killed。








审核编辑:刘清

声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。 举报投诉
  • RBAC
    +关注

    关注

    0

    文章

    43

    浏览量

    9891
  • SpringBoot
    +关注

    关注

    0

    文章

    172

    浏览量

    106

原文标题:SpringBoot+ElasticSearch 实现模糊查询,批量CRUD,排序,分页,高亮

文章出处:【微信号:芋道源码,微信公众号:芋道源码】欢迎添加关注!文章转载请注明出处。

收藏 人收藏

    评论

    相关推荐

    SpringBoot整合ElasticSearch

    ElasticSearch是个开源分布式搜索引擎,提供搜集、分析、存储数据三大功能。它的特点有:分布式,零配置,自动发现,索引自动分片,索引副本机制,restful风格接口,多数据源,自动搜索负载
    的头像 发表于 03-09 14:56 446次阅读
    <b class='flag-5'>SpringBoot</b>整合<b class='flag-5'>ElasticSearch</b>

    ElasticSearch是最常用的组合查询:布尔查询

    ElasticSearch查询 第五篇:布尔查询
    发表于 04-22 13:02

    ElasticSearch引擎的文档更新

    ElasticSearch查询 第二篇:文档更新
    发表于 04-24 07:55

    ElasticSearch的词条查询

    ElasticSearch查询 第三篇:词条查询
    发表于 04-30 17:03

    ElasticSearch查询的匹配查询

    ElasticSearch查询 第四篇:匹配查询(Match)
    发表于 05-15 09:59

    基于SpringBoot mybatis方式的增删改查实现

    SpringBoot mybatis方式实现增删改查
    发表于 06-18 16:56

    分析一下MySQL数据库与ElasticSearch的实际应用

    1、MySQL与ElasticSearch的组合使用假设有一业务场景:现有一电子商务系统需要具备让用户准确的找到自己想要商品的功能,因此怎么也绕不开的就是商品信息的检索了可以来分析一下,对于一个电商
    发表于 06-15 17:15

    Delphi教程之标准/模糊查询

    Delphi教程之标准/模糊查询,学习Delphi的必备资料。
    发表于 03-31 11:29 2次下载

    为什么ElasticSearch复杂条件查询比MySQL好?

    的方式因为只能通过一个索引进行过滤,所以需要进行大量的 I/O 操作来读取行数据,并消耗 CPU 进行内存过滤,导致查询性能的下降。 而 ElasticSearch 因其特性,十分适合进行复杂条件查询,是业界主流的复杂条件
    的头像 发表于 04-09 11:16 2519次阅读
    为什么<b class='flag-5'>ElasticSearch</b>复杂条件<b class='flag-5'>查询</b>比MySQL好?

    ElasticSearch是什么?应用场景是什么?

    ElasticSearch是什么 ElasticSearch功能 ElasticSearch的应用场景 ElasticSearc
    的头像 发表于 10-09 18:38 1939次阅读

    SpringBoot实现多线程

    SpringBoot实现多线程
    的头像 发表于 01-12 16:59 1292次阅读
    <b class='flag-5'>SpringBoot</b><b class='flag-5'>实现</b>多线程

    SpringBoot模板分类树查询功能介绍

    背景 第1次优化 第2次优化 第3次优化 第4次优化 第5次优化 分类树查询功能,在各个业务系统中可以说随处可见,特别是在电商系统中。   但就是这样一个简单的分类树查询功能,我们却优
    的头像 发表于 05-22 11:39 496次阅读
    <b class='flag-5'>SpringBoot</b>模板分类树<b class='flag-5'>查询</b><b class='flag-5'>功能</b>介绍

    加密后的敏感字段还能进行模糊查询吗?该如何实现

    有一个问题不知道大家想过没?敏感字段数据是加密存储在数据库的表中,如果需要对这些敏感字段进行模模糊查询,还用原来的通过sql的where从句的like来模糊查询的方式肯定是不行的
    的头像 发表于 06-05 16:43 452次阅读
    加密后的敏感字段还能进行<b class='flag-5'>模糊</b><b class='flag-5'>查询</b>吗?该如何<b class='flag-5'>实现</b>?

    SpringBoot 连接ElasticSearch的使用方式

    SpringBoot,今天我们就以 SpringBoot 整合 ElasticSearch 为例,给大家详细的介绍 ElasticSearch 的使用!
    的头像 发表于 10-09 10:35 426次阅读

    Redis的分页+多条件模糊查询组合实现方案

    Redis是key-value类型的内存数据库,通过key直接取数据虽然很方便,但是并未提供像mysql那样方便的sql条件查询支持。因此我们需要借助Redis提供的结构和功能去自己实现模糊
    的头像 发表于 11-20 14:26 341次阅读
    Redis的分页+多条件<b class='flag-5'>模糊</b><b class='flag-5'>查询</b>组合<b class='flag-5'>实现</b>方案