SpringBoot+ElasticSearch 实现模糊查询,批量CRUD,排序,分页,高亮

简介: SpringBoot+ElasticSearch 实现模糊查询,批量CRUD,排序,分页,高亮


一、导入elasticsearch依赖

在pom.xml里加入如下依赖

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

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

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

二、创建高级客户端

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ElasticSearchClientConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient(){
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("服务器IP", 9200, "http")));
        return client;
    }
}

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

三、基本用法

1.创建、判断存在、删除索引
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
@SpringBootTest
class ElasticsearchApplicationTests {
 @Autowired
 private RestHighLevelClient restHighLevelClient;
 @Test
 void testCreateIndex() throws IOException {
  //1.创建索引请求
  CreateIndexRequest request = new CreateIndexRequest("ljx666");
  //2.客户端执行请求IndicesClient,执行create方法创建索引,请求后获得响应
  CreateIndexResponse response=
    restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
  System.out.println(response);
 }
 @Test
 void testExistIndex() throws IOException {
        //1.查询索引请求
  GetIndexRequest request=new GetIndexRequest("ljx666");
        //2.执行exists方法判断是否存在
  boolean exists=restHighLevelClient.indices().exists(request,RequestOptions.DEFAULT);
  System.out.println(exists);
 }
 @Test
 void testDeleteIndex() throws IOException {
        //1.删除索引请求
  DeleteIndexRequest request=new DeleteIndexRequest("ljx666");
        //执行delete方法删除指定索引
  AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
  System.out.println(delete.isAcknowledged());
 }
}
2.对文档的CRUD

创建文档:

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

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

@Test
void testAddUser() throws IOException {
 //1.创建对象
 User user=new User("Go",21,new String[]{"内卷","吃饭"});
 //2.创建请求
 IndexRequest request=new IndexRequest("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.客户端发送请求,获取响应结果
 IndexResponse indexResponse=restHighLevelClient.index(request,RequestOptions.DEFAULT);
 System.out.println(indexResponse.toString());
 System.out.println(indexResponse.status());
}

获取文档中的数据:

@Test
void testGetUser() throws IOException {
 //1.创建请求,指定索引、文档id
 GetRequest request=new GetRequest("ljx666","1");
 GetResponse getResponse=restHighLevelClient.get(request,RequestOptions.DEFAULT);
 System.out.println(getResponse);//获取响应结果
 //getResponse.getSource() 返回的是Map集合
 System.out.println(getResponse.getSourceAsString());//获取响应结果source中内容,转化为字符串
}

更新文档数据:

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

@Test
void testUpdateUser() throws IOException {
 //1.创建请求,指定索引、文档id
 UpdateRequest request=new UpdateRequest("ljx666","6");
 User user =new User("GoGo",21,new String[]{"内卷","吃饭"});
 //将创建的对象放入文档中
 request.doc(JSONValue.toJSONString(user),XContentType.JSON);
 UpdateResponse updateResponse=restHighLevelClient.update(request,RequestOptions.DEFAULT);
 System.out.println(updateResponse.status());//更新成功返回OK
}

删除文档:

@Test
void testDeleteUser() throws IOException {
 //创建删除请求,指定要删除的索引与文档ID
 DeleteRequest request=new DeleteRequest("ljx666","6");
 DeleteResponse updateResponse=restHighLevelClient.delete(request,RequestOptions.DEFAULT);
 System.out.println(updateResponse.status());//删除成功返回OK,没有找到返回NOT_FOUND
}
3.批量CRUD数据

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

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

@Test
void testBulkAddUser() throws IOException {
 BulkRequest bulkRequest=new BulkRequest();
 //设置超时
 bulkRequest.timeout("10s");
 ArrayList<User> list=new ArrayList<>();
 list.add(new User("Java",25,new String[]{"内卷"}));
 list.add(new User("Go",18,new String[]{"内卷"}));
 list.add(new User("C",30,new String[]{"内卷"}));
 list.add(new User("C++",26,new String[]{"内卷"}));
 list.add(new User("Python",20,new String[]{"内卷"}));
 int id=1;
 //批量处理请求
 for (User u :list){
  //不设置id会生成随机id
  bulkRequest.add(new IndexRequest("ljx666")
    .id(""+(id++))
    .source(JSONValue.toJSONString(u),XContentType.JSON));
 }
 BulkResponse bulkResponse=restHighLevelClient.bulk(bulkRequest,RequestOptions.DEFAULT);
 System.out.println(bulkResponse.hasFailures());//是否执行失败,false为执行成功
}
4.查询所有、模糊查询、分页查询、排序、高亮显示
@Test
void testSearch() throws IOException {
 SearchRequest searchRequest=new SearchRequest("ljx666");//里面可以放多个索引
 SearchSourceBuilder sourceBuilder=new SearchSourceBuilder();//构造搜索条件
 //此处可以使用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.给指定字段加上指定高亮样式
 HighlightBuilder highlightBuilder=new HighlightBuilder();
 highlightBuilder.field("name").preTags("<span style='color:red;'>").postTags("</span>");
 sourceBuilder.highlighter(highlightBuilder);
 searchRequest.source(sourceBuilder);
 SearchResponse searchResponse=restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
 //获取总条数
 System.out.println(searchResponse.getHits().getTotalHits().value);
 //输出结果数据(如果不设置返回条数,大于10条默认只返回10条)
 SearchHit[] hits=searchResponse.getHits().getHits();
 for(SearchHit hit :hits){
  System.out.println("分数:"+hit.getScore());
  Map<String,Object> source=hit.getSourceAsMap();
  System.out.println("index->"+hit.getIndex());
  System.out.println("id->"+hit.getId());
  for(Map.Entry<String,Object> s: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


相关实践学习
以电商场景为例搭建AI语义搜索应用
本实验旨在通过阿里云Elasticsearch结合阿里云搜索开发工作台AI模型服务,构建一个高效、精准的语义搜索系统,模拟电商场景,深入理解AI搜索技术原理并掌握其实现过程。
ElasticSearch 最新快速入门教程
本课程由千锋教育提供。全文搜索的需求非常大。而开源的解决办法Elasricsearch(Elastic)就是一个非常好的工具。目前是全文搜索引擎的首选。本系列教程由浅入深讲解了在CentOS7系统下如何搭建ElasticSearch,如何使用Kibana实现各种方式的搜索并详细分析了搜索的原理,最后讲解了在Java应用中如何集成ElasticSearch并实现搜索。 &nbsp;
相关文章
存储 JSON Java
527 0
|
8月前
|
SQL 前端开发 Java
深入理解 Spring Boot 项目中的分页与排序功能
本文深入讲解了在Spring Boot项目中实现分页与排序功能的完整流程。通过实际案例,从Service层接口设计到Mapper层SQL动态生成,再到Controller层参数传递及前端页面交互,逐一剖析每个环节的核心逻辑与实现细节。重点包括分页计算、排序参数校验、动态SQL处理以及前后端联动,确保数据展示高效且安全。适合希望掌握分页排序实现原理的开发者参考学习。
535 4
|
9月前
|
人工智能 自然语言处理 Java
对话即服务:Spring Boot整合MCP让你的CRUD系统秒变AI助手
本文介绍了如何通过Model Context Protocol (MCP) 协议将传统Spring Boot服务改造为支持AI交互的智能系统。MCP作为“万能适配器”,让AI以统一方式与多种服务和数据源交互,降低开发复杂度。文章以图书管理服务为例,详细说明了引入依赖、配置MCP服务器、改造服务方法(注解方式或函数Bean方式)及接口测试的全流程。最终实现用户通过自然语言查询数据库的功能,展示了MCP在简化AI集成、提升系统易用性方面的价值。未来,“对话即服务”有望成为主流开发范式。
6481 7
|
前端开发 Java Maven
深入解析:如何用 Spring Boot 实现分页和排序
深入解析:如何用 Spring Boot 实现分页和排序
1008 2
|
JSON Java API
springboot集成ElasticSearch使用completion实现补全功能
springboot集成ElasticSearch使用completion实现补全功能
225 1
|
Web App开发 JavaScript Java
elasticsearch学习五:springboot整合 rest 操作elasticsearch的 实际案例操作,编写搜索的前后端,爬取京东数据到elasticsearch中。
这篇文章是关于如何使用Spring Boot整合Elasticsearch,并通过REST客户端操作Elasticsearch,实现一个简单的搜索前后端,以及如何爬取京东数据到Elasticsearch的案例教程。
870 0
elasticsearch学习五:springboot整合 rest 操作elasticsearch的 实际案例操作,编写搜索的前后端,爬取京东数据到elasticsearch中。
|
JSON Java 网络架构
elasticsearch学习四:使用springboot整合 rest 进行搭建elasticsearch服务
这篇文章介绍了如何使用Spring Boot整合REST方式来搭建和操作Elasticsearch服务。
391 4
elasticsearch学习四:使用springboot整合 rest 进行搭建elasticsearch服务
|
自然语言处理 Java Maven
elasticsearch学习二:使用springboot整合TransportClient 进行搭建elasticsearch服务
这篇博客介绍了如何使用Spring Boot整合TransportClient搭建Elasticsearch服务,包括项目创建、Maven依赖、业务代码和测试示例。
657 0
elasticsearch学习二:使用springboot整合TransportClient 进行搭建elasticsearch服务
|
SQL JSON Java
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
这篇文章介绍了如何在Spring Boot项目中整合MyBatis和PageHelper进行分页操作,并且集成Swagger2来生成API文档,同时定义了统一的数据返回格式和请求模块。
561 1
mybatis使用三:springboot整合mybatis,使用PageHelper 进行分页操作,并整合swagger2。使用正规的开发模式:定义统一的数据返回格式和请求模块
|
缓存 关系型数据库 API
京东面试题:ElasticSearch深度分页解决方案!
京东面试题:ElasticSearch深度分页解决方案!
263 0

热门文章

最新文章