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 net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
/**
* Подсказки при вводе поиска: дописывает последнее слово по словарю
* search_words («барс» → «барсетка», «барсик»). В словаре только слова из
* заголовков текущих объявлений, поэтому любая подсказка что-то находит.
*
*
Порядок подсказок — по популярности: в скольких объявлениях есть слово
* и как часто его ищут. Поиски копятся в памяти и пишутся в БД раз в
* 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 pending = new ConcurrentHashMap<>();
public SearchSuggestService(SearchWordRepository repository, SearchProperties properties) {
this.repository = repository;
this.properties = properties.getSuggest();
}
/** Подсказки для последнего слова ввода. Пустой список, если слово слишком короткое. */
@Transactional(readOnly = true)
public List suggest(String text) {
String last = lastWord(text);
if (last == null || last.length() < properties.getMinLength()) {
return List.of();
}
// +1: само введённое слово тоже может прийти, но его не подсказываем
Map 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 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 buffer = pending;
if (buffer.isEmpty()) {
return;
}
pending = new ConcurrentHashMap<>();
Map 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}")
// Словарь общий (таблица search_words) — пересобирает один экземпляр
@SchedulerLock(name = "rebuildSearchDictionary", lockAtMostFor = "PT5M", lockAtLeastFor = "PT30S")
@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('ё', 'е');
}
}