Spring-data-elasticsearch|Spring-data-elasticsearch - 集成

官网:https://spring.io/projects/spring-data-elasticsearch
Spring-data-elasticsearch 应用组成 1、配置Maven依赖

org.elasticsearch elasticsearch 6.5.0 org.springframework.data spring-data-elasticsearch 3.1.2.RELEASE

2、Spring Bean配置

3、POJO类
public class Person { @Id @Field(index=false,store=true,type=FieldType.Integer) private Integer id; @Field(index=true,analyzer="ik",store=true,searchAnalyzer="ik",type=FieldType.Text) private String title; @Field(index=true,analyzer="ik",store=true,searchAnalyzer="ik",type=FieldType.Text) private String content; }

4、DAO接口
// 会自动生成具体实现 public interface PersonRepository extends ElasticsearchRepository { List findByTitle(String title); // 模糊查询 @Query("{'bool': {'must' : {'field' : {'title' : '?0'}}}}")// 指定查询json Page findByTitle(String title, Pageable pageable); // 分页查询 }

5、Service层
@Service public class PersonServiceImpl { @Autowired private ElasticsearchTemplate elasticsearchTemplate; @Autowired private PersonRepository personRepository; public void createIndex() { elasticsearchTemplate.createIndex(Person.class); // 创建索引 elasticsearchTemplate.putMapping(Person.class); // 设置映射 }public void save(Person person){ personRepository.save(person); } public void delete(Person article) { personRepository.delete(article); } public Iterable findAll() { return personRepository.findAll(); }public List findByTitle(String title) { return personRepository.findByTitle(title); } public Page findByTitle(String title, Pageable pageable) { return personRepository.findByTitle(title, pageable); } }

【Spring-data-elasticsearch|Spring-data-elasticsearch - 集成】6、使用
@Autowired private PersonServiceImpl personService;

使用场景 1、在RDS中不是索引的字段,但又要被搜索,可以将这个字段和ID存在ES。查询时从ES中找出这条数据的ID,再拿ID去RDS查出完整数据

    推荐阅读