Files
materio-d9/web/modules/custom/materio_sapi/src/RankFusion.php
T
bachirandClaude Opus 5.5 797a5714f1 materio_sapi: hybrid search, keyword and kNN results merged by RRF (H5)
RankFusion::fuse(): exact matches (references, phrase, all words) first, in
their order; then the OR query and the kNN neighbours merged by reciprocal
rank fusion (k = 60, ranks only). Base::neighbours() asks materio_ai for 200
neighbours of the phrase without references; no model call for a chosen
term, references alone, a missing service, or an error (logged, keyword
results only). Unit test RankFusionTest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ShDspHaZGwHoRZCsPBJzsM
2026-11-17 12:43:04 +01:00

67 lines
1.9 KiB
PHP

<?php
declare(strict_types=1);
namespace Drupal\materio_sapi;
/**
* Merges ranked result lists: exact matches first, the rest by RRF (H5).
*
* Reciprocal rank fusion: a node scores the sum of 1 / (k + rank) over the
* lists that hold it (rank from 1). Only ranks count, not the scores of each
* engine, which are not comparable (BM25 against cosine). Equal scores keep
* the order of first appearance, list by list: the keyword lists are already
* sorted by relevance then by date (fallback sort kept).
*/
final class RankFusion {
/**
* Usual constant of RRF: dampens the weight of the first ranks.
*/
public const K = 60;
/**
* Returns the merged order.
*
* @param array<int|string> $exact
* Node IDs of the exact matches (references, phrase, all words), in order.
* Always first, whatever the other lists say.
* @param array<array<int|string>> $rankings
* Ranked lists of node IDs (keyword OR query, kNN neighbours…).
* @param int $k
* RRF constant.
*
* @return array<int|string>
* Node IDs, each once.
*/
public static function fuse(array $exact, array $rankings, int $k = self::K): array {
$merged = [];
foreach ($exact as $nid) {
$merged[$nid] ??= $nid;
}
$scores = [];
$first = [];
$position = 0;
foreach ($rankings as $ranking) {
$rank = 0;
foreach ($ranking as $nid) {
$rank++;
if (isset($merged[$nid])) {
continue;
}
if (!isset($scores[$nid])) {
$scores[$nid] = 0.0;
$first[$nid] = [$position++, $nid];
}
$scores[$nid] += 1 / ($k + $rank);
}
}
uksort($scores, static fn ($a, $b): int => [$scores[$b], $first[$a][0]] <=> [$scores[$a], $first[$b][0]]);
foreach (array_keys($scores) as $nid) {
$merged[$nid] = $first[$nid][1];
}
return array_values($merged);
}
}