在Spring Boot中整合Elasticsearch實(shí)現(xiàn)排序,可以通過以下步驟實(shí)現(xiàn):
<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);
}
}
這樣就可以通過調(diào)用findByLastName
方法,傳入排序字段和排序方向,實(shí)現(xiàn)對結(jié)果的排序。