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,并插入几条虚拟的数据

    三、演示

     截图一

     截图二

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

  • 相关阅读:
    洛谷P5173 传球(暴力)
    uoj#402. 【CTSC2018】混合果汁(主席树+二分)
    uoj#401. 【CTSC2018】青蕈领主(分治FFT)
    uoj#400. 【CTSC2018】暴力写挂(边分治)
    uoj#399. 【CTSC2018】假面(概率期望)
    P4769 [NOI2018]冒泡排序(dp)
    洛谷P3688/uoj#291. [ZJOI2017]树状数组
    uoj#290. 【ZJOI2017】仙人掌(数数+仙人掌+树形dp)
    Git环境部署
    mysql修改密码
  • 原文地址:https://www.cnblogs.com/bytecodebuffer/p/13808659.html
Copyright © 2011-2022 走看看