fixed search and add hints
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user