Merge pull request #52 from SlimusMinus/full-text-search
All checks were successful
deploy-backend / deploy (push) Successful in 2m18s
All checks were successful
deploy-backend / deploy (push) Successful in 2m18s
fixed search and add hints
This commit is contained in:
@@ -70,6 +70,10 @@ dependencies {
|
||||
runtimeOnly 'org.postgresql:postgresql'
|
||||
|
||||
testImplementation 'org.springframework.boot:spring-boot-starter-test'
|
||||
// Поиск опирается на возможности PostgreSQL (стемминг, tsvector, pg_trgm) — тестируем на настоящей БД
|
||||
testImplementation 'org.springframework.boot:spring-boot-testcontainers'
|
||||
testImplementation 'org.testcontainers:junit-jupiter'
|
||||
testImplementation 'org.testcontainers:postgresql'
|
||||
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.krylov.refound;
|
||||
import com.krylov.refound.ai.config.AiProperties;
|
||||
import com.krylov.refound.ai.config.AiRetryProperties;
|
||||
import com.krylov.refound.config.MinioProperties;
|
||||
import com.krylov.refound.search.SearchProperties;
|
||||
import io.awspring.cloud.autoconfigure.s3.S3AutoConfiguration;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
@@ -15,7 +16,8 @@ import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
scanBasePackages = "com.krylov.refound",
|
||||
exclude = { S3AutoConfiguration.class, UserDetailsServiceAutoConfiguration.class }
|
||||
)@EnableScheduling
|
||||
@EnableConfigurationProperties({MinioProperties.class, AiProperties.class, AiRetryProperties.class})
|
||||
@EnableConfigurationProperties({MinioProperties.class, AiProperties.class, AiRetryProperties.class,
|
||||
SearchProperties.class})
|
||||
@EnableRetry
|
||||
public class ReFoundApplication {
|
||||
|
||||
|
||||
@@ -3,6 +3,10 @@ package com.krylov.refound.controller;
|
||||
import com.krylov.refound.dto.PostRequest;
|
||||
import com.krylov.refound.dto.PostResponse;
|
||||
import com.krylov.refound.dto.StatusUpdateRequest;
|
||||
import com.krylov.refound.enums.ErrorCode;
|
||||
import com.krylov.refound.exception.ApiException;
|
||||
import com.krylov.refound.search.PostFeedFilter;
|
||||
import com.krylov.refound.search.SearchSuggestService;
|
||||
import com.krylov.refound.service.PostService;
|
||||
import java.util.List;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -11,6 +15,7 @@ import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.web.PageableDefault;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
@@ -32,6 +37,7 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
public class PostController {
|
||||
|
||||
private final PostService service;
|
||||
private final SearchSuggestService searchSuggestService;
|
||||
|
||||
@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public PostRequest create(@ModelAttribute PostRequest request, @RequestParam(value = "images", required = false) List<MultipartFile> images) {
|
||||
@@ -40,9 +46,26 @@ public class PostController {
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public Page<PostResponse> getFeed(@RequestParam(required = false) String search, @PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) {
|
||||
log.info("get all feed");
|
||||
return service.getFeed(search, pageable);
|
||||
public Page<PostResponse> getFeed(@RequestParam(required = false) String search,
|
||||
@RequestParam(required = false) String type,
|
||||
@RequestParam(name = "category", required = false) List<String> categories,
|
||||
@RequestParam(name = "city", required = false) List<String> cities,
|
||||
@PageableDefault(size = 20, sort = "createdAt", direction = Sort.Direction.DESC) Pageable pageable) {
|
||||
log.info("get feed: search='{}', type={}, categories={}, cities={}", search, type, categories, cities);
|
||||
PostFeedFilter filter;
|
||||
try {
|
||||
filter = PostFeedFilter.of(type, categories, cities);
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new ApiException(ErrorCode.VALIDATION_ERROR, "Некорректный фильтр ленты: " + e.getMessage(),
|
||||
HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
return service.getFeed(search, filter, pageable);
|
||||
}
|
||||
|
||||
/** Подсказки для последнего слова строки поиска: «потерян барс» → [барсетка, барсик]. */
|
||||
@GetMapping("/search/suggest")
|
||||
public List<String> suggest(@RequestParam(name = "q", defaultValue = "") String query) {
|
||||
return searchSuggestService.suggest(query);
|
||||
}
|
||||
|
||||
@GetMapping("/{id:\\d+}")
|
||||
|
||||
77
src/main/java/com/krylov/refound/search/PostFeedFilter.java
Normal file
77
src/main/java/com/krylov/refound/search/PostFeedFilter.java
Normal file
@@ -0,0 +1,77 @@
|
||||
package com.krylov.refound.search;
|
||||
|
||||
import com.krylov.refound.enums.PostCategory;
|
||||
import com.krylov.refound.enums.PostType;
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
/**
|
||||
* Фильтры публичной ленты: тип объявления, категории, города.
|
||||
* Пустые значения означают «без ограничения».
|
||||
*
|
||||
* @param cities названия городов/районов в нижнем регистре
|
||||
*/
|
||||
public record PostFeedFilter(PostType type, Set<PostCategory> categories, Set<String> cities) {
|
||||
|
||||
public static final PostFeedFilter NONE = new PostFeedFilter(null, Set.of(), Set.of());
|
||||
|
||||
public PostFeedFilter {
|
||||
categories = categories == null ? Set.of() : Set.copyOf(categories);
|
||||
cities = cities == null ? Set.of() : Set.copyOf(cities);
|
||||
}
|
||||
|
||||
/**
|
||||
* Собирает фильтр из параметров запроса. Тип принимается в любом регистре
|
||||
* ("loss"/"LOSS"), категории — именем enum (ANIMAL) или как на фронте («Питомец»).
|
||||
* Неизвестные значения — 400 через IllegalArgumentException.
|
||||
*/
|
||||
public static PostFeedFilter of(String type, Collection<String> categories, Collection<String> cities) {
|
||||
PostType postType = StringUtils.hasText(type) ? PostType.from(type.trim()) : null;
|
||||
|
||||
Set<PostCategory> postCategories = categories == null ? Set.of() : categories.stream()
|
||||
.filter(StringUtils::hasText)
|
||||
.flatMap(value -> Arrays.stream(value.split(",")))
|
||||
.map(String::trim)
|
||||
.filter(StringUtils::hasText)
|
||||
.map(PostFeedFilter::parseCategory)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
|
||||
Set<String> cityNames = cities == null ? Set.of() : cities.stream()
|
||||
.filter(StringUtils::hasText)
|
||||
.map(city -> city.trim().toLowerCase(Locale.ROOT))
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
|
||||
return new PostFeedFilter(postType, postCategories, cityNames);
|
||||
}
|
||||
|
||||
public boolean isEmpty() {
|
||||
return type == null && categories.isEmpty() && cities.isEmpty();
|
||||
}
|
||||
|
||||
/** Стабильное представление для ключа кэша. */
|
||||
public String cacheKeyPart() {
|
||||
return "type=" + Objects.toString(type, "")
|
||||
+ ":cat=" + categories.stream().map(Enum::name).sorted().collect(Collectors.joining(","))
|
||||
+ ":city=" + cities.stream().sorted().collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
private static PostCategory parseCategory(String value) {
|
||||
for (PostCategory category : PostCategory.values()) {
|
||||
if (category.name().equalsIgnoreCase(value)) {
|
||||
return category;
|
||||
}
|
||||
}
|
||||
return PostCategory.fromDisplayName(value);
|
||||
}
|
||||
|
||||
public List<String> categoryNames() {
|
||||
return categories.stream().map(Enum::name).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.krylov.refound.search;
|
||||
|
||||
import com.krylov.refound.enums.PostStatus;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
|
||||
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/**
|
||||
* Нативные запросы полнотекстового поиска по объявлениям (PostgreSQL).
|
||||
* Возвращает только id в нужном порядке — сами посты грузит JPA.
|
||||
*/
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class PostSearchRepository {
|
||||
|
||||
/** Должно совпадать с выражением индекса idx_posts_title_trgm (changelog 019). */
|
||||
private static final String TITLE_TRGM = "translate(lower(p.title), 'ё', 'е')";
|
||||
|
||||
private final NamedParameterJdbcTemplate jdbc;
|
||||
|
||||
/** Разобранный пользовательский ввод в виде текста tsquery ("" — нет значимых слов). */
|
||||
public record ParsedQuery(String full, String rest, String prefix, String titlePrefix) {
|
||||
}
|
||||
|
||||
/**
|
||||
* websearch_to_tsquery не падает на спецсимволах и понимает "кавычки", -минус и or.
|
||||
* rest — запрос без последнего слова, prefix — последнее слово как префикс ('кош':*),
|
||||
* titlePrefix — тот же префикс, но только среди слов заголовка ('кош':*A, вес A — заголовок).
|
||||
*/
|
||||
public ParsedQuery parse(String text, String rest, String prefixWord) {
|
||||
MapSqlParameterSource params = new MapSqlParameterSource()
|
||||
.addValue("text", text)
|
||||
.addValue("rest", rest == null ? "" : rest)
|
||||
// prefixWord заранее очищен до букв и цифр — to_tsquery на нём не упадёт
|
||||
.addValue("prefix", prefixWord == null || prefixWord.isEmpty() ? "" : prefixWord + ":*")
|
||||
.addValue("titlePrefix", prefixWord == null || prefixWord.isEmpty() ? "" : prefixWord + ":*A");
|
||||
return jdbc.queryForObject("""
|
||||
select websearch_to_tsquery('russian', :text)::text as full_q,
|
||||
websearch_to_tsquery('russian', :rest)::text as rest_q,
|
||||
case when :prefix = '' then '' else to_tsquery('russian', :prefix)::text end as prefix_q,
|
||||
case when :titlePrefix = '' then '' else to_tsquery('russian', :titlePrefix)::text end as title_prefix_q
|
||||
""", params, (rs, i) -> new ParsedQuery(rs.getString(1), rs.getString(2), rs.getString(3),
|
||||
rs.getString(4)));
|
||||
}
|
||||
|
||||
/** Слово → его лексемы по русскому стеммеру (для синонимов). */
|
||||
public List<String> lexemes(String word) {
|
||||
return jdbc.queryForList(
|
||||
"select lexeme from unnest(to_tsvector('russian', :word)) order by lexeme",
|
||||
new MapSqlParameterSource("word", word), String.class);
|
||||
}
|
||||
|
||||
public long countFullText(String tsquery, Collection<PostStatus> statuses, PostFeedFilter filter) {
|
||||
MapSqlParameterSource params = baseParams(statuses, filter).addValue("q", tsquery);
|
||||
return jdbc.queryForObject("select count(*) from posts p where p.search_vector @@ cast(:q as tsquery)"
|
||||
+ filters(filter), params, Long.class);
|
||||
}
|
||||
|
||||
/** Совпадения в заголовке (вес A) ранжируются выше, чем в описании (вес B). */
|
||||
public List<Long> findFullText(String tsquery, Collection<PostStatus> statuses, PostFeedFilter filter,
|
||||
long offset, int limit) {
|
||||
MapSqlParameterSource params = baseParams(statuses, filter)
|
||||
.addValue("q", tsquery)
|
||||
.addValue("offset", offset)
|
||||
.addValue("limit", limit);
|
||||
return jdbc.queryForList("select p.id from posts p where p.search_vector @@ cast(:q as tsquery)"
|
||||
+ filters(filter)
|
||||
+ " order by ts_rank_cd(p.search_vector, cast(:q as tsquery)) desc, p.created_at desc, p.id desc"
|
||||
+ " limit :limit offset :offset", params, Long.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Поиск с опечатками по заголовку. Порог задаётся на транзакцию, поэтому
|
||||
* методы *Typo вызываются внутри @Transactional — иначе set_config не
|
||||
* действует на следующий запрос. Оператор <% использует GIN-индекс.
|
||||
*/
|
||||
public void setTypoThreshold(double threshold) {
|
||||
jdbc.queryForObject("select set_config('pg_trgm.word_similarity_threshold', :t, true)",
|
||||
new MapSqlParameterSource("t", Double.toString(threshold)), String.class);
|
||||
}
|
||||
|
||||
public long countTypo(String text, Collection<PostStatus> statuses, PostFeedFilter filter) {
|
||||
MapSqlParameterSource params = baseParams(statuses, filter).addValue("q", normalizeForTrgm(text));
|
||||
return jdbc.queryForObject("select count(*) from posts p where :q <% " + TITLE_TRGM
|
||||
+ filters(filter), params, Long.class);
|
||||
}
|
||||
|
||||
public List<Long> findTypo(String text, Collection<PostStatus> statuses, PostFeedFilter filter,
|
||||
long offset, int limit) {
|
||||
MapSqlParameterSource params = baseParams(statuses, filter)
|
||||
.addValue("q", normalizeForTrgm(text))
|
||||
.addValue("offset", offset)
|
||||
.addValue("limit", limit);
|
||||
return jdbc.queryForList("select p.id from posts p where :q <% " + TITLE_TRGM
|
||||
+ filters(filter)
|
||||
+ " order by word_similarity(:q, " + TITLE_TRGM + ") desc, p.created_at desc, p.id desc"
|
||||
+ " limit :limit offset :offset", params, Long.class);
|
||||
}
|
||||
|
||||
static String normalizeForTrgm(String text) {
|
||||
return text.toLowerCase(Locale.ROOT).replace('ё', 'е').trim();
|
||||
}
|
||||
|
||||
private static MapSqlParameterSource baseParams(Collection<PostStatus> statuses, PostFeedFilter filter) {
|
||||
return new MapSqlParameterSource()
|
||||
.addValue("statuses", statuses.stream().map(Enum::name).toList())
|
||||
.addValue("type", filter.type() == null ? null : filter.type().name())
|
||||
.addValue("categories", filter.categoryNames())
|
||||
.addValue("cities", List.copyOf(filter.cities()));
|
||||
}
|
||||
|
||||
private static String filters(PostFeedFilter filter) {
|
||||
StringBuilder sql = new StringBuilder(" and p.status in (:statuses)");
|
||||
if (filter.type() != null) {
|
||||
sql.append(" and p.type = :type");
|
||||
}
|
||||
if (!filter.categories().isEmpty()) {
|
||||
sql.append(" and p.category in (:categories)");
|
||||
}
|
||||
if (!filter.cities().isEmpty()) {
|
||||
sql.append(" and (lower(p.city) in (:cities) or lower(p.district) in (:cities))");
|
||||
}
|
||||
return sql.toString();
|
||||
}
|
||||
}
|
||||
158
src/main/java/com/krylov/refound/search/PostSearchService.java
Normal file
158
src/main/java/com/krylov/refound/search/PostSearchService.java
Normal file
@@ -0,0 +1,158 @@
|
||||
package com.krylov.refound.search;
|
||||
|
||||
import com.krylov.refound.enums.PostStatus;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.regex.Pattern;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
/**
|
||||
* Поиск объявлений по тексту. Этапы идут по очереди, пока какой-то не найдёт
|
||||
* хоть что-то:
|
||||
* <ol>
|
||||
* <li>полнотекстовый поиск (стемминг + синонимы): «кот» → коты, кошка, но не «который»;</li>
|
||||
* <li>последнее слово как префикс — поиск по мере ввода: «кош» → «кошка».
|
||||
* Только если первый этап пуст: иначе «кот:*» подтянул бы «который».
|
||||
* Сначала префикс ищется только в заголовках: заголовок говорит, что
|
||||
* потеряли, а в описании полно случайных слов — «барс» должен найти
|
||||
* «Потеряна барсетка», а не кота, который «откликается на Барсик».
|
||||
* Описания подключаются, только если в заголовках ничего нет;</li>
|
||||
* <li>опечатки: похожесть триграмм по заголовку («кошька» → «кошка»).</li>
|
||||
* </ol>
|
||||
* Этап выбирается по наличию результатов вообще, а не на странице, поэтому
|
||||
* все страницы одного запроса берутся из одного этапа — пагинация не скачет.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class PostSearchService {
|
||||
|
||||
/** Длиннее этого ввод обрезаем — защищает БД от гигантских запросов. */
|
||||
static final int MAX_QUERY_LENGTH = 200;
|
||||
|
||||
private static final Pattern HAS_WORD = Pattern.compile("[\\p{L}\\p{N}]");
|
||||
private static final Pattern PLAIN_WORD = Pattern.compile("[\\p{L}\\p{N}]+");
|
||||
|
||||
enum Stage { FULL_TEXT, TITLE_PREFIX, PREFIX, TYPO, NONE }
|
||||
|
||||
private final PostSearchRepository repository;
|
||||
private final SearchProperties properties;
|
||||
private volatile SynonymExpander synonyms;
|
||||
|
||||
public PostSearchService(PostSearchRepository repository, SearchProperties properties) {
|
||||
this.repository = repository;
|
||||
this.properties = properties;
|
||||
}
|
||||
|
||||
/** Есть ли в строке, что искать (хоть одна буква или цифра). */
|
||||
public static boolean hasSearchText(String text) {
|
||||
return text != null && HAS_WORD.matcher(text).find();
|
||||
}
|
||||
|
||||
/** Страница id объявлений в порядке релевантности. */
|
||||
@Transactional(readOnly = true)
|
||||
public Page<Long> search(String rawText, PostFeedFilter filter, Collection<PostStatus> statuses,
|
||||
Pageable pageable) {
|
||||
String text = normalize(rawText);
|
||||
long offset = pageable.getOffset();
|
||||
int limit = pageable.getPageSize();
|
||||
|
||||
String lastWord = lastPlainWord(text);
|
||||
String rest = lastWord == null ? "" : text.substring(0, text.length() - lastWord.length()).trim();
|
||||
PostSearchRepository.ParsedQuery parsed = repository.parse(text, rest, lastWord);
|
||||
|
||||
// 1. Полнотекстовый поиск с синонимами
|
||||
String fullQuery = expander().expand(parsed.full());
|
||||
if (!fullQuery.isBlank()) {
|
||||
long total = repository.countFullText(fullQuery, statuses, filter);
|
||||
if (total > 0) {
|
||||
return page(Stage.FULL_TEXT, text, repository.findFullText(fullQuery, statuses, filter, offset, limit),
|
||||
pageable, total);
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Последнее слово как начало слова — поиск по мере ввода: сначала в заголовках, потом везде
|
||||
if (!parsed.prefix().isBlank()) {
|
||||
String restQuery = expander().expand(parsed.rest());
|
||||
Page<Long> byTitle = prefixStage(Stage.TITLE_PREFIX, text, restQuery, parsed.titlePrefix(), statuses,
|
||||
filter, pageable);
|
||||
if (byTitle != null) {
|
||||
return byTitle;
|
||||
}
|
||||
Page<Long> anywhere = prefixStage(Stage.PREFIX, text, restQuery, parsed.prefix(), statuses, filter,
|
||||
pageable);
|
||||
if (anywhere != null) {
|
||||
return anywhere;
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Опечатки — похожесть по заголовку
|
||||
repository.setTypoThreshold(properties.getTypoThreshold());
|
||||
long total = repository.countTypo(text, statuses, filter);
|
||||
if (total > 0) {
|
||||
return page(Stage.TYPO, text, repository.findTypo(text, statuses, filter, offset, limit), pageable, total);
|
||||
}
|
||||
|
||||
return page(Stage.NONE, text, List.of(), pageable, 0);
|
||||
}
|
||||
|
||||
/** Страница этапа с префиксом или null, если этап ничего не нашёл. */
|
||||
private Page<Long> prefixStage(Stage stage, String text, String restQuery, String prefix,
|
||||
Collection<PostStatus> statuses, PostFeedFilter filter, Pageable pageable) {
|
||||
String query = restQuery.isBlank() ? prefix : "( " + restQuery + " ) & " + prefix;
|
||||
long total = repository.countFullText(query, statuses, filter);
|
||||
if (total == 0) {
|
||||
return null;
|
||||
}
|
||||
return page(stage, text, repository.findFullText(query, statuses, filter, pageable.getOffset(),
|
||||
pageable.getPageSize()), pageable, total);
|
||||
}
|
||||
|
||||
static String normalize(String text) {
|
||||
String collapsed = text.strip().replaceAll("\\s+", " ");
|
||||
return collapsed.length() > MAX_QUERY_LENGTH ? collapsed.substring(0, MAX_QUERY_LENGTH) : collapsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Последнее слово, если его можно искать как префикс: обычное слово
|
||||
* (не в кавычках, не минус-слово, не «or») не короче minPrefixLength.
|
||||
*/
|
||||
String lastPlainWord(String text) {
|
||||
// Нечётное число кавычек — пользователь ещё печатает фразу в кавычках
|
||||
if (text.chars().filter(c -> c == '"').count() % 2 != 0) {
|
||||
return null;
|
||||
}
|
||||
int space = text.lastIndexOf(' ');
|
||||
String last = text.substring(space + 1);
|
||||
if (!PLAIN_WORD.matcher(last).matches()
|
||||
|| last.length() < properties.getMinPrefixLength()
|
||||
|| last.equalsIgnoreCase("or")) {
|
||||
return null;
|
||||
}
|
||||
return last;
|
||||
}
|
||||
|
||||
private Page<Long> page(Stage stage, String text, List<Long> ids, Pageable pageable, long total) {
|
||||
log.debug("Post search '{}': stage={}, total={}", text, stage, total);
|
||||
return new PageImpl<>(ids, pageable, total);
|
||||
}
|
||||
|
||||
/** Синонимы приводятся к лексемам через стеммер Postgres — один раз, при первом поиске. */
|
||||
private SynonymExpander expander() {
|
||||
SynonymExpander current = synonyms;
|
||||
if (current == null) {
|
||||
synchronized (this) {
|
||||
current = synonyms;
|
||||
if (current == null) {
|
||||
current = new SynonymExpander(properties.getSynonyms(), repository::lexemes);
|
||||
synonyms = current;
|
||||
}
|
||||
}
|
||||
}
|
||||
return current;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.krylov.refound.search;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
|
||||
/**
|
||||
* Настройки поиска по объявлениям (prefix "search" в application.yaml).
|
||||
*/
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
@ConfigurationProperties(prefix = "search")
|
||||
public class SearchProperties {
|
||||
|
||||
/**
|
||||
* Группы синонимов: слово из любой группы ищется вместе со всеми словами
|
||||
* этой группы («кот» → кот | кошка | котёнок). Слова можно писать в любой
|
||||
* форме — к основе их приводит тот же русский стеммер Postgres, что и при
|
||||
* индексации. Добавить синоним = дописать слово сюда и перезапустить сервис.
|
||||
*/
|
||||
private List<List<String>> synonyms = new ArrayList<>();
|
||||
|
||||
/**
|
||||
* Порог pg_trgm word_similarity для поиска с опечатками (0..1). Ниже —
|
||||
* больше «похожих» результатов, но и больше мусора.
|
||||
*/
|
||||
private double typoThreshold = 0.3;
|
||||
|
||||
/**
|
||||
* Минимальная длина последнего слова, чтобы искать его как начало слова
|
||||
* («кош» → «кошка»). Совсем короткие префиксы находят почти всё подряд.
|
||||
*/
|
||||
private int minPrefixLength = 3;
|
||||
|
||||
/** Подсказки при вводе (SearchSuggestService). */
|
||||
private Suggest suggest = new Suggest();
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
public static class Suggest {
|
||||
|
||||
/** Сколько подсказок отдавать. */
|
||||
private int limit = 8;
|
||||
|
||||
/** С какой длины слова начинать подсказывать. */
|
||||
private int minLength = 2;
|
||||
|
||||
/** С какой длины слова искать похожие, если по началу ничего нет. */
|
||||
private int typoMinLength = 4;
|
||||
|
||||
/** Порог pg_trgm word_similarity для подсказок с опечаткой (0..1). */
|
||||
private double typoThreshold = 0.5;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package com.krylov.refound.search;
|
||||
|
||||
import com.krylov.refound.util.PostVisibility;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.atomic.LongAdder;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
/**
|
||||
* Подсказки при вводе поиска: дописывает последнее слово по словарю
|
||||
* search_words («барс» → «барсетка», «барсик»). В словаре только слова из
|
||||
* заголовков текущих объявлений, поэтому любая подсказка что-то находит.
|
||||
*
|
||||
* <p>Порядок подсказок — по популярности: в скольких объявлениях есть слово
|
||||
* и как часто его ищут. Поиски копятся в памяти и пишутся в БД раз в
|
||||
* flush-interval, чтобы не делать запись на каждое нажатие клавиши.
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class SearchSuggestService {
|
||||
|
||||
private static final Pattern WORD = Pattern.compile("[\\p{L}\\p{N}]+");
|
||||
/** Предел буфера счётчиков: мусорный ввод не должен съесть память между сбросами. */
|
||||
static final int MAX_PENDING_WORDS = 10_000;
|
||||
|
||||
private final SearchWordRepository repository;
|
||||
private final SearchProperties.Suggest properties;
|
||||
private volatile ConcurrentHashMap<String, LongAdder> pending = new ConcurrentHashMap<>();
|
||||
|
||||
public SearchSuggestService(SearchWordRepository repository, SearchProperties properties) {
|
||||
this.repository = repository;
|
||||
this.properties = properties.getSuggest();
|
||||
}
|
||||
|
||||
/** Подсказки для последнего слова ввода. Пустой список, если слово слишком короткое. */
|
||||
@Transactional(readOnly = true)
|
||||
public List<String> suggest(String text) {
|
||||
String last = lastWord(text);
|
||||
if (last == null || last.length() < properties.getMinLength()) {
|
||||
return List.of();
|
||||
}
|
||||
// +1: само введённое слово тоже может прийти, но его не подсказываем
|
||||
Map<String, String> completions = repository.findByPrefix(last, properties.getLimit() + 1);
|
||||
boolean exactWord = completions.remove(last) != null;
|
||||
if (completions.isEmpty() && !exactWord && last.length() >= properties.getTypoMinLength()) {
|
||||
return repository.findSimilar(last, properties.getTypoThreshold(), properties.getLimit());
|
||||
}
|
||||
return completions.values().stream().limit(properties.getLimit()).toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* Учитывает поиск, который что-то нашёл. Считаются все слова запроса, но в
|
||||
* БД попадут только те, что есть в словаре, — опечатки и обрывки слов отсеются.
|
||||
*/
|
||||
public void recordSearch(String text) {
|
||||
if (text == null) {
|
||||
return;
|
||||
}
|
||||
Map<String, LongAdder> buffer = pending;
|
||||
Matcher m = WORD.matcher(text);
|
||||
while (m.find()) {
|
||||
String word = normalize(m.group());
|
||||
if (word.length() < 3) {
|
||||
continue;
|
||||
}
|
||||
LongAdder counter = buffer.get(word);
|
||||
if (counter == null) {
|
||||
if (buffer.size() >= MAX_PENDING_WORDS) {
|
||||
continue;
|
||||
}
|
||||
counter = buffer.computeIfAbsent(word, w -> new LongAdder());
|
||||
}
|
||||
counter.increment();
|
||||
}
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelayString = "${search.suggest.flush-interval:PT1M}")
|
||||
public void flushSearchCounts() {
|
||||
ConcurrentHashMap<String, LongAdder> buffer = pending;
|
||||
if (buffer.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
pending = new ConcurrentHashMap<>();
|
||||
Map<String, Long> counts = new HashMap<>();
|
||||
buffer.forEach((word, counter) -> counts.put(word, counter.sum()));
|
||||
repository.addSearchCounts(counts);
|
||||
log.debug("Search suggest: flushed {} searched words", counts.size());
|
||||
}
|
||||
|
||||
@Scheduled(initialDelayString = "${search.suggest.initial-delay:PT10S}",
|
||||
fixedDelayString = "${search.suggest.refresh-interval:PT10M}")
|
||||
@Transactional
|
||||
public void rebuildDictionary() {
|
||||
long start = System.currentTimeMillis();
|
||||
repository.rebuild(PostVisibility.FEED_VISIBLE_STATUSES);
|
||||
log.debug("Search suggest: dictionary rebuilt in {} ms", System.currentTimeMillis() - start);
|
||||
}
|
||||
|
||||
/** Последнее слово, если ввод им заканчивается (после пробела подсказывать нечего). */
|
||||
static String lastWord(String text) {
|
||||
if (text == null || text.isEmpty() || !Character.isLetterOrDigit(text.charAt(text.length() - 1))) {
|
||||
return null;
|
||||
}
|
||||
Matcher m = WORD.matcher(text);
|
||||
String last = null;
|
||||
while (m.find()) {
|
||||
last = m.group();
|
||||
}
|
||||
return last == null ? null : normalize(last);
|
||||
}
|
||||
|
||||
static String normalize(String word) {
|
||||
return word.toLowerCase(Locale.ROOT).replace('ё', 'е');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.krylov.refound.search;
|
||||
|
||||
import com.krylov.refound.enums.PostStatus;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
|
||||
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
|
||||
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
|
||||
import org.springframework.stereotype.Repository;
|
||||
|
||||
/**
|
||||
* Словарь подсказок search_words (changelog 020).
|
||||
*/
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class SearchWordRepository {
|
||||
|
||||
private final NamedParameterJdbcTemplate jdbc;
|
||||
|
||||
/**
|
||||
* Пересобирает doc_count по заголовкам видимых объявлений. Строки с
|
||||
* неизменившимися значениями не трогаем, исчезнувшие слова обнуляем,
|
||||
* а слова без объявлений и без поисков удаляем. search_count не меняется.
|
||||
* Стоп-слова («для», «без») отсекает русский словарь Postgres.
|
||||
*/
|
||||
public void rebuild(Collection<PostStatus> statuses) {
|
||||
MapSqlParameterSource params = new MapSqlParameterSource("statuses",
|
||||
statuses.stream().map(Enum::name).toList());
|
||||
jdbc.update("""
|
||||
with fresh as (
|
||||
select translate(w, 'ё', 'е') as norm, max(w) as word, count(distinct p.id) as cnt
|
||||
from posts p, regexp_split_to_table(lower(p.title), '[^а-яёa-z0-9]+') w
|
||||
where p.status in (:statuses)
|
||||
and length(w) >= 3
|
||||
and w !~ '^[0-9]+$'
|
||||
and length(to_tsvector('russian', w)) > 0
|
||||
group by 1
|
||||
), upserted as (
|
||||
insert into search_words (norm, word, doc_count)
|
||||
select norm, word, cnt from fresh
|
||||
on conflict (norm) do update set word = excluded.word, doc_count = excluded.doc_count
|
||||
where (search_words.word, search_words.doc_count) is distinct from (excluded.word, excluded.doc_count)
|
||||
)
|
||||
update search_words set doc_count = 0
|
||||
where doc_count > 0 and norm not in (select norm from fresh)
|
||||
""", params);
|
||||
jdbc.update("delete from search_words where doc_count = 0 and search_count = 0", Map.of());
|
||||
}
|
||||
|
||||
/** Прибавляет счётчики поисков. Слова, которых нет в словаре, игнорируются. */
|
||||
public void addSearchCounts(Map<String, Long> counts) {
|
||||
SqlParameterSource[] batch = counts.entrySet().stream()
|
||||
.map(e -> new MapSqlParameterSource().addValue("norm", e.getKey()).addValue("count", e.getValue()))
|
||||
.toArray(SqlParameterSource[]::new);
|
||||
jdbc.batchUpdate("update search_words set search_count = search_count + :count where norm = :norm", batch);
|
||||
}
|
||||
|
||||
/**
|
||||
* Слова (norm → word), начинающиеся с prefix, включая само слово prefix, если оно есть
|
||||
* (prefix уже нормализован: нижний регистр, ё → е, только буквы и цифры).
|
||||
* Популярность — и сколько объявлений со словом есть, и как часто его ищут;
|
||||
* логарифм не даёт накрутить слово одними поисками.
|
||||
*/
|
||||
public Map<String, String> findByPrefix(String prefix, int limit) {
|
||||
Map<String, String> words = new LinkedHashMap<>();
|
||||
jdbc.query("""
|
||||
select norm, word from search_words
|
||||
where doc_count > 0 and norm like :prefix || '%'
|
||||
order by ln(1 + doc_count) + ln(1 + search_count) desc, norm
|
||||
limit :limit
|
||||
""", new MapSqlParameterSource().addValue("prefix", prefix).addValue("limit", limit),
|
||||
rs -> {
|
||||
words.put(rs.getString("norm"), rs.getString("word"));
|
||||
});
|
||||
return words;
|
||||
}
|
||||
|
||||
/** Похожие слова для ввода с опечаткой («барст» → «барсетка»). Словарь небольшой — без индекса. */
|
||||
public List<String> findSimilar(String text, double threshold, int limit) {
|
||||
return jdbc.queryForList("""
|
||||
select word from search_words
|
||||
where doc_count > 0 and word_similarity(:text, norm) >= :threshold
|
||||
order by word_similarity(:text, norm) desc, ln(1 + doc_count) + ln(1 + search_count) desc, norm
|
||||
limit :limit
|
||||
""", new MapSqlParameterSource()
|
||||
.addValue("text", text)
|
||||
.addValue("threshold", threshold)
|
||||
.addValue("limit", limit), String.class);
|
||||
}
|
||||
}
|
||||
85
src/main/java/com/krylov/refound/search/SynonymExpander.java
Normal file
85
src/main/java/com/krylov/refound/search/SynonymExpander.java
Normal file
@@ -0,0 +1,85 @@
|
||||
package com.krylov.refound.search;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Расширяет tsquery синонимами: лексема 'кот' превращается в
|
||||
* ( 'кот' | 'кошк' | 'котенок' ).
|
||||
*
|
||||
* <p>Работает с текстовым видом tsquery, который вернул websearch_to_tsquery,
|
||||
* поэтому кавычки, минус-слова и OR из пользовательского ввода сохраняются:
|
||||
* «-собака» исключит и собак, и щенков. Лексемы с префиксом или весом
|
||||
* ('кош':*) не трогаем.
|
||||
*
|
||||
* <p>Почему синонимы на стороне Java, а не thesaurus-словарь Postgres:
|
||||
* словарь — это файл в каталоге tsearch_data внутри контейнера БД, своя
|
||||
* text search configuration и пересборка search_vector при каждой правке.
|
||||
* Здесь синонимы — список в application.yaml, индекс от них не зависит.
|
||||
*/
|
||||
public class SynonymExpander {
|
||||
|
||||
// 'лексема' с необязательным суффиксом :* / :A и т.п.; '' внутри — экранированная кавычка
|
||||
private static final Pattern LEXEME = Pattern.compile("'((?:[^']|'')*)'(:[*A-Da-d]+)?");
|
||||
|
||||
/** лексема → все лексемы её группы (в стабильном порядке) */
|
||||
private final Map<String, List<String>> groupByLexeme;
|
||||
|
||||
/**
|
||||
* @param groups группы синонимов в виде слов
|
||||
* @param toLexemes слово → его лексемы по стеммеру Postgres
|
||||
*/
|
||||
public SynonymExpander(List<List<String>> groups, Function<String, List<String>> toLexemes) {
|
||||
Map<String, List<String>> map = new HashMap<>();
|
||||
for (List<String> group : groups) {
|
||||
Set<String> lexemes = new LinkedHashSet<>();
|
||||
for (String word : group) {
|
||||
List<String> wordLexemes = toLexemes.apply(word);
|
||||
// Синоним из нескольких слов одной лексемой не заменить — пропускаем
|
||||
if (wordLexemes.size() == 1) {
|
||||
lexemes.add(wordLexemes.get(0));
|
||||
}
|
||||
}
|
||||
if (lexemes.size() < 2) {
|
||||
continue;
|
||||
}
|
||||
List<String> alternatives = List.copyOf(lexemes);
|
||||
for (String lexeme : lexemes) {
|
||||
map.merge(lexeme, alternatives, (a, b) -> List.copyOf(new LinkedHashSet<>(
|
||||
Stream.concat(a.stream(), b.stream()).toList())));
|
||||
}
|
||||
}
|
||||
this.groupByLexeme = Map.copyOf(map);
|
||||
}
|
||||
|
||||
/** Подставляет группы синонимов в текст tsquery. Пустую строку возвращает как есть. */
|
||||
public String expand(String tsquery) {
|
||||
if (tsquery == null || tsquery.isBlank() || groupByLexeme.isEmpty()) {
|
||||
return tsquery;
|
||||
}
|
||||
Matcher m = LEXEME.matcher(tsquery);
|
||||
StringBuilder out = new StringBuilder();
|
||||
while (m.find()) {
|
||||
String lexeme = m.group(1).replace("''", "'");
|
||||
List<String> group = m.group(2) == null ? groupByLexeme.get(lexeme) : null;
|
||||
String replacement = group == null
|
||||
? m.group()
|
||||
: group.stream().map(SynonymExpander::quote).collect(Collectors.joining(" | ", "( ", " )"));
|
||||
m.appendReplacement(out, Matcher.quoteReplacement(replacement));
|
||||
}
|
||||
m.appendTail(out);
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
private static String quote(String lexeme) {
|
||||
return "'" + lexeme.replace("'", "''") + "'";
|
||||
}
|
||||
}
|
||||
@@ -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). Если у вас уже есть контроллер,
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.krylov.refound.service.redis;
|
||||
|
||||
import com.krylov.refound.enums.PostCategory;
|
||||
import com.krylov.refound.enums.PostType;
|
||||
import com.krylov.refound.search.PostFeedFilter;
|
||||
import com.krylov.refound.service.redis.PostCacheService;
|
||||
import java.util.stream.Collectors;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -18,7 +19,8 @@ public class PostCacheKeyGenerator {
|
||||
|
||||
private final PostCacheService postCacheService;
|
||||
|
||||
public String feedKey(String search, Pageable pageable) {
|
||||
/** Ключ кэша ленты без текстового поиска (поиск не кэшируется). */
|
||||
public String feedKey(PostFeedFilter filter, Pageable pageable) {
|
||||
// Версия читается здесь, то есть в самом начале getFeed, до запроса в БД
|
||||
String version = postCacheService.currentVersion();
|
||||
|
||||
@@ -28,7 +30,7 @@ public class PostCacheKeyGenerator {
|
||||
.collect(Collectors.joining(","));
|
||||
|
||||
return PREFIX + version
|
||||
+ ":search=" + RedisCacheKeyUtil.sha256(RedisCacheKeyUtil.normalize(search))
|
||||
+ ":filter=" + RedisCacheKeyUtil.sha256(filter.cacheKeyPart())
|
||||
+ ":page=" + pageable.getPageNumber()
|
||||
+ ":size=" + pageable.getPageSize()
|
||||
+ ":sort=" + sort;
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.krylov.refound.entity.Post;
|
||||
import com.krylov.refound.entity.User;
|
||||
import com.krylov.refound.enums.PostStatus;
|
||||
import com.krylov.refound.enums.PostType;
|
||||
import com.krylov.refound.search.PostFeedFilter;
|
||||
import jakarta.persistence.criteria.Join;
|
||||
import java.util.Set;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
@@ -45,17 +46,19 @@ public class PostSpecification {
|
||||
);
|
||||
}
|
||||
|
||||
public static Specification<Post> hasSearch(String search) {
|
||||
return (root, query, cb) -> {
|
||||
if (search == null || search.isBlank()) {
|
||||
return cb.conjunction();
|
||||
}
|
||||
String pattern = "%" + search.toLowerCase() + "%";
|
||||
return cb.or(
|
||||
cb.like(cb.lower(root.get("title")), pattern),
|
||||
cb.like(cb.lower(root.get("description")), pattern)
|
||||
);
|
||||
};
|
||||
/** Фильтры публичной ленты: тип, категории, города (город или район, без учёта регистра). */
|
||||
public static Specification<Post> feedFilter(PostFeedFilter filter) {
|
||||
return Specification.allOf(
|
||||
(root, query, cb) -> filter.type() == null ? cb.conjunction() : cb.equal(root.get("type"), filter.type()),
|
||||
(root, query, cb) -> filter.categories().isEmpty()
|
||||
? cb.conjunction()
|
||||
: root.get("category").in(filter.categories()),
|
||||
(root, query, cb) -> filter.cities().isEmpty()
|
||||
? cb.conjunction()
|
||||
: cb.or(
|
||||
cb.lower(root.get("city")).in(filter.cities()),
|
||||
cb.lower(root.get("district")).in(filter.cities()))
|
||||
);
|
||||
}
|
||||
|
||||
public static Specification<Post> cityOrDistrictLike(String query) {
|
||||
|
||||
@@ -55,6 +55,31 @@ ai:
|
||||
delay: 500
|
||||
multiplier: 2
|
||||
|
||||
# Поиск по объявлениям (PostSearchService)
|
||||
search:
|
||||
typo-threshold: 0.3
|
||||
min-prefix-length: 3
|
||||
# Слово из группы ищется вместе со всеми словами группы. Форма слова не важна —
|
||||
# к основе приводит русский стеммер Postgres. Синонимы из нескольких слов не поддерживаются.
|
||||
synonyms:
|
||||
- [кот, кошка, котёнок, котята, котик]
|
||||
- [собака, пёс, щенок, щенки, собачка, пёсик]
|
||||
- [телефон, смартфон, мобильник, айфон, iphone]
|
||||
- [кошелёк, портмоне, бумажник]
|
||||
- [ключи, ключ, связка]
|
||||
- [паспорт, документы]
|
||||
- [рюкзак, ранец]
|
||||
- [очки, окуляры]
|
||||
- [попугай, попугайчик]
|
||||
# Подсказки при вводе (SearchSuggestService): словарь слов из заголовков объявлений
|
||||
suggest:
|
||||
limit: 8
|
||||
min-length: 2
|
||||
typo-min-length: 4
|
||||
typo-threshold: 0.5
|
||||
refresh-interval: PT10M # пересборка словаря
|
||||
flush-interval: PT1M # запись накопленной статистики поисков
|
||||
|
||||
jwt:
|
||||
secret: ${JWT_SECRET}
|
||||
access-expiration: ${JWT_ACCESS_EXPIRATION:900000} # 15 минут
|
||||
|
||||
@@ -31,3 +31,5 @@ databaseChangeLog:
|
||||
- include: { file: db/changelog/alter/014-posts-rules-accepted-type.yaml }
|
||||
- include: { file: db/changelog/alter/015-chats-unique-per-post.yaml }
|
||||
- include: { file: db/changelog/add/018-add-address-posts.yaml }
|
||||
- include: { file: db/changelog/search/019-posts-full-text-search.yaml }
|
||||
- include: { file: db/changelog/search/020-search-words.yaml }
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
databaseChangeLog:
|
||||
- changeSet:
|
||||
id: 019-posts-full-text-search
|
||||
author: krylov
|
||||
comment: >
|
||||
Полнотекстовый поиск по объявлениям. search_vector — сгенерированная
|
||||
колонка: Postgres сам пересчитывает её при изменении title/description,
|
||||
приложению её писать не нужно (в сущности Post она не маппится).
|
||||
Заголовок весит больше описания (A > B) — это учитывает ts_rank_cd.
|
||||
Конфигурация 'russian' стеммит слова: «кот» находит «кота», «коты»,
|
||||
но не «который». pg_trgm — для поиска с опечатками по заголовку.
|
||||
changes:
|
||||
- sql:
|
||||
sql: CREATE EXTENSION IF NOT EXISTS pg_trgm
|
||||
- sql:
|
||||
sql: >
|
||||
ALTER TABLE posts ADD COLUMN search_vector tsvector
|
||||
GENERATED ALWAYS AS (
|
||||
setweight(to_tsvector('russian'::regconfig, coalesce(title, '')), 'A') ||
|
||||
setweight(to_tsvector('russian'::regconfig, coalesce(description, '')), 'B')
|
||||
) STORED
|
||||
- sql:
|
||||
sql: CREATE INDEX idx_posts_search_vector ON posts USING gin (search_vector)
|
||||
- sql:
|
||||
# Выражение должно совпадать с тем, что в PostSearchRepository,
|
||||
# иначе индекс не используется. translate — чтобы «ё» и «е» не мешали опечаткам.
|
||||
sql: CREATE INDEX idx_posts_title_trgm ON posts USING gin (translate(lower(title), 'ё', 'е') gin_trgm_ops)
|
||||
rollback:
|
||||
- sql:
|
||||
sql: DROP INDEX IF EXISTS idx_posts_title_trgm
|
||||
- sql:
|
||||
sql: DROP INDEX IF EXISTS idx_posts_search_vector
|
||||
- sql:
|
||||
sql: ALTER TABLE posts DROP COLUMN IF EXISTS search_vector
|
||||
23
src/main/resources/db/changelog/search/020-search-words.yaml
Normal file
23
src/main/resources/db/changelog/search/020-search-words.yaml
Normal file
@@ -0,0 +1,23 @@
|
||||
databaseChangeLog:
|
||||
- changeSet:
|
||||
id: 020-search-words
|
||||
author: krylov
|
||||
comment: >
|
||||
Словарь для подсказок при вводе поиска. Слова берутся из заголовков
|
||||
видимых объявлений (doc_count — в скольких объявлениях встречается),
|
||||
search_count — сколько раз слово искали с ненулевым результатом.
|
||||
Таблицу пересобирает SearchSuggestService по расписанию; search_count
|
||||
при пересборке сохраняется. norm — слово в нижнем регистре с ё → е,
|
||||
в collation "C", чтобы первичный ключ обслуживал LIKE 'префикс%'.
|
||||
changes:
|
||||
- sql:
|
||||
sql: >
|
||||
CREATE TABLE search_words (
|
||||
norm text COLLATE "C" PRIMARY KEY,
|
||||
word text NOT NULL,
|
||||
doc_count int NOT NULL DEFAULT 0,
|
||||
search_count bigint NOT NULL DEFAULT 0
|
||||
)
|
||||
rollback:
|
||||
- sql:
|
||||
sql: DROP TABLE IF EXISTS search_words
|
||||
Reference in New Issue
Block a user