Springboot2.0整合ElasticSearch

环境搭建

1、maven依赖

<parent>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-parentartifactId>
    <version>2.0.0.RELEASEversion>
    <relativePath /> 
parent>
<dependencies>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-data-elasticsearchartifactId>
    dependency>
    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
    dependency>
dependencies>

UserEntity

@Data
//indexName代表索引名称,type代表类型
@Document(indexName = "xwhy",type = "user")
public class UserEntity {
    //代表唯一标识
    @Id
    private String id;
    private String username;
    private Integer age;
    private String sex;
}

UserDao

//CrudRepository   泛型参数第一个:entity类型,第二个:id类型
public interface UserDao extends CrudRepository<UserEntity,String> {

}

controller

@RestController
public class EsController {
    @Autowired
    private UserDao userDao;

    @RequestMapping("/addUser")
    public UserEntity addUser(@RequestBody UserEntity userEntity){
        return userDao.save(userEntity);
    }

    @RequestMapping("/findById")
    public Optional<UserEntity> findById(String id){
        return userDao.findById(id);
    }
}

启动类

@SpringBootApplication
@EnableElasticsearchRepositories("com.xwhy.repository")
public class AppEs {
    public static void main(String[] args) {
        SpringApplication.run(AppEs.class,args);
    }
}

application.yml

spring:
  data:
    elasticsearch:
      ####集群名称
      cluster-name: elasticsearch
      ####地址
      cluster-nodes: 192.168.112.138:9300

这里集群名称默认是elasticsearch,如果要修改,到该目录修改elasticsearch.yml
vi /usr/local/elasticsearch-6.4.3/config/elasticsearch.yml
修改这一行
cluster.name: myes

测试:

添加一个文档
Springboot2.0整合ElasticSearch_第1张图片
Springboot2.0整合ElasticSearch_第2张图片

查询文档:
Springboot2.0整合ElasticSearch_第3张图片

你可能感兴趣的:(ELK)