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

三、演示

 截图一

 

 截图二

 

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

posted @ 2020-10-13 14:30  byebai95  阅读(377)  评论(0编辑  收藏  举报