天天看点

SpringBoot如何整合ElasticSearch? | 带你读《SpringBoot实战教程》之四十

上一篇:ElasticSearch概述及安装 | 带你读《SpringBoot实战教程》之三十九 下一篇:SpringBoot如何整合WebSocket? | 带你读《SpringBoot实战教程》之四十一

本文来自于千锋教育在阿里云开发者社区学习中心上线课程《SpringBoot实战教程》,主讲人杨红艳,

点击查看视频内容

SpringBoot整合ElasticSearch

添加依赖:

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

application.yml全局配置:

spring:
           data:
           elasticsearch:
           cluster-nodes: 192.168.25.129:9300
           local: false
           repositories:
              enabled: true           

针对上一节的案例,我们来做说明。

封装实体类:

新建包:com.qianfeng.pojo

@Document(indexName="userindex",type="user")
public class User implements Serializable{
    
    @Id
    private Long id;
    private String first_name;
    private String last_name;
    private int age;
    private String about;
    private List<String> interests;

    //get、set方法省略
    @Override
    public String toString() {
        return "User[id=" + id +",first_name=" + first_name + ", last_name=" + last_name + ", age=" + age + ", about =" + about + ", interests=" + interests + "]";
    }
}           

实现搜索:

com.qianfeng.controller:

@Controller
public class TestController {

    //SpringBoot在启动时自动配置了ElasticsearchTemplate
    @Autowired
    private ElasticsearchTemplate elasticSearchTemplate;


    @RequestMapping("/search")
    @ResponseBody
    public String findDoc() {
        //构造搜索条件
        QueryBuilder builder = QueryBuilders.existsQuery("first_name");

        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder);
                                                      .build();
        List<User> users=elasticSearchTemplate.queryForList(searchQuery, User.class);

        for(User user:users) {
            System.out.println(user);
        }
        return "success";
    }
}           

在启动类中添加所有需要扫描的包:

@SpringBootApplication(scanBasePackages="com.qianfeng")           

执行结果:

SpringBoot如何整合ElasticSearch? | 带你读《SpringBoot实战教程》之四十
SpringBoot如何整合ElasticSearch? | 带你读《SpringBoot实战教程》之四十

配套视频