zoukankan      html  css  js  c++  java
  • spring boot 集成 Elasticsearch 查询

     最终效果

    一、配置 maven 依赖

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

    spring boot 版本 2.2x ,则对应的导入的是 es 6.x ,spring boot 2.3x ,则导入的是 7.x 版本的 es ( es 6.x 版本与 7.x 版本中 type 废除,删除新增改动)

     本次引入的 spring boot 版本 2.2.10

     <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.2.10.RELEASE</version>
            <relativePath/>
     </parent>

    在此之前,需要服务器或者本地搭建es服务,并支持远程访问。只需要在 application.yml 文件中指定es 即可

    server:
      port: 9000
    
    spring:
      elasticsearch:
        rest:
          uris: ["http://81.68.206.246:9200"]
      thymeleaf:
        suffix: .html
        prefix: classpath:/templates/

    二、搜索实现

     public List<Address> searchByKey(@RequestParam("keyword")String keyword) throws Exception{
    
            BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder()
                    .should(QueryBuilders.wildcardQuery("name","*"+keyword+"*"))
                    .should(QueryBuilders.matchQuery("name",keyword))
                    .should(QueryBuilders.wildcardQuery("fullName","*"+keyword+"*"))
                    .should(QueryBuilders.matchQuery("fullName",keyword));
    
            NativeSearchQuery nativeSearchQuery = new NativeSearchQuery(boolQueryBuilder);
            nativeSearchQuery.setPageable(PageRequest.of(0,10));
            SearchHits<Address> addressSearchHits = elasticsearchRestTemplate.search(nativeSearchQuery, Address.class, IndexCoordinates.of("address"));
            List<Address> addresses = new ArrayList<>();
            if(addressSearchHits!=null && addressSearchHits.hasSearchHits()){
                addresses = addressSearchHits.stream()
                        .map(item->item.getContent())
                        .collect(Collectors.toList());
            }
            return addresses;

    github 代码地址:https://github.com/bytecodebuffer/spring/tree/main/springboot-elasticsearch

    下载运行即可使用。但需要提前配置好es,并插入几条虚拟的数据

    三、演示

     截图一

     截图二

     效果和预期的相似,总体功能实现。高亮部分属于比较加单的附加功能,而最终的效果也达到

  • 相关阅读:
    C# 操作txt
    下周学习计划(0815——0822)
    配置允许外界访问的端口
    修改表结构
    C# return和break
    js Ajax的几种操作方法
    WebForm
    Extjs4新特性
    25、手把手教你Extjs5(二十五)Extjs5常用组件--form的基本用法
    24、手把手教你Extjs5(二十四)模块Form的自定义的设计[3]
  • 原文地址:https://www.cnblogs.com/bytecodebuffer/p/13808659.html
Copyright © 2011-2022 走看看