溫馨提示×

springboot整合es排序怎么實(shí)現(xiàn)

小億
168
2023-11-02 11:28:52
欄目: 編程語言

在Spring Boot中整合Elasticsearch實(shí)現(xiàn)排序,可以通過以下步驟實(shí)現(xiàn):

  1. 首先,在pom.xml文件中添加Elasticsearch依賴項(xiàng):
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
  1. 創(chuàng)建一個Elasticsearch配置類,用于配置Elasticsearch連接信息:
@Configuration
@EnableElasticsearchRepositories(basePackages = "com.example.repository")
public class ElasticsearchConfig {

    @Value("${elasticsearch.host}")
    private String host;

    @Value("${elasticsearch.port}")
    private int port;

    @Bean
    public RestHighLevelClient elasticsearchClient() {
        return new RestHighLevelClient(
                RestClient.builder(new HttpHost(host, port))
        );
    }

    @Bean
    public ElasticsearchOperations elasticsearchTemplate() {
        return new ElasticsearchRestTemplate(elasticsearchClient());
    }
}
  1. 創(chuàng)建一個Spring Data Elasticsearch的Repository接口,用于定義Elasticsearch的查詢方法:
@Repository
public interface UserRepository extends ElasticsearchRepository<User, String> {

    List<User> findByLastName(String lastName, Sort sort);

}
  1. 在需要排序的查詢方法中,使用Sort對象指定排序方式:
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public List<User> findByLastName(String lastName, String sortField, Sort.Direction sortDirection) {
        Sort sort = Sort.by(sortDirection, sortField);
        return userRepository.findByLastName(lastName, sort);
    }
}

這樣就可以通過調(diào)用findByLastName方法,傳入排序字段和排序方向,實(shí)現(xiàn)對結(jié)果的排序。

0