(4)ElasticSearch--springBoot2.0整合ElasticSearch

一、springBoot整合es

1.maven依赖

   org.springframework.boot
    spring-boot-starter-data-elasticsearch

2.配置文件
spring:
  data:
    elasticsearch:
      # 9200作为Http协议,主要用于外部通讯
      # 9300作为Tcp协议,jar之间就是通过tcp协议通讯
      cluster-nodes: 10.1.84.116:9300
      #默认为elasticsearch
      cluster-name: elasticsearch
3.实体类
/**
 * @author 绿眼加菲
 */
@Data
@Document(indexName = "school",type = "person")
public class User {
    @Id
    private String id;
    private String name;
    private int age ;
    private String mail ;
    private String hobby;

}
4.dao
/**
 * @author 绿眼加菲
 */
public interface UserDao extends ElasticsearchRepository<User,String> {
}
5.controller
@RestController
@RequestMapping("/es")
public class UserController {
    @Autowired
    private UserDao userDao;

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/getById")
    public User getById(String id) {
        Optional<User> us = userDao.findById(id);
        return us.get();
    }
    /**
     * 查询全部
     */
    @GetMapping("/queryAll")
    public Map<String,Object> queryAll() {
        Map<String,Object> result = new HashMap<>() ;
        Iterable<User> all = userDao.findAll();
        result.put("result",all);
        return result;
    }

    /**
     * 根据年龄排序
     * @return
     */
    @GetMapping("/orderByAge")
    public Map<String,Object> orderByAge() {
        Map<String,Object> result = new HashMap<>(16) ;
        Sort sort = new Sort(Sort.Direction.ASC,"age") ;
        Iterable<User> all = userDao.findAll(sort);
        result.put("result",all);
        return result;
    }

    /**
     * 全文搜索
     * @return
     */
    @GetMapping("/search")
    public Map<String,Object> search(String keyWord) {
        Map<String,Object> result = new HashMap<>(16) ;
        QueryBuilder builder = QueryBuilders.boolQuery()
                .must(QueryBuilders.matchQuery("hobby", keyWord));
        Iterable<User> search = userDao.search(builder);
        result.put("result",search);
        return result;
    }
}
6.启动类
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
@EnableElasticsearchRepositories(basePackages = "demo.es.dao")
public class EsApplication {
    public static void main(String[] args) {
        SpringApplication.run(EsApplication.class, args);
    }

}

二、项目地址

gitHub:实例代码

你可能感兴趣的:(#,Elasticsearch,springBoot整合es)