materio_sapi: ranking cached for the next pages (H9)

Each page of 15 results ran every query again (0.7 s for words, 1 s for a
phrase, up to 4 s). Base::rankedSearch() caches the ranking 10 min in the
materio_sapi bin, per user (results depend on node grants), invalidated by
node_list. Pages 2+ now take 1 ms, page 1 unchanged.

The OR query is not limited yet: tied to the tail cut of H6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ShDspHaZGwHoRZCsPBJzsM
This commit is contained in:
2026-11-17 19:10:10 +01:00
co-authored by Claude Opus 5.5
parent 6d8c64c94f
commit 88ecfb7199
2 changed files with 39 additions and 1 deletions
@@ -0,0 +1,8 @@
services:
# Rankings of the searches, reused by the next pages (H9).
cache.materio_sapi:
class: Drupal\Core\Cache\CacheBackendInterface
tags:
- { name: cache.bin }
factory: ['@cache_factory', 'get']
arguments: [materio_sapi]
@@ -117,6 +117,36 @@ class Base extends ControllerBase {
*/ */
public const SHORT_QUERY_WORDS = 6; public const SHORT_QUERY_WORDS = 6;
/**
* Lifetime of a cached ranking, in seconds (H9).
*/
public const RANKING_LIFETIME = 600;
/**
* Ranking of the search, computed once for all its pages (H9).
*
* Each page used to run every query again (0.7 s for words, 1 s for a
* phrase, up to 4 s, page 2 as slow as page 1). The ranking is cached per
* user: results depend on the node grants, so two accounts never share an
* entry; anonymous visitors share theirs. Dropped after RANKING_LIFETIME
* or when a node changes (node_list).
*/
private function rankedSearch(string $lang): void {
$cid = implode(':', [
'ranking',
$lang,
$this->currentUser()->id(),
hash('sha256', json_encode([$this->phrase, $this->terms])),
]);
$cache = \Drupal::cache('materio_sapi');
if ($cached = $cache->get($cid)) {
[$this->results, $this->exactematch_count, $this->knn_count] = $cached->data;
return;
}
$this->sapiQuery();
$cache->set($cid, [$this->results, $this->exactematch_count, $this->knn_count], \Drupal::time()->getRequestTime() + self::RANKING_LIFETIME, ['node_list']);
}
/** /**
* Runs the keyword queries and merges their results, exact matches first. * Runs the keyword queries and merges their results, exact matches first.
* *
@@ -423,7 +453,7 @@ class Base extends ControllerBase {
if ($this->keys) { if ($this->keys) {
$lang = \Drupal::languageManager()->getCurrentLanguage()->getId(); $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
$this->sapiQuery(); $this->rankedSearch($lang);
$resp['keys'] = json_encode($this->keys); $resp['keys'] = json_encode($this->keys);
$resp['terms'] = json_encode($this->terms); $resp['terms'] = json_encode($this->terms);