Spring Data访问Elasticsearch----查询方法,程序员必学
    		       		warning:
    		            这篇文章距离上次修改已过452天,其中的内容可能已经有所变动。
    		        
        		                
                在Spring Data中,我们可以通过定义接口继承ElasticsearchRepository来实现对Elasticsearch的操作。Spring Data会自动生成接口的实现。
以下是一些常用的查询方法示例:
- 查询所有数据
 
Iterable<T> findAll();- 根据ID查询
 
T findById(ID id);- 根据ID查询,如果未找到则返回Optional
 
Optional<T> findById(Id id);- 查询所有数据,返回Page对象
 
Page<T> findAll(Pageable pageable);- 根据查询条件查询
 
List<T> findAll(Example<T> example);- 根据查询条件查询,返回Page对象
 
Page<T> findAll(Example<T> example, Pageable pageable);- 根据查询条件查询,返回Slice对象
 
Slice<T> findAll(Example<T> example, Pageable pageable);- 根据查询条件查询,返回List对象
 
List<T> findAll(Example<T> example);- 根据查询条件查询,返回List对象,并支持排序
 
List<T> findAll(Example<T> example, Sort sort);- 根据查询条件查询,返回是否存在
 
boolean existsById(ID id);- 根据查询条件查询,返回数量
 
long count();- 根据查询条件查询,返回数量
 
long count(Example<T> example);注意:以上的查询方法都是Spring Data Elasticsearch为我们自动生成的实现,我们只需要在自定义的ElasticsearchRepository接口中定义好方法即可使用。
例如,我们定义一个ElasticsearchRepository接口:
public interface UserRepository extends ElasticsearchRepository<User, Long> {
    List<User> findByName(String name);
}在上述接口中,我们定义了一个findByName的方法,Spring Data Elasticsearch会自动根据方法名生成对应的查询条件并查询数据。
在使用时,我们只需要将此接口注入到我们的Service或者Controller中,然后直接调用findByName方法即可获取到对应的数据。
@Autowired
private UserRepository userRepository;
 
public List<User> getUserByName(String name){
    return userRepository.findByName(name);
}以上就是Spring Data Elasticsearch中的查询方法,程序员可以根据自己的需求定义相应的查询方法,Spring Data Elasticsearch会自动帮我们生成相应的查询实现。
评论已关闭