Spring Boot 集成 ElasticSearch:实现模糊查询、批量 CRUD、排序、分页和高亮功能

这篇具有很好参考价值的文章主要介绍了Spring Boot 集成 ElasticSearch:实现模糊查询、批量 CRUD、排序、分页和高亮功能。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

文章来源:https://blog.csdn.net/qq_52355487/article/details/123805713
Spring Boot 集成 ElasticSearch:实现模糊查询、批量 CRUD、排序、分页和高亮功能,Springboot,spring boot,elasticsearch,jenkins

一、导入elasticsearch依赖

在pom.xml里加入如下依赖

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

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

Spring Boot 集成 ElasticSearch:实现模糊查询、批量 CRUD、排序、分页和高亮功能,Springboot,spring boot,elasticsearch,jenkins

二、创建高级客户端

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;
    }
}

三、基本用法

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.注意事项文章来源地址https://www.toymoban.com/news/detail-765242.html

  • 如果不指定id,会自动生成一个随机id
  • 正常情况下,不应该这样使用new IndexRequest(“ljx777”),如果索引发生改变了,那么代码都需要修改,可以定义一个枚举类或者一个专门存放常量的类,将变量用final static等进行修饰,并指定索引值。其他地方引用该常量即可,需要修改也只需修改该类即可。
  • elasticsearch相关的东西,版本都必须一致,不然会报错
  • elasticsearch很消耗内存,建议在内存较大的服务器上运行elasticsearch,否则会因为内存不足导致elasticsearch自动killed

到了这里,关于Spring Boot 集成 ElasticSearch:实现模糊查询、批量 CRUD、排序、分页和高亮功能的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Spring Boot Elasticsearch7.6.2实现创建索引、删除索引、判断索引是否存在、获取/添加/删除/更新索引别名、单条/批量插入、单条/批量更新、删除数据、递归统计ES聚合的数据

    注意:我的版本是elasticsearch7.6.2、spring-boot-starter-data-elasticsearch-2.5.6 引入依赖 有时候你可能需要查询大批量的数据,建议加上下面配置文件

    2024年02月13日
    浏览(51)
  • Spring Boot 集成 ElasticSearch

    首先创建一个项目,在项目中加入 ES 相关依赖,具体依赖如下所示: 在配置文件 application.properties 中配置 ES 的相关参数,具体内容如下: 其中指定了 ES 的 host 和端口以及超时时间的设置,另外我们的 ES 没有添加任何的安全认证,因此 username 和 password 就没有设置。 然后在

    2024年02月03日
    浏览(40)
  • Spring Boot集成Elasticsearch实战

    最近项目中要使用Elasticsearch所以就去简单的学习了一下怎么使用,具体的一些在高级的功能暂时展示不了,能力目前有点限,不过一些基本的需求还是可以满足的。所以就写了一篇整理一下也希望能够指出不足之处 docker部署 正常部署 首先根据spring提供的findAll方法获取所有

    2024年02月09日
    浏览(31)
  • Spring Boot 集成 Elasticsearch 实战

    @Configuration public class ElasticsearchConfiguration { @Value(“${elasticsearch.host}”) private String host; @Value(“${elasticsearch.port}”) private int port; @Value(“${elasticsearch.connTimeout}”) private int connTimeout; @Value(“${elasticsearch.socketTimeout}”) private int socketTimeout; @Value(“${elasticsearch.connectionRequestTimeout}”

    2024年04月10日
    浏览(36)
  • Spring boot简单集成Elasticsearch

    本文主要介绍Spring boot如何简单集成Elasticsearch,关于es,可以理解为一个数据库,往es中插入数据,然后使用es进行检索。 环境准备 安装es 和kibana :参考 安装ik分词器:参考 相关配置 pom.xml文件中引入es: yml文件配置es: ES查询 往es插数据 需要让mapper层继承ElasticsearchReposito

    2024年02月22日
    浏览(34)
  • Java实战:SpringBoot+ElasticSearch 实现模糊查询

    本文将详细介绍如何使用SpringBoot整合ElasticSearch,实现模糊查询、批量CRUD、排序、分页和高亮功能。我们将深入探讨ElasticSearch的相关概念和技术细节,以及如何使用SpringData Elasticsearch库简化开发过程。 ElasticSearch是一个基于Lucene构建的开源搜索引擎,它提供了一个分布式、多

    2024年04月25日
    浏览(25)
  • ElasticSearch入门:使用ES来实现模糊查询功能

    本文针对在工作中遇到的需求:通过es来实现 模糊查询 来进行总结;模糊查询的具体需求是:查询基金/A股/港股等金融数据,要求可以根据 字段 , 拼音首字母 , 部分拼音全称 进行联想查询;需要注意的是,金融数据名称中可能不止包含汉字,还有英文,数字,特殊字符等

    2023年04月09日
    浏览(35)
  • Elasticsearch实现对同一字段既能精准查询也能模糊查询

     使用@MultiField注解给字段取别名并设置为keyword类型 dao层如下 实体类如下 模糊查询测试如下: 可以看到模糊查询content中一共有3条数据有我这个分词  精准查询如下:  可以看到精准查询就只有一条结果,符合精准查询。 注意:该方法需要版本支持,具体版本未知,但是在

    2024年02月02日
    浏览(35)
  • spring boot集成Elasticsearch-SpringBoot(25)

      搜索引擎(search engine )通常意义上是指:根据特定策略,运用特定的爬虫程序从互联网上搜集信息,然后对信息进行处理后,为用户提供检索服务,将检索到的相关信息展示给用户的系统。   而我们讲解的是捜索的索引和检索,不涉及爬虫程序的内容爬取。大部分公司

    2023年04月09日
    浏览(94)
  • spring boot集成mybatis-plus——Mybatis Plus 批量 Insert_新增数据(图文讲解)

     更新时间 2023-01-10 16:02:58 大家好,我是小哈。 本小节中,我们将学习如何通过 Mybatis Plus 实现 MySQL 批量插入数据。 先抛出一个问题:假设老板给你下了个任务,向数据库中添加 100 万条数据,并且不能耗时太久! 通常来说,我们向 MySQL 中新增一条记录,SQL 语句类似如下:

    2024年02月04日
    浏览(35)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包