fixed search and add hints

This commit is contained in:
SlimusMinus
2026-10-18 23:46:13 +03:00
parent c1b14da7b9
commit 96b4be5e6f
17 changed files with 904 additions and 20 deletions

View File

@@ -17,6 +17,9 @@ import com.krylov.refound.exception.ApiException;
import com.krylov.refound.mapper.PostMapper;
import com.krylov.refound.repository.ImageRepository;
import com.krylov.refound.repository.PostRepository;
import com.krylov.refound.search.PostFeedFilter;
import com.krylov.refound.search.PostSearchService;
import com.krylov.refound.search.SearchSuggestService;
import com.krylov.refound.service.redis.MapCacheService;
import com.krylov.refound.service.redis.PostCacheKeyGenerator;
import com.krylov.refound.service.redis.PostCacheService;
@@ -40,6 +43,10 @@ import org.springframework.web.multipart.MultipartFile;
import java.time.Duration;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.Set;
@Service
@@ -61,6 +68,8 @@ public class PostService {
private final PostCacheService postCacheService;
private final PostCacheKeyGenerator postCacheKeyGenerator;
private final MapCacheService mapCacheService;
private final PostSearchService postSearchService;
private final SearchSuggestService searchSuggestService;
@Transactional
public PostRequest create(PostRequest request, List<MultipartFile> images) {
@@ -94,7 +103,25 @@ public class PostService {
return request;
}
public Page<PostResponse> getFeed(String search, Pageable pageable) {
/**
* Публичная лента: фильтры по типу, категориям и городам + поиск по тексту.
* С текстом поиска — полнотекстовый поиск с ранжированием по релевантности
* (сортировка из pageable игнорируется) и без кэша: запросы почти всегда
* уникальны, а GIN-индекс отвечает быстро. Без текста — обычная лента,
* кэшируется в Redis с учётом фильтров.
*/
public Page<PostResponse> getFeed(String search, PostFeedFilter filter, Pageable pageable) {
PostFeedFilter feedFilter = filter == null ? PostFeedFilter.NONE : filter;
if (PostSearchService.hasSearchText(search)) {
Page<Long> ids = postSearchService.search(search, feedFilter, FEED_VISIBLE_STATUSES, pageable);
// Статистика для подсказок: только удачные поиски и только первая страница —
// подгрузка следующих страниц того же запроса не делает слово популярнее
if (pageable.getPageNumber() == 0 && ids.getTotalElements() > 0) {
searchSuggestService.recordSearch(search);
}
return new PageImpl<>(loadInOrder(ids.getContent()), ids.getPageable(), ids.getTotalElements());
}
// Без уникального ключа в сортировке порядок постов с одинаковым createdAt
// недетерминирован, и при LIMIT/OFFSET посты дублируются или пропадают между страницами
@@ -104,7 +131,7 @@ public class PostService {
}
// Ключ содержит версию ленты, она читается до запроса в БД
String cacheKey = postCacheKeyGenerator.feedKey(search, pageable);
String cacheKey = postCacheKeyGenerator.feedKey(feedFilter, pageable);
CachedPostPage cached = postCacheService.getFeed(cacheKey);
@@ -115,7 +142,7 @@ public class PostService {
log.debug("Feed cache MISS: {}", cacheKey);
Specification<Post> spec = PostSpecification.hasSearch(search)
Specification<Post> spec = PostSpecification.feedFilter(feedFilter)
.and((root, query, cb) ->
root.get("status").in(FEED_VISIBLE_STATUSES)
);
@@ -136,6 +163,21 @@ public class PostService {
return responsePage;
}
/** Загружает посты по id и отдаёт их в том же порядке (порядок релевантности поиска). */
private List<PostResponse> loadInOrder(List<Long> ids) {
if (ids.isEmpty()) {
return List.of();
}
Map<Long, Post> byId = postRepository.findAllById(ids).stream()
.collect(Collectors.toMap(Post::getId, Function.identity()));
return ids.stream()
.map(byId::get)
// пост могли удалить между двумя запросами — просто пропускаем
.filter(Objects::nonNull)
.map(post -> toResponse(post, true))
.toList();
}
/**
* Возвращает посты указанного пользователя (это НЕ поиск поста по его собственному id,
* несмотря на то, как метод назывался раньше — getById). Если у вас уже есть контроллер,