86 lines
3.8 KiB
Java
86 lines
3.8 KiB
Java
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("'", "''") + "'";
|
||
}
|
||
}
|