我想在 Spring boot 中构建一个搜索算法。 我有一个 **公司实体 **,我想获得一个带分页的集合。 我想根据计算的相关性值对集合进行排序,该值是根据与CompanyEntity映射的值计算得出的,例如公司有多少条评论、平均评论、所有者活动。
Specification<CompanyEntity> specification = CompanySpecification.build(searchDto);
Pageable pageable = PageRequest.of(searchDto.getPage(),PAGE_SIZE,utility.sortBuilder(searchDto));
Page<CompanyEntity> companyEntities = companyRepository.findAll(specification,pageable);
从存储库获取集合后对其进行排序太慢。 我尝试使用排序对象,但只能按列名称排序。我是否必须在 SQL 级别计算这个相关值,或者 Spring 中已经为此制定了解决方案? 泰.
您可以考虑的一种方法是在获取数据后计算 Java 代码中的相关性值,然后对结果进行排序。这样,您可以更灵活地定义相关性计算逻辑。但是,正如您所提到的,从存储库中获取集合后在内存中对集合进行排序可能会很慢,尤其是在处理大型数据集时。
要优化此过程,您可以考虑使用 PriorityQueue 以及考虑计算的相关性值的自定义比较器。这使您可以在获取数据时保持集合的高效排序。例如:
// Define your custom comparator for the priority queue
Comparator<CompanyEntity> relevanceComparator = (company1, company2) -> {
// Calculate relevance values for company1 and company2
double relevance1 = calculateRelevance(company1);
double relevance2 = calculateRelevance(company2);
// Compare based on relevance values
return Double.compare(relevance2, relevance1); // Reverse order for higher relevance first
};
PriorityQueue<CompanyEntity> sortedCompanies = new PriorityQueue<>(relevanceComparator);
// Fetch data and add to the priority queue
for (CompanyEntity company : companyEntities) {
double relevance = calculateRelevance(company);
company.setRelevance(relevance); // Store the calculated relevance in the entity
sortedCompanies.offer(company);
}
// Paginate the sorted results
List<CompanyEntity> paginatedResults = new ArrayList<>();
int startIndex = searchDto.getPage() * PAGE_SIZE;
int endIndex = startIndex + PAGE_SIZE;
for (int i = 0; i < startIndex && !sortedCompanies.isEmpty(); i++) {
sortedCompanies.poll(); // Discard companies before the desired page
}
for (int i = startIndex; i < endIndex && !sortedCompanies.isEmpty(); i++) {
paginatedResults.add(sortedCompanies.poll());
}
虽然这种方法需要更多的内存来存储优先级队列,但它比在内存中对整个集合进行排序要高效得多。