在Spring Boot中整合Elasticsearch實現排序,可以通過以下步驟實現:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
@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());
}
}
@Repository
public interface UserRepository extends ElasticsearchRepository<User, String> {
List<User> findByLastName(String lastName, Sort 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);
}
}
這樣就可以通過調用findByLastName
方法,傳入排序字段和排序方向,實現對結果的排序。