在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
方法,传入排序字段和排序方向,实现对结果的排序。