springboot 整合elasticsearch

springboot 整合elasticsearch_第1张图片
  • 引入依赖
       
        
            org.springframework.boot
            spring-boot-starter-data-elasticsearch
        
  • 配置yml
spring:
  data:
    elasticsearch:
      cluster-nodes: ip:9300
      cluster-name: elasticsearch
      ## 默认cluster-name的是elasticsearch
  • 扫包
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;

@SpringBootApplication
@EnableElasticsearchRepositories("com.zhanhao.springbootelasticsearch.dao")
public class SpringbootElasticsearchApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootElasticsearchApplication.class, args);
    }
}
  • 创建实体
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

//添加索引名及文档类型
@Document( indexName = "myindex", type = "user")
public class UserEntity {

    @Id
    private String id;
    private String name;
    private String sex;
    private Integer age;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}
  • 创建dao
import com.zhanhao.springbootelasticsearch.entity.UserEntity;
import org.springframework.data.repository.CrudRepository;

//对应的实体和id类型
public interface UserDao extends ElasticsearchRepository {
}
  • 定义接口
import com.zhanhao.springbootelasticsearch.dao.UserDao;
import com.zhanhao.springbootelasticsearch.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;

@RestController
public class TestController {

    @Autowired
    private UserDao userDao

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

    //查询文档
    @RequestMapping("/findById")
    public Optional findById(@RequestParam("id") String id){
        return userDao.findById(id);
    }
}

你可能感兴趣的:(springboot 整合elasticsearch)