Files
materio-d9/web/modules/custom/materio_sapi/src/RankFusion.php
T
bachirandClaude Opus 5.5 7755ff3f01 Search: words found only in a description come back (Q8)
The model sums up a whole record in one vector: a rare word of the
description weighs too little (« métamorphose »: 5 records missing or
far). With the neighbours, the keyword query over every field runs
again, all words required, best 100 matches, reordered by closeness to
the phrase, then fused with the neighbours. Without the model it stays
the former any-word query. RankFusion takes a weight per list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 12:33:15 +01:00

70 lines
2.0 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.
* @param array<float> $weights
* Weight of each ranking, same keys; 1 when missing (Q8).
*
* @return array<int|string>
* Node IDs, each once.
*/
public static function fuse(array $exact, array $rankings, int $k = self::K, array $weights = []): array {
$merged = [];
foreach ($exact as $nid) {
$merged[$nid] ??= $nid;
}
$scores = [];
$first = [];
$position = 0;
foreach ($rankings as $key => $ranking) {
$weight = $weights[$key] ?? 1.0;
$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] += $weight / ($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);
}
}