Search: autocomplete terms add up as labels, all their records exact (Q7)

A chosen suggestion becomes a removable label in the field; the search
starts with Enter or the button, so several terms and free text combine.
The request sends the whole phrase (titles, model) and the term IDs.
Terms are ANDed in the same filter as the countries of Q6; every record
of the chosen terms is exact, ordered by the other words then by the
model, then close results from the whole catalogue. The message names
what makes a result exact (terms, countries as typed). Wider field.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-01 11:34:25 +01:00
co-authored by Claude Opus 5.5
parent 030fe5ee86
commit 91d03b44ce
15 changed files with 403 additions and 69 deletions
@@ -62,6 +62,13 @@ function materio_sapi_search_messages_strings(): array {
=> '1 résultat exact pour « @keys »',
$plural('@n exact result out of @total relevant results for “@keys”', '@n exact results out of @total relevant results for “@keys”')
=> $plural('@n résultat exact sur @total résultats pertinents pour « @keys »', '@n résultats exacts sur @total résultats pertinents pour « @keys »'),
// What makes a result exact, named (Q6, Q7).
$plural('No exact result for @filters, @n close result for “@keys”', 'No exact result for @filters, @n close results for “@keys”')
=> $plural('Aucun résultat exact pour @filters, @n résultat proche pour « @keys »', 'Aucun résultat exact pour @filters, @n résultats proches pour « @keys »'),
'1 exact result for @filters: “@keys”'
=> '1 résultat exact pour @filters : « @keys »',
$plural('@n exact result for @filters, out of @total relevant results for “@keys”', '@n exact results for @filters, out of @total relevant results for “@keys”')
=> $plural('@n résultat exact pour @filters, sur @total résultats pertinents pour « @keys »', '@n résultats exacts pour @filters, sur @total résultats pertinents pour « @keys »'),
// Former text, French corrected ("le champs").
'Please use the search form to search from our @count materials.'
=> 'Utilisez le champ de recherche pour naviguer dans nos @count matériaux référencés.',
@@ -93,3 +100,10 @@ function materio_sapi_update_11002(): string {
_locale_refresh_translations(['fr'], $lids);
return 'French translation of the search messages added.';
}
/**
* Adds the French translation of the messages naming the filters (Q6, Q7).
*/
function materio_sapi_update_11003(): string {
return materio_sapi_update_11002();
}
@@ -111,7 +111,7 @@ class Base extends ControllerBase {
*
* Off on trial since 17/11 (H6): on a phrase it matched about 40 % of the
* catalogue. Kept: it still runs when there are no neighbours (model
* stopped, slow or switched off, term chosen in the autocomplete), so that
* stopped, slow or switched off), so that
* the search answers as before.
*/
public const OR_WITH_KNN = FALSE;
@@ -138,10 +138,31 @@ class Base extends ControllerBase {
private ?array $countryTermIds = NULL;
/**
* Whether the queries are restricted to the countries found (Q6).
* Whether the queries are restricted to the countries found (Q6) and to the
* terms chosen in the autocomplete (Q7).
*/
private bool $countryFilter = FALSE;
/**
* Terms chosen in the autocomplete, as IDs (Q7).
*
* @var int[]
*/
private array $termIds = [];
/**
* What makes a result exact, for the message: names of the chosen terms,
* countries as typed (Q6, Q7).
*
* @var string[]
*/
private array $filterNames = [];
/**
* Most terms taken from a request (Q7).
*/
public const MAX_TERMS = 10;
/**
* The reference query, run before the others.
*
@@ -180,11 +201,11 @@ class Base extends ControllerBase {
]);
$cache = \Drupal::cache('materio_sapi');
if ($cached = $cache->get($cid)) {
[$this->results, $this->exactematch_count, $this->knn_count] = $cached->data;
[$this->results, $this->exactematch_count, $this->knn_count, $this->filterNames] = $cached->data + [3 => []];
return;
}
$this->sapiQuery();
$cache->set($cid, [$this->results, $this->exactematch_count, $this->knn_count], \Drupal::time()->getRequestTime() + self::RANKING_LIFETIME, ['node_list']);
$cache->set($cid, [$this->results, $this->exactematch_count, $this->knn_count, $this->filterNames], \Drupal::time()->getRequestTime() + self::RANKING_LIFETIME, ['node_list']);
}
/**
@@ -213,11 +234,17 @@ class Base extends ControllerBase {
// Only stop words: search the phrase as typed, as before.
$keys = $words ? implode(' ', $words) : implode(' ', $this->keys);
// A country named in the phrase is a condition, not a keyword (Q6):
// « pigment Italie » searches « pigment » among the records of Italian
// companies or tagged Italie. Not for a term chosen in the autocomplete.
$this->countries = $this->terms ? $this->countries : CountryDetector::detect($text);
$this->countryFilter = (bool) $this->countries['codes'];
// Terms chosen in the autocomplete (Q7) and a country named in the
// phrase (Q6) are conditions, not keywords: « pigment Italie » searches
// « pigment » among the records of Italian companies or tagged Italie;
// [céramique] [translucide] japon searches « japon » among the records
// that have both terms. The phrase keeps the names of the terms for the
// titles and the model; the conditions use their IDs.
$this->termIds = $this->chosenTermIds();
$free = $this->termIds ? $this->withoutTermNames($text, $lang) : $text;
$this->countries = CountryDetector::detect($free);
$this->countryFilter = $this->termIds || $this->countries['codes'];
$this->filterNames = [...$this->termNames($lang), ...$this->countries['forms']];
$this->knn_count = 0;
if (!$this->countryFilter) {
[$nids, $uuids, $this->exactematch_count] = $this->rank($keys, $words, $lang, $exact, TRUE);
@@ -225,27 +252,43 @@ class Base extends ControllerBase {
else {
$rest = KeywordText::words($this->countries['rest'], $lang);
if (!$rest) {
// The country alone (« italien »): all its records, no model.
// The terms or the country alone (« italien »): all their records.
$exact += $this->countryQuery($lang);
$this->exactematch_count = count($exact);
$this->results = ['uuids' => array_column($exact, 1), 'nids' => array_column($exact, 0)];
return;
$nids = array_keys($exact);
$uuids = array_column($exact, 1, 0);
}
if (count($words) <= self::SHORT_QUERY_WORDS) {
// A title may hold the country (« papier japonais »): whole phrase.
$exact += $this->phraseQuery($keys, $lang);
else {
if (count($words) <= self::SHORT_QUERY_WORDS) {
// A title may hold the country (« papier japonais »): whole phrase.
$exact += $this->phraseQuery($keys, $lang);
}
if ($this->termIds) {
// Terms chosen are a filter asked for (Q7): all their records are
// exact, the rest of the phrase only orders them. « bois-résiné
// qui sent bon » gave no exact match and 2 of the 31 records of
// the term on top, the others scattered or cut (01/12).
[$nids, $uuids, $this->exactematch_count] = $this->termRecords(implode(' ', $rest), $rest, $lang, $exact);
}
else {
// The records of the country first: their exact matches on the
// rest of the phrase, then their neighbours…
[$nids, $uuids, $this->exactematch_count] = $this->rank(implode(' ', $rest), $rest, $lang, $exact, FALSE);
}
}
$keys = implode(' ', $rest);
// The country first: its exact matches, then its neighbours…
[$nids, $uuids, $this->exactematch_count] = $this->rank($keys, $rest, $lang, $exact, FALSE);
// …then the same search everywhere, as without a country, so that the
// list does not stop after a handful of records (51 Portuguese records
// in all, « céramique Portugal » gave 2 results, 30/11). Counted as
// close results: only the records of the country are exact.
// …then the same search everywhere, so that the list does not stop
// after a handful of records (51 Portuguese records in all,
// « céramique Portugal » gave 2 results, 30/11; 13 records have both
// céramique and translucide, 01/12). Counted as close results: only
// the records of the terms and the country are exact. The names of the
// terms count again here, as words; nothing more for a country alone.
$this->countryFilter = FALSE;
[$more, $more_uuids] = $this->rank($keys, $rest, $lang, [], TRUE);
$nids = array_merge($nids, array_values(array_diff($more, $nids)));
$uuids += $more_uuids;
$wide = KeywordText::words($this->countries['codes'] ? CountryDetector::detect($text)['rest'] : $text, $lang);
if ($wide) {
[$more, $more_uuids] = $this->rank(implode(' ', $wide), $wide, $lang, [], TRUE);
$nids = array_merge($nids, array_values(array_diff($more, $nids)));
$uuids += $more_uuids;
}
}
$this->results = [
@@ -289,11 +332,47 @@ class Base extends ControllerBase {
return [$nids, $uuids, count($exact)];
}
/**
* Every record of the chosen terms, in order (Q7).
*
* First the exact matches already found and the records whose tags hold
* every other word, then the others by closeness to the phrase (no
* ScoreCut: they are all kept), then those the model did not score.
*
* @param string $keys
* Rest of the phrase, without stop words.
* @param string[] $words
* The same, as a list.
* @param array<int, array{0: mixed, 1: string}> $exact
* Exact matches already found (references, titles).
*
* @return array{0: array<int|string>, 1: array<int, string>, 2: int}
* Node IDs in order, their UUIDs keyed by nid, number of exact matches.
*/
private function termRecords(string $keys, array $words, string $lang, array $exact): array {
if (count($words) <= self::SHORT_QUERY_WORDS) {
$exact += $this->andQuery($keys, $lang);
}
$all = $this->countryQuery($lang);
// A title holding the phrase counts only with the terms.
$exact = array_intersect_key($exact, $all);
$neighbours = $this->neighbours($lang) ?? [];
$this->knn_count += count($neighbours);
$nids = array_keys($exact);
foreach (array_keys($neighbours) as $nid) {
if (isset($all[$nid])) {
$nids[] = $nid;
}
}
$nids = array_values(array_unique(array_merge($nids, array_keys($all))));
$uuids = array_column($exact + $all, 1, 0);
return [$nids, $uuids, count($nids)];
}
/**
* Nodes closest in meaning to the phrase (materio_ai, Solr kNN).
*
* Not for a term chosen in the autocomplete (direct search) nor without
* the materio_ai service. On a model or Solr error, past the delay of
* Not without the materio_ai service. On a model or Solr error, past the delay of
* QueryEmbedder (1 s), or with materio_ai switched off, the keyword
* results stand alone, with no message: the search answers as before H5.
*
@@ -302,12 +381,14 @@ class Base extends ControllerBase {
* are no neighbours to use.
*/
private function neighbours(string $lang): ?array {
if ($this->terms || !\Drupal::hasService('materio_ai.neighbour_search')) {
if (!\Drupal::hasService('materio_ai.neighbour_search')) {
return NULL;
}
// References are keywords: they mean nothing to the model. Neither do
// countries (« italien » brought Milano, Veneto): they filter instead (Q6).
$phrase = $this->countries['codes'] ? $this->countries['rest'] : $this->phrase;
// The names of the chosen terms stay (Q7): « céramique translucide » means
// more to the model than « translucide ».
$phrase = $this->countries['codes'] ? CountryDetector::detect($this->phrase)['rest'] : $this->phrase;
$phrase = trim(preg_replace(self::REFERENCE_PATTERN, ' ', $phrase) ?? '');
if ($phrase === '') {
return NULL;
@@ -395,17 +476,6 @@ class Base extends ControllerBase {
private function andQuery(string $keys, string $lang): array {
$this->and_query = $this->keywordQuery('terms', 'AND', $keys, $lang, 'materio_sapi_search_and_query');
// A term chosen in the autocomplete restricts to the taxonomy fields.
if ($this->terms && is_array($this->terms) && count($this->terms)) {
$term_conditions = $this->and_query->createConditionGroup('OR');
foreach ($this->terms as $term) {
foreach (['tag_tid', 'thesaurus_tid'] as $field) {
$term_conditions->addCondition($field, (int) $term->value);
}
}
$this->and_query->addConditionGroup($term_conditions);
}
// Thesaurus and tag fields only.
$this->and_query->setFulltextFields([
'thesaurus_name_0',
@@ -428,7 +498,7 @@ class Base extends ControllerBase {
}
/**
* Every record of the countries named in the phrase (Q6).
* Every record of the chosen terms and of the countries named (Q6, Q7).
*
* @return array<int, array{0: mixed, 1: string}>
* [nid, uuid] keyed by nid, in result order.
@@ -450,8 +520,19 @@ class Base extends ControllerBase {
* The query, not executed yet.
*/
private function addCountryCondition($query): void {
if (!$this->countryFilter) {
return;
}
// Every chosen term, as a tag or a thesaurus term (Q7): AND between the
// terms, so that choosing a second one narrows the list.
foreach ($this->termIds as $tid) {
$group = $query->createConditionGroup('OR');
$group->addCondition('tag_tid', $tid);
$group->addCondition('thesaurus_tid', $tid);
$query->addConditionGroup($group);
}
$codes = $this->countries['codes'];
if (!$this->countryFilter || !$codes) {
if (!$codes) {
return;
}
$group = $query->createConditionGroup('OR');
@@ -464,6 +545,63 @@ class Base extends ControllerBase {
$query->addConditionGroup($group);
}
/**
* IDs of the terms chosen in the autocomplete (Q7).
*
* The request sends [{"value": tid, "label": name}, …]; only the IDs are
* kept, the names come from the terms themselves.
*
* @return int[]
* Term IDs, at most MAX_TERMS.
*/
private function chosenTermIds(): array {
$ids = [];
foreach (is_array($this->terms) ? $this->terms : [] as $term) {
$tid = is_object($term) ? ($term->value ?? NULL) : $term;
if (is_numeric($tid) && (int) $tid > 0) {
$ids[(int) $tid] = (int) $tid;
}
}
return array_slice(array_values($ids), 0, self::MAX_TERMS);
}
/**
* Names of the chosen terms in the language, in the order chosen (Q7).
*
* @return string[]
* Names.
*/
private function termNames(string $lang): array {
$terms = \Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadMultiple($this->termIds);
$names = [];
foreach ($this->termIds as $tid) {
if (isset($terms[$tid])) {
$term = $terms[$tid];
$names[] = $term->hasTranslation($lang) ? $term->getTranslation($lang)->label() : $term->label();
}
}
return $names;
}
/**
* The phrase without the names of the chosen terms (Q7).
*
* What is left is searched among the records of the terms.
*/
private function withoutTermNames(string $text, string $lang): string {
$names = $this->termNames($lang);
foreach (\Drupal::entityTypeManager()->getStorage('taxonomy_term')->loadMultiple($this->termIds) as $term) {
$names[] = $term->label();
}
// Longest first (« bois flotté » before « bois »).
$names = array_unique(array_filter($names));
usort($names, static fn ($a, $b): int => mb_strlen($b) <=> mb_strlen($a));
foreach ($names as $name) {
$text = preg_replace('/(?<![\p{L}\p{N}])' . preg_quote($name, '/') . '(?![\p{L}\p{N}])/iu', ' ', $text) ?? $text;
}
return trim(preg_replace('/\s+/u', ' ', $text) ?? $text);
}
/**
* Tags and thesaurus terms named like the countries found.
*
@@ -624,7 +762,7 @@ class Base extends ControllerBase {
// count no longer depends on an arbitrary limit. Plurals and "close"
// results without any exact match (F4).
$resp['infos'] = (new SearchMessage($this->getStringTranslation()))
->results($resp['exactematch_count'], $resp['count'], $this->phrase, $lang);
->results($resp['exactematch_count'], $resp['count'], $this->phrase, $lang, $this->filterNames);
// $resp['options'] = $this->query->getOptions();
// $uuids = [];
@@ -27,8 +27,12 @@ final class SearchMessage {
/**
* Message of a search: exact matches out of all the results shown.
*
* @param string[] $filters
* What makes a result exact, when it is not every word: terms chosen in
* the autocomplete (Q7), countries as typed (Q6). Named in the message.
*/
public function results(int $exact, int $total, string $keys, string $lang): TranslatableMarkup {
public function results(int $exact, int $total, string $keys, string $lang, array $filters = []): TranslatableMarkup {
$args = [
'@n' => self::number($exact, $lang),
'@total' => self::number($total, $lang),
@@ -37,6 +41,19 @@ final class SearchMessage {
if ($total === 0) {
return $this->translation->translate('No results for “@keys”. Try other words or a broader description.', $args);
}
$named = self::listing($filters, $lang);
// « italien » alone: naming it twice says nothing more.
if ($named !== '' && mb_strtolower($named) !== mb_strtolower($keys)) {
$args['@filters'] = $named;
if ($exact === 0) {
$args['@n'] = $args['@total'];
return $this->translation->formatPlural($total, 'No exact result for @filters, @n close result for “@keys”', 'No exact result for @filters, @n close results for “@keys”', $args);
}
if ($total === 1) {
return $this->translation->translate('1 exact result for @filters: “@keys”', $args);
}
return $this->translation->formatPlural($exact, '@n exact result for @filters, out of @total relevant results for “@keys”', '@n exact results for @filters, out of @total relevant results for “@keys”', $args);
}
if ($exact === 0) {
$args['@n'] = $args['@total'];
return $this->translation->formatPlural($total, 'No exact result, @n close result for “@keys”', 'No exact result, @n close results for “@keys”', $args);
@@ -59,6 +76,21 @@ final class SearchMessage {
]);
}
/**
* « a », « a et b », « a, b et c » (English: and).
*
* @param string[] $items
* Names.
*/
public static function listing(array $items, string $lang): string {
$items = array_values(array_filter(array_map('trim', $items), 'strlen'));
if (count($items) < 2) {
return $items[0] ?? '';
}
$last = array_pop($items);
return implode(', ', $items) . ($lang === 'fr' ? ' et ' : ' and ') . $last;
}
/**
* A number with the thousands separator of the language.
*
@@ -41,6 +41,37 @@ final class SearchMessageTest extends UnitTestCase {
$this->assertSame($expected, (string) $message->results($exact, $total, 'bois', 'en'));
}
/**
* Cases with a filter: what makes a result exact is named (Q6, Q7).
*/
public static function filtersProvider(): array {
return [
'one term' => [30, 252, 'bois-résiné qui sent bon', ['bois-résiné'], '30 exact results for bois-résiné, out of 252 relevant results for “bois-résiné qui sent bon”'],
'terms and country' => [3, 291, 'céramique translucide japon', ['céramique', 'translucide', 'japon'], '3 exact results for céramique, translucide and japon, out of 291 relevant results for “céramique translucide japon”'],
'none exact' => [0, 40, 'bois-résiné bleu', ['bois-résiné'], 'No exact result for bois-résiné, 40 close results for “bois-résiné bleu”'],
'one alone' => [1, 1, 'tissu Islande', ['Islande'], '1 exact result for Islande: “tissu Islande”'],
'country alone' => [586, 586, 'italien', ['italien'], '586 exact results out of 586 relevant results for “italien”'],
];
}
/**
* The filters are named, unless they are the whole phrase.
*/
#[DataProvider('filtersProvider')]
public function testFilters(int $exact, int $total, string $keys, array $filters, string $expected): void {
$message = new SearchMessage($this->getStringTranslationStub());
$this->assertSame($expected, (string) $message->results($exact, $total, $keys, 'en', $filters));
}
/**
* French list: « a, b et c ».
*/
public function testListing(): void {
$this->assertSame('céramique, translucide et Japon', SearchMessage::listing(['céramique', 'translucide', 'Japon'], 'fr'));
$this->assertSame('a and b', SearchMessage::listing(['a', 'b'], 'en'));
$this->assertSame('', SearchMessage::listing([], 'fr'));
}
/**
* The help before any search gives the size of the catalogue.
*/