From fea2e9b9ffc7ece0542da555826f25fb98c299ab Mon Sep 17 00:00:00 2001 From: Shinsuke Sugaya Date: Sun, 9 Aug 2026 00:07:02 +0900 Subject: [PATCH] docs(search): correct the 15.8 rank fusion page against the implementation Verified ja/15.8/config/rank-fusion.rst against RankFusionProcessor, SemanticChunkSearcher, FessConfigImpl, SystemHelper, fess_rankfusion.xml and fess_config.properties, then propagated the result to the other six languages. Corrections: - The troubleshooting sections recommended lowering rank.fusion.window_size to 100. init() clamps the value to paging.search.page.max.size * 2, which is 200 by default -- the same as window_size's own default. The suggested value was therefore silently raised back to 200. The page now states that paging.search.page.max.size has to be lowered first, and shows both keys together. - rank.fusion.threads is computed as availableProcessors * 3 / 2 + 1 with integer arithmetic, not "cores x 1.5 + 1"; it sizes a fixed thread pool. - content_chunker.search.enabled is a system property (conf/system.properties or -Dfess.system.), not a fess_config.properties key, and it is only evaluated at startup. - rank.fusion.searchers is read with a raw System.getProperty, so the -Dfess.config. / -Dfess.system. prefixed forms do not work. The fess.in.sh snippet now uses the FESS_JAVA_OPTS form. It can also be set from the "System Property" field under System > General, which promotes arbitrary keys via System.setProperty. Added: - Verifying fusion results: the searcher and rf_score fields, that both are runtime-only and absent from the index, and that seeing them in /api/v2/search requires query.additional.api.response.fields. - Impact on hit counts: fusion adds the documents only the non-main searchers found to the reported total, and skips that correction when the count is a lower bound. - Behavior when a searcher fails: a failing searcher degrades to an empty result with a WARN and fusion continues, except for InvalidQueryException and ResultOffsetExceededException, and except on deep pages, where the fallback path has no exception handling. There is no per-searcher timeout. - All four rank.fusion.* settings require a restart, because FessConfigImpl memoizes fess_config.properties values for the lifetime of the JVM. - RRF is fixed, with no algorithm switch and no per-searcher weighting. - Troubleshooting now starts from the searcher field and the semantic-skip conditions. --- de/15.8/config/rank-fusion.rst | 186 +++++++++++++++++++++++++---- en/15.8/config/rank-fusion.rst | 174 ++++++++++++++++++++++++--- es/15.8/config/rank-fusion.rst | 186 +++++++++++++++++++++++++---- fr/15.8/config/rank-fusion.rst | 192 ++++++++++++++++++++++++++---- ja/15.8/config/rank-fusion.rst | 168 ++++++++++++++++++++++---- ko/15.8/config/rank-fusion.rst | 168 ++++++++++++++++++++++---- zh-cn/15.8/config/rank-fusion.rst | 161 +++++++++++++++++++++---- 7 files changed, 1094 insertions(+), 141 deletions(-) diff --git a/de/15.8/config/rank-fusion.rst b/de/15.8/config/rank-fusion.rst index e4021222..1f0c386a 100644 --- a/de/15.8/config/rank-fusion.rst +++ b/de/15.8/config/rank-fusion.rst @@ -46,6 +46,13 @@ Formel:: - ``rank(d)``: Rang des Dokuments d in jedem Suchergebnis (0-basiert) - ``Σ``: Summe über alle Sucher, in denen Dokument d vorkommt +.. note:: + + Der Fusionsalgorithmus ist fest auf RRF eingestellt; es gibt keine Einstellung, um auf einen + anderen Algorithmus umzuschalten. Ebenso wird keine Gewichtung einzelner Sucher unterstützt — + der Beitrag jedes Suchers geht mit demselben Gewicht in die Summe ein. Die einzige + Stellschraube für die Ranking-Tendenz ist ``rank.fusion.rank_constant``. + Einstellungen ============= @@ -63,7 +70,7 @@ Grundkonfiguration:: rank.fusion.rank_constant=20 # Anzahl der Threads für parallele Verarbeitung - # (bei 0 oder kleiner wird die Anzahl verfügbarer CPU-Kerne × 1.5 + 1 verwendet) + # (bei 0 oder kleiner wird die Anzahl verfügbarer CPU-Kerne × 3 ÷ 2 + 1 verwendet) rank.fusion.threads=-1 # Name des Score-Felds (Feld, in dem der fusionierte Score gespeichert wird) @@ -78,29 +85,54 @@ Grundkonfiguration:: - Beschreibung * - ``rank.fusion.window_size`` - ``200`` - - Maximale Anzahl der Ergebnisse, die von jedem Sucher für die Fusion abgerufen werden. Muss >= ``paging.search.page.max.size × 2`` (standardmäßig ``200``) sein; bei einem kleineren Wert wird dieser automatisch auf dieses Minimum angehoben. + - Maximale Anzahl der Ergebnisse, die von jedem Sucher für die Fusion abgerufen werden. Muss >= ``paging.search.page.max.size × 2`` (standardmäßig ``200``) sein; bei einem kleineren Wert wird dieser automatisch auf dieses Minimum angehoben (beim Start wird dazu eine WARN-Meldung protokolliert). * - ``rank.fusion.rank_constant`` - ``20`` - Die Konstante ``k`` in der RRF-Formel. Ein größerer Wert verringert den Score-Unterschied zwischen höher und niedriger platzierten Ergebnissen. * - ``rank.fusion.threads`` - ``-1`` - - Anzahl der Threads beim parallelen Ausführen mehrerer Sucher. Bei Angabe von ``0`` oder kleiner wird automatisch ``Anzahl verfügbarer CPU-Kerne × 1.5 + 1`` verwendet. + - Anzahl der Threads des festen Thread-Pools, der mehrere Sucher parallel ausführt. Bei Angabe von ``0`` oder kleiner wird automatisch ``Anzahl verfügbarer CPU-Kerne × 3 ÷ 2 + 1`` verwendet (die Berechnung erfolgt in Ganzzahlarithmetik, Nachkommastellen werden also abgeschnitten; Beispiel: 4 Kerne → 7, 5 Kerne → 8). * - ``rank.fusion.score_field`` - ``rf_score`` - Name des Ergebnisdokument-Felds, in dem der fusionierte Score gespeichert wird. +.. note:: + + **Wann Änderungen wirksam werden** + + Alle vier oben genannten Einstellungen erfordern einen Neustart von |Fess|, damit eine + Änderung wirksam wird. Aus ``fess_config.properties`` gelesene Werte werden innerhalb der JVM + zwischengespeichert; ein Bearbeiten der Datei im laufenden Betrieb bleibt daher wirkungslos. + + Ergänzend: ``rank.fusion.window_size`` wird nur einmal beim Start gelesen, + ``rank.fusion.threads`` beim Anlegen des Thread-Pools. Der Thread-Pool wird angelegt, sobald + ein anderer Sucher als ``default`` (etwa der semantische Sucher) registriert wird; ist die + semantische Suche deaktiviert, wird der Thread-Pool gar nicht erst angelegt. + JVM-Systemeigenschaften ----------------------- Die zu verwendenden Sucher werden als JVM-Systemeigenschaft angegeben. Fügen Sie Folgendes -zu ``fess.in.sh`` (oder ``fess.in.bat``) hinzu:: +zu ``fess.in.sh`` hinzu:: - # Sucher angeben (kommagetrennt) - -Drank.fusion.searchers=default,semantic_chunk + FESS_JAVA_OPTS="$FESS_JAVA_OPTS -Drank.fusion.searchers=default,semantic_chunk" + +Bei ``fess.in.bat`` lautet der Eintrag wie folgt:: + + set FESS_JAVA_OPTS=%FESS_JAVA_OPTS% -Drank.fusion.searchers=default,semantic_chunk Diese Eigenschaft verhält sich wie folgt: -- Sie wird als JVM-Option gesetzt, nicht in ``fess_config.properties``. +- Sie wird als JVM-Option gesetzt, nicht in ``fess_config.properties``. Geben Sie als Schlüssel + genau ``rank.fusion.searchers`` an. Die bei anderen Einstellungen gebräuchlichen Formen mit + vorangestelltem ``-Dfess.config.`` oder ``-Dfess.system.`` (etwa + ``-Dfess.config.rank.fusion.searchers``) werden nicht erkannt. +- Anstelle einer JVM-Option können Sie den Wert auch in der Verwaltungsoberfläche unter + „System > Allgemein" im Feld „Systemeigenschaften" als einzelne Zeile eintragen, etwa + ``rank.fusion.searchers=default,semantic_chunk``. Beachten Sie jedoch, dass ein Wert in diesem + Feld nur angewendet wird, wenn noch keine gleichnamige Systemeigenschaft gesetzt ist. Eine + Angabe per ``-D`` hat also Vorrang, und um einen bereits angewendeten Wert zu ändern, ist ein + Neustart von |Fess| erforderlich. - ``default`` ist der Sucher, der die Standard-Schlüsselwortsuche ausführt, und ist stets verfügbar. - Der Name eines Suchers leitet sich vom Namen seiner Implementierungsklasse ab: Das abschließende ``Searcher`` wird entfernt und der Rest in Snake Case in Kleinbuchstaben umgewandelt @@ -130,8 +162,70 @@ Integration mit Hybridsuche Rank Fusion ist besonders effektiv bei der Hybridsuche, die Schlüsselwortsuche und semantische Suche kombiniert. Um die semantische Suche zu nutzen, konfigurieren Sie die -Content-Chunking-Funktion und setzen Sie ``content_chunker.search.enabled=true``. Siehe -:doc:`search-semantic` für Details. +Content-Chunking-Funktion und setzen Sie anschließend ``content_chunker.search.enabled=true``. + +.. warning:: + + Die Einstellungen unter ``content_chunker.*`` — etwa ``content_chunker.enabled`` oder + ``content_chunker.search.enabled`` — sind **Systemeigenschaften** und gehören nicht in + ``fess_config.properties``. Tragen Sie sie in ``conf/system.properties`` ein oder geben Sie + sie als JVM-Option an, zum Beispiel + ``-Dfess.system.content_chunker.search.enabled=true``. Einträge in + ``fess_config.properties`` bleiben wirkungslos. Zudem wird + ``content_chunker.search.enabled`` nur beim Start ausgewertet; nach dem Aktivieren ist daher + ein Neustart von |Fess| erforderlich. + +Siehe :doc:`search-semantic` für Details. + +Fusionsergebnisse überprüfen +============================ + +Ob Rank Fusion tatsächlich arbeitet, erkennen Sie an den beiden folgenden Feldern, die den +Suchergebnissen hinzugefügt werden. + +.. list-table:: + :header-rows: 1 + :widths: 20 80 + + * - Feld + - Inhalt + * - ``searcher`` + - Array mit den Namen der Sucher, die dieses Dokument abgerufen haben (Beispiel: ``["default", "semantic_chunk"]``). Sind beide enthalten, wurde das Dokument sowohl von der Schlüsselwortsuche als auch von der semantischen Suche gefunden. + * - ``rf_score`` + - Der mit RRF berechnete fusionierte Score. Der Feldname lässt sich über ``rank.fusion.score_field`` ändern. + +Beide Werte werden zur Suchzeit dynamisch hinzugefügt und nicht im Index gespeichert. +Da sie standardmäßig nicht in der Antwort von ``/api/v2/search`` enthalten sind, nehmen Sie zum +Überprüfen die folgende Einstellung in ``fess_config.properties`` vor und starten Sie |Fess| +neu:: + + query.additional.api.response.fields=rf_score,searcher + +.. note:: + + ``query.additional.api.response.fields`` fügt der Allowlist der Felder Einträge hinzu, die in + der Antwort der v2-Such-API enthalten sein dürfen. Nehmen Sie dort keine Felder der + Zugriffskontrolle wie ``role`` oder ``virtual_host`` auf, da sonst Informationen zur + Zugriffskontrolle in der Antwort der Such-API offengelegt werden. + +Auswirkungen auf die Trefferzahl +================================ + +Wird Rank Fusion ausgeführt, entspricht die zurückgegebene Gesamttrefferzahl nicht unverändert +der Trefferzahl des Hauptsuchers (des an erster Stelle registrierten ``default``-Suchers), +sondern wird wie folgt korrigiert:: + + Gesamttrefferzahl = Gesamttrefferzahl des Hauptsuchers + Korrekturwert + +Der Korrekturwert ist die Anzahl derjenigen Dokumente unter den obersten ``window_size ÷ 2`` +Ergebnissen nach der Fusion, die nicht in den obersten ``window_size ÷ 2`` Ergebnissen des +Hauptsuchers enthalten waren. Die Trefferzahl erhöht sich also genau um die Dokumente, die nur +die semantische Suche gefunden hat. +Daher kann sich die Trefferzahl bei derselben Anfrage unterscheiden, je nachdem, ob die +Hybridsuche aktiviert ist oder nicht. + +Wird die Gesamttrefferzahl des Hauptsuchers als Näherungswert (Untergrenze) zurückgegeben, +findet diese Korrektur nicht statt. Anwendungsbeispiele =================== @@ -167,13 +261,25 @@ Speicherverbrauch ----------------- - Der Speicherverbrauch steigt, da mehrere Suchergebnisse vorgehalten werden. -- Verwenden Sie ``rank.fusion.window_size``, um die maximale Anzahl der zu fusionierenden Ergebnisse zu begrenzen. Der Hauptsucher (der führende ``default``-Sucher) ruft bis zu ``window_size`` Ergebnisse ab, während jeder der anderen Sucher ``window_size ÷ Anzahl der Sucher`` Ergebnisse abruft. +- Verwenden Sie ``rank.fusion.window_size``, um die maximale Anzahl der zu fusionierenden Ergebnisse zu begrenzen. Der Hauptsucher (der führende ``default``-Sucher) ruft bis zu ``window_size`` Ergebnisse ab, während jeder der anderen Sucher ``window_size ÷ Anzahl der Sucher`` Ergebnisse abruft (die ``Anzahl der Sucher`` ist die Gesamtzahl einschließlich des Hauptsuchers, und die Division wird abgerundet). +- Gibt es beispielsweise zwei Sucher (``default`` und ``semantic_chunk``) und gilt ``window_size=200``, so ruft der Hauptsucher 200 und der semantische Sucher 100 Ergebnisse ab; es werden also maximal 300 Dokumente vorgehalten. :: # Fenstergröße für die Fusion rank.fusion.window_size=200 +.. warning:: + + ``rank.fusion.window_size`` kann ``paging.search.page.max.size × 2`` nicht unterschreiten. + Steht ``paging.search.page.max.size`` auf dem Standardwert ``100``, liegt die Untergrenze bei + ``200`` und damit genau beim Standardwert von ``rank.fusion.window_size``. Das bedeutet: **In + der Standardkonfiguration lässt sich window_size gar nicht unter den Standardwert senken.** + Ein kleinerer Wert führt beim Start lediglich zu einer WARN-Meldung und wird auf ``200`` + angehoben. Um den Wert tatsächlich zu verringern, müssen Sie zuerst + ``paging.search.page.max.size`` senken; damit sinkt jedoch zugleich die maximale Anzahl an + Ergebnissen, die im Suchbildschirm oder über die API pro Seite angefordert werden kann. + Verarbeitungszeit ----------------- @@ -183,9 +289,32 @@ Verarbeitungszeit :: # Anzahl der Threads für parallele Ausführung - # (bei 0 oder kleiner wird die Anzahl verfügbarer CPU-Kerne × 1.5 + 1 verwendet) + # (bei 0 oder kleiner wird die Anzahl verfügbarer CPU-Kerne × 3 ÷ 2 + 1 verwendet) rank.fusion.threads=-1 +.. note:: + + Für die Ausführung der Sucher ist kein Timeout konfiguriert. Antwortet ein Sucher nicht, + wartet die Suchanfrage, bis dieser abgeschlossen ist. + +Verhalten bei Fehlern eines Suchers +=================================== + +Schlägt einer der Sucher mit einer Ausnahme fehl, wird sein Ergebnis als leer behandelt; es wird +eine WARN-Meldung protokolliert und die Fusion mit den Ergebnissen der übrigen Sucher +fortgesetzt. Die Suchanfrage selbst schlägt dadurch nicht fehl. + +Ausgenommen davon sind Syntaxfehler in der Anfrage (``InvalidQueryException``) und das +Überschreiten der Paging-Obergrenze (``ResultOffsetExceededException``) — diese werden +unverändert als Fehler zurückgegeben. Zudem wird bei tiefen Seiten, auf denen keine Fusion +durchgeführt wird (wo ``Startposition × 2`` größer oder gleich ``rank.fusion.window_size`` ist), +eine im Hauptsucher aufgetretene Ausnahme unverändert als Fehler der Suchanfrage +zurückgegeben. + +Kann der semantische Sucher den Embedding-Anbieter nicht erreichen oder schlägt die +Embedding-Verarbeitung fehl, gibt er ein leeres Ergebnis zurück. Auch in diesem Fall tritt kein +Fehler auf; zurückgegeben werden dann nur die Ergebnisse der Schlüsselwortsuche. + Fehlersuche =========== @@ -196,10 +325,20 @@ Suchergebnisse weichen von Erwartungen ab **Prüfpunkte**: -1. Ergebnisse jedes Suchtyps einzeln überprüfen -2. Den Wert von ``rank.fusion.rank_constant`` anpassen -3. Den Wert von ``rank.fusion.window_size`` anpassen -4. Bei tiefen Seiten (wo ``Startposition × 2`` größer oder gleich ``rank.fusion.window_size`` ist) wird keine Fusion durchgeführt und nur der Hauptsucher wird verwendet. Wenn Sie auf mehr Seiten fusionierte Ergebnisse wünschen, erhöhen Sie ``rank.fusion.window_size``. +1. Prüfen Sie das Feld ``searcher`` (siehe „Fusionsergebnisse überprüfen"). Enthält es bei allen + Dokumenten nur ``["default"]``, liefert der semantische Sucher keine Ergebnisse. +2. Prüfen Sie, ob die semantische Suche übersprungen wird. Neben Anfragen, die Suchsyntax + enthalten (etwa ``"``, ``:`` oder ``AND``), liefert der semantische Sucher auch beim + Eingrenzen über Labels, Sortierung oder Facetten sowie bei der Geolokalisierungssuche und der + Suche nach ähnlichen Dokumenten keine Ergebnisse; zurückgegeben werden dann nur die + Ergebnisse der Schlüsselwortsuche. Einzelheiten zu den Bedingungen für das Überspringen + finden Sie unter :doc:`search-semantic`. +3. Ergebnisse jedes Suchtyps einzeln überprüfen +4. Den Wert von ``rank.fusion.rank_constant`` anpassen +5. Bei tiefen Seiten (wo ``Startposition × 2`` größer oder gleich ``rank.fusion.window_size`` + ist, standardmäßig also ab dem 101. Ergebnis) wird keine Fusion durchgeführt und nur der + Hauptsucher wird verwendet. Wenn Sie auf mehr Seiten fusionierte Ergebnisse wünschen, erhöhen + Sie ``rank.fusion.window_size``. Suche ist langsam ----------------- @@ -208,13 +347,19 @@ Suche ist langsam **Lösungen**: -1. ``rank.fusion.window_size`` reduzieren:: +1. ``rank.fusion.threads`` anpassen:: - rank.fusion.window_size=100 + rank.fusion.threads=4 -2. ``rank.fusion.threads`` anpassen:: +2. ``rank.fusion.window_size`` reduzieren. Da der Wert die Untergrenze + (``paging.search.page.max.size × 2``) nicht unterschreiten kann, setzen Sie in der + Standardkonfiguration die folgenden beiden Werte gemeinsam:: - rank.fusion.threads=4 + paging.search.page.max.size=50 + rank.fusion.window_size=100 + + Beachten Sie, dass dadurch auch die maximale Anzahl an Ergebnissen sinkt, die pro Seite + angefordert werden kann. Nach der Änderung ist ein Neustart erforderlich. Speichermangel -------------- @@ -223,12 +368,13 @@ Speichermangel **Lösungen**: -1. ``rank.fusion.window_size`` reduzieren +1. ``rank.fusion.window_size`` wie unter „Suche ist langsam" beschrieben reduzieren 2. JVM-Heap-Größe erhöhen Referenz ======== +- :doc:`search-semantic` - Konfiguration der semantischen Suche (Content-Chunking) - :doc:`scripting-overview` - Scripting-Übersicht - :doc:`search-advanced` - Erweiterte Sucheinstellungen - :doc:`llm-overview` - LLM-Integrations-Leitfaden (Semantische Suche) diff --git a/en/15.8/config/rank-fusion.rst b/en/15.8/config/rank-fusion.rst index 0b6296f8..a6172246 100644 --- a/en/15.8/config/rank-fusion.rst +++ b/en/15.8/config/rank-fusion.rst @@ -46,6 +46,13 @@ Formula:: - ``rank(d)``: Rank of document d in each search result (0-based) - ``Σ``: Sum over all searchers in which document d appears +.. note:: + + The fusion algorithm is fixed to RRF; there is no setting to switch to a different algorithm. + Per-searcher weighting is not supported either: every searcher contributes with the same weight + when the scores are summed. ``rank.fusion.rank_constant`` is the only setting that lets you + adjust the ranking behavior. + Settings ======== @@ -63,7 +70,7 @@ Basic configuration:: rank.fusion.rank_constant=20 # Number of threads for parallel processing - # (if 0 or less, availableProcessors × 1.5 + 1 is used) + # (if 0 or less, availableProcessors × 3 / 2 + 1 is used) rank.fusion.threads=-1 # Score field name (field that stores the fused score) @@ -78,29 +85,53 @@ Basic configuration:: - Description * - ``rank.fusion.window_size`` - ``200`` - - Maximum number of results retrieved from each searcher for fusion. Must be >= ``paging.search.page.max.size × 2`` (``200`` by default); if a smaller value is set, it is automatically raised to this minimum. + - Maximum number of results retrieved from each searcher for fusion. Must be >= ``paging.search.page.max.size × 2`` (``200`` by default); if a smaller value is set, it is automatically raised to this minimum (a WARN log is written at startup). * - ``rank.fusion.rank_constant`` - ``20`` - The constant ``k`` in the RRF formula. A larger value reduces the score difference between higher- and lower-ranked results. * - ``rank.fusion.threads`` - ``-1`` - - Number of threads used when running multiple searchers in parallel. If ``0`` or less is specified, ``availableProcessors × 1.5 + 1`` is used automatically. + - Number of threads in the fixed thread pool used to run multiple searchers in parallel. If ``0`` or less is specified, ``availableProcessors × 3 / 2 + 1`` is used automatically (the calculation uses integer arithmetic, so the fractional part is truncated: for example, 4 cores → 7 and 5 cores → 8). * - ``rank.fusion.score_field`` - ``rf_score`` - Name of the result-document field used to store the fused score. +.. note:: + + **When changes take effect** + + All four settings above require |Fess| to be restarted before a change takes effect. Values + read from ``fess_config.properties`` are cached in the JVM, so editing the file while |Fess| is + running has no effect. + + For reference, ``rank.fusion.window_size`` is read once at startup and ``rank.fusion.threads`` + is read when the thread pool is created. The thread pool is created when a searcher other than + ``default`` (such as the semantic searcher) is registered, so if semantic search is disabled, + no thread pool is created at all. + JVM System Properties --------------------- The searchers to use are specified as a JVM system property. Add the following to -``fess.in.sh`` (or ``fess.in.bat``):: +``fess.in.sh``:: - # Specify searchers (comma-separated) - -Drank.fusion.searchers=default,semantic_chunk + FESS_JAVA_OPTS="$FESS_JAVA_OPTS -Drank.fusion.searchers=default,semantic_chunk" + +For ``fess.in.bat``, write it as follows:: + + set FESS_JAVA_OPTS=%FESS_JAVA_OPTS% -Drank.fusion.searchers=default,semantic_chunk This property behaves as follows: -- It is set as a JVM option, not in ``fess_config.properties``. +- It is set as a JVM option, not in ``fess_config.properties``. Specify the key name + ``rank.fusion.searchers`` exactly as-is. The prefixed forms that are common for other settings, + ``-Dfess.config.`` and ``-Dfess.system.`` (for example ``-Dfess.config.rank.fusion.searchers``), + are not recognized. +- Instead of a JVM option, you can also enter it on a single line, such as + ``rank.fusion.searchers=default,semantic_chunk``, in the "System Property" field under + System > General in the administration UI. Note that a value in that field is applied only when + a system property of the same name is not already set. A ``-D`` option therefore takes + precedence, and changing a value that has already been applied requires restarting |Fess|. - ``default`` is the searcher that performs standard keyword search and is always available. - A searcher's name is derived from its implementation class name by removing the trailing ``Searcher`` and decamelizing the remainder into lowercase snake_case @@ -128,7 +159,64 @@ Integration with Hybrid Search Rank Fusion is particularly effective for hybrid search, which combines keyword search and semantic search. To use semantic search, configure the content chunking feature and -set ``content_chunker.search.enabled=true``. See :doc:`search-semantic` for details. +then set ``content_chunker.search.enabled=true``. + +.. warning:: + + The ``content_chunker.*`` settings, such as ``content_chunker.enabled`` and + ``content_chunker.search.enabled``, are **system properties**, not ``fess_config.properties`` + settings. Write them in ``conf/system.properties``, or specify them as JVM options such as + ``-Dfess.system.content_chunker.search.enabled=true``. Writing them in + ``fess_config.properties`` has no effect. In addition, ``content_chunker.search.enabled`` is + evaluated only at startup, so |Fess| must be restarted after you enable it. + +See :doc:`search-semantic` for details. + +Verifying Fusion Results +======================== + +You can check whether Rank Fusion is actually working by looking at the following two fields added +to the search results. + +.. list-table:: + :header-rows: 1 + :widths: 20 80 + + * - Field + - Description + * - ``searcher`` + - An array of the names of the searchers that retrieved the document (for example, ``["default", "semantic_chunk"]``). If both are present, the document was hit by both keyword search and semantic search. + * - ``rf_score`` + - The fused score calculated by RRF. The field name can be changed with ``rank.fusion.score_field``. + +Both values are added dynamically at search time and are not stored in the index. +They are also not included in the ``/api/v2/search`` response by default, so to see them, add the +following to ``fess_config.properties`` and restart |Fess|:: + + query.additional.api.response.fields=rf_score,searcher + +.. note:: + + ``query.additional.api.response.fields`` adds entries to the allowlist of fields that may be + included in the v2 search API response. Do not add access control fields such as ``role`` or + ``virtual_host``, because doing so exposes access control information in search API responses. + +Impact on Hit Counts +==================== + +When Rank Fusion runs, the total hit count that is returned is not the count from the main +searcher (the ``default`` searcher registered first) as-is; it is adjusted as follows:: + + total hits = total hits of the main searcher + adjustment + +The adjustment is the number of documents among the top ``window_size ÷ 2`` fused results that +were not among the top ``window_size ÷ 2`` results of the main searcher. In other words, the count +increases by the number of documents that only semantic search found. +As a result, the same query can report a different hit count depending on whether hybrid search is +enabled. + +Note that this adjustment is not applied when the total hit count of the main searcher is returned +as an approximate (lower-bound) value. Usage Examples ============== @@ -164,13 +252,24 @@ Memory Usage ------------ - Memory usage increases because multiple search results are retained. -- Use ``rank.fusion.window_size`` to limit the maximum number of results to fuse. The main searcher (the leading ``default`` searcher) retrieves up to ``window_size`` results, while each of the other searchers retrieves ``window_size ÷ number of searchers`` results. +- Use ``rank.fusion.window_size`` to limit the maximum number of results to fuse. The main searcher (the leading ``default`` searcher) retrieves up to ``window_size`` results, while each of the other searchers retrieves ``window_size ÷ number of searchers`` results (``number of searchers`` is the total including the main searcher, and the division is truncated). +- For example, with two searchers (``default`` and ``semantic_chunk``) and ``window_size=200``, the main searcher retrieves 200 results and the semantic searcher retrieves 100, so up to 300 documents are retained. :: # Window size for fusion rank.fusion.window_size=200 +.. warning:: + + ``rank.fusion.window_size`` cannot go below ``paging.search.page.max.size × 2``. When + ``paging.search.page.max.size`` has its default value of ``100``, the lower bound is ``200``, + which is exactly the default value of ``rank.fusion.window_size``. In other words, **in the + default configuration you cannot set window_size to anything smaller than its default**. If you + configure a smaller value, a WARN log is written at startup and the value is raised to ``200``. + To lower it in practice, you must first lower ``paging.search.page.max.size``, but that also + lowers the maximum number of results per page that clients can request. + Processing Time --------------- @@ -180,9 +279,31 @@ Processing Time :: # Number of threads for parallel execution - # (if 0 or less, availableProcessors × 1.5 + 1) + # (if 0 or less, availableProcessors × 3 / 2 + 1) rank.fusion.threads=-1 +.. note:: + + No timeout is applied to searcher execution. If a searcher never responds, the search request + waits until it completes. + +Behavior When a Searcher Fails +============================== + +If a searcher fails with an exception, its results are treated as empty, a WARN log is written, +and fusion continues with the results of the remaining searchers. The search request itself does +not fail. + +Query syntax errors (``InvalidQueryException``) and paging limit violations +(``ResultOffsetExceededException``) are the exceptions to this rule: they are returned as errors +as-is. In addition, on deep pages where fusion is not performed (where ``start position × 2`` is +greater than or equal to ``rank.fusion.window_size``), an exception raised by the main searcher is +returned as a search request error as-is. + +The semantic searcher returns empty results when it cannot connect to the embedding provider or +when embedding processing fails. This does not cause an error either; the response contains +keyword search results only. + Troubleshooting =============== @@ -193,10 +314,18 @@ Search Results Differ from Expectations **Checks**: -1. Verify the results of each search type individually -2. Adjust the ``rank.fusion.rank_constant`` value -3. Adjust the ``rank.fusion.window_size`` value -4. On deep pages (where ``start position × 2`` is greater than or equal to ``rank.fusion.window_size``), fusion is not performed and only the main searcher is used. If you want fused results on more pages, increase ``rank.fusion.window_size``. +1. Check the ``searcher`` field (see "Verifying Fusion Results"). If every document has only + ``["default"]``, the semantic searcher is not returning any results. +2. Check whether semantic search is being skipped. The semantic searcher returns no results, so + only keyword search results are used, for queries that contain search syntax (such as ``"``, + ``:``, or ``AND``), as well as for narrowing by label, sort, or facet, for geo searches, and + for similar-document searches. See :doc:`search-semantic` for details on the skip conditions. +3. Verify the results of each search type individually +4. Adjust the ``rank.fusion.rank_constant`` value +5. On deep pages (where ``start position × 2`` is greater than or equal to + ``rank.fusion.window_size``, which by default means from the 101st result onward), fusion is + not performed and only the main searcher is used. If you want fused results on more pages, + increase ``rank.fusion.window_size``. Slow Search ----------- @@ -205,13 +334,19 @@ Slow Search **Solutions**: -1. Reduce ``rank.fusion.window_size``:: +1. Adjust ``rank.fusion.threads``:: - rank.fusion.window_size=100 + rank.fusion.threads=4 -2. Adjust ``rank.fusion.threads``:: +2. Reduce ``rank.fusion.window_size``. Because it cannot go below its lower bound + (``paging.search.page.max.size × 2``), in the default configuration you have to set the + following two properties together:: - rank.fusion.threads=4 + paging.search.page.max.size=50 + rank.fusion.window_size=100 + + Note that this also lowers the maximum number of results that can be requested per page. A + restart is required after changing these settings. Out of Memory ------------- @@ -220,12 +355,13 @@ Out of Memory **Solutions**: -1. Reduce ``rank.fusion.window_size`` +1. Reduce ``rank.fusion.window_size`` using the same procedure as in "Slow Search" 2. Increase the JVM heap size Reference ========= +- :doc:`search-semantic` - Semantic Search (Content Chunking) Settings - :doc:`scripting-overview` - Scripting Overview - :doc:`search-advanced` - Advanced Search Settings - :doc:`llm-overview` - LLM Integration Guide (Semantic Search) diff --git a/es/15.8/config/rank-fusion.rst b/es/15.8/config/rank-fusion.rst index 80396a3a..92fb4e33 100644 --- a/es/15.8/config/rank-fusion.rst +++ b/es/15.8/config/rank-fusion.rst @@ -46,6 +46,13 @@ Fórmula:: - ``rank(d)``: Posición del documento d en cada resultado de búsqueda (base 0) - ``Σ``: Suma sobre todos los buscadores en los que aparece el documento d +.. note:: + + El algoritmo de fusión es siempre RRF; no existe ningún ajuste para cambiar a otro algoritmo. + Tampoco se admite la ponderación por buscador: la contribución de cada buscador se suma con + el mismo peso. El único ajuste que permite modificar la tendencia del ranking es + ``rank.fusion.rank_constant``. + Configuración ============= @@ -63,7 +70,7 @@ Configuración básica:: rank.fusion.rank_constant=20 # Número de hilos para procesamiento paralelo - # (si es 0 o menos, se usa availableProcessors × 1.5 + 1) + # (si es 0 o menos, se usa availableProcessors × 3 ÷ 2 + 1) rank.fusion.threads=-1 # Nombre del campo de puntuación (campo que almacena la puntuación fusionada) @@ -78,29 +85,55 @@ Configuración básica:: - Descripción * - ``rank.fusion.window_size`` - ``200`` - - Número máximo de resultados recuperados de cada buscador para la fusión. Debe ser >= ``paging.search.page.max.size × 2`` (``200`` de forma predeterminada); si se establece un valor menor, se eleva automáticamente a este mínimo. + - Número máximo de resultados recuperados de cada buscador para la fusión. Debe ser >= ``paging.search.page.max.size × 2`` (``200`` de forma predeterminada); si se establece un valor menor, se eleva automáticamente a este mínimo (se registra una advertencia WARN al iniciar). * - ``rank.fusion.rank_constant`` - ``20`` - La constante ``k`` en la fórmula RRF. Un valor mayor reduce la diferencia de puntuación entre los resultados con mayor y menor rango. * - ``rank.fusion.threads`` - ``-1`` - - Número de hilos utilizados al ejecutar múltiples buscadores en paralelo. Si se especifica ``0`` o menos, se usa ``availableProcessors × 1.5 + 1`` automáticamente. + - Número de hilos del grupo de hilos fijo que ejecuta múltiples buscadores en paralelo. Si se especifica ``0`` o menos, se usa ``availableProcessors × 3 ÷ 2 + 1`` automáticamente (al tratarse de aritmética entera, la parte decimal se trunca; por ejemplo: 4 núcleos → 7, 5 núcleos → 8). * - ``rank.fusion.score_field`` - ``rf_score`` - Nombre del campo del documento de resultados utilizado para almacenar la puntuación fusionada. +.. note:: + + **Cuándo se aplican los cambios de configuración** + + Los cuatro ajustes anteriores requieren reiniciar |Fess| para que un cambio se aplique. Los + valores leídos de ``fess_config.properties`` se almacenan en caché en la JVM, por lo que + modificar el archivo mientras |Fess| está en ejecución no tiene ningún efecto. + + A modo de referencia, ``rank.fusion.window_size`` se lee una sola vez al iniciar y + ``rank.fusion.threads`` se lee en el momento en que se crea el grupo de hilos. El grupo de + hilos se crea cuando se registra un buscador distinto de ``default`` (por ejemplo, el buscador + semántico), de modo que si la búsqueda semántica está deshabilitada no se crea ningún grupo + de hilos. + Propiedades del sistema JVM --------------------------- Los buscadores a utilizar se especifican como una propiedad del sistema JVM. Añada lo -siguiente a ``fess.in.sh`` (o ``fess.in.bat``):: +siguiente a ``fess.in.sh``:: - # Especificar buscadores (separados por comas) - -Drank.fusion.searchers=default,semantic_chunk + FESS_JAVA_OPTS="$FESS_JAVA_OPTS -Drank.fusion.searchers=default,semantic_chunk" + +En el caso de ``fess.in.bat``, escriba lo siguiente:: + + set FESS_JAVA_OPTS=%FESS_JAVA_OPTS% -Drank.fusion.searchers=default,semantic_chunk Esta propiedad se comporta de la siguiente manera: -- Se establece como opción JVM, no en ``fess_config.properties``. +- Se establece como opción JVM, no en ``fess_config.properties``. Especifique el nombre de la + clave tal cual: ``rank.fusion.searchers``. Las formas con los prefijos ``-Dfess.config.`` o + ``-Dfess.system.``, habituales en otros ajustes (por ejemplo, + ``-Dfess.config.rank.fusion.searchers``), no se reconocen. +- En lugar de una opción JVM, también puede escribirlo en una sola línea, como + ``rank.fusion.searchers=default,semantic_chunk``, en el campo "Propiedades del sistema" de + "Sistema > General" de la pantalla de administración. Tenga en cuenta que el valor de ese campo + solo se aplica cuando todavía no existe una propiedad del sistema con el mismo nombre. Por ello, + si se ha indicado con ``-D``, la opción JVM tiene prioridad, y para modificar un valor que ya se + ha aplicado es necesario reiniciar |Fess|. - ``default`` es el buscador que realiza la búsqueda estándar por palabras clave y siempre está disponible. - El nombre de un buscador se deriva del nombre de su clase de implementación eliminando el sufijo ``Searcher`` y convirtiendo el resto a snake_case en minúsculas @@ -129,8 +162,69 @@ Integración con la búsqueda híbrida Rank Fusion es particularmente eficaz para la búsqueda híbrida, que combina la búsqueda por palabras clave y la búsqueda semántica. Para usar la búsqueda semántica, configure la función -de chunking de contenido y establezca ``content_chunker.search.enabled=true``. Consulte -:doc:`search-semantic` para más detalles. +de chunking de contenido y establezca ``content_chunker.search.enabled=true``. + +.. warning:: + + Los ajustes ``content_chunker.*``, como ``content_chunker.enabled`` y + ``content_chunker.search.enabled``, no pertenecen a ``fess_config.properties``, sino que son + **propiedades del sistema**. Escríbalos en ``conf/system.properties`` o especifíquelos como + opción JVM, por ejemplo ``-Dfess.system.content_chunker.search.enabled=true``. Si los escribe + en ``fess_config.properties``, no tendrán ningún efecto. Además, + ``content_chunker.search.enabled`` solo se evalúa al iniciar, por lo que tras habilitarlo es + necesario reiniciar |Fess|. + +Consulte :doc:`search-semantic` para más detalles. + +Verificación de los resultados de la fusión +=========================================== + +Puede comprobar si Rank Fusion está funcionando realmente mediante los dos campos siguientes, +que se añaden a los resultados de búsqueda. + +.. list-table:: + :header-rows: 1 + :widths: 20 80 + + * - Campo + - Contenido + * - ``searcher`` + - Array con los nombres de los buscadores que recuperaron el documento (por ejemplo, ``["default", "semantic_chunk"]``). Si contiene ambos, significa que el documento coincidió tanto en la búsqueda por palabras clave como en la búsqueda semántica. + * - ``rf_score`` + - Puntuación fusionada calculada mediante RRF. El nombre del campo se puede cambiar con ``rank.fusion.score_field``. + +Ambos son valores que se añaden dinámicamente en el momento de la búsqueda y no se almacenan en +el índice. Además, de forma predeterminada no se incluyen en la respuesta de ``/api/v2/search``, +por lo que, para consultarlos, establezca lo siguiente en ``fess_config.properties`` y reinicie +|Fess|:: + + query.additional.api.response.fields=rf_score,searcher + +.. note:: + + ``query.additional.api.response.fields`` es un ajuste que añade elementos a la lista de + permitidos de los campos que pueden incluirse en la respuesta de la API de búsqueda v2. No + añada campos de control de acceso como ``role`` o ``virtual_host``, ya que la información de + control de acceso quedaría expuesta en la respuesta de la API de búsqueda. + +Impacto en el número de resultados +================================== + +Cuando se ejecuta Rank Fusion, el número total de resultados devuelto no es sin más el del +buscador principal (el buscador ``default`` registrado en primer lugar), sino que se corrige de +la siguiente manera:: + + Número total de resultados = número total del buscador principal + valor de corrección + +El valor de corrección es el número de documentos que, estando entre los ``window_size ÷ 2`` +primeros resultados tras la fusión, no estaban entre los ``window_size ÷ 2`` primeros resultados +del buscador principal. Es decir, el número aumenta en la cantidad de documentos que solo +encontró la búsqueda semántica. +Por ello, para una misma consulta el número de resultados puede variar según si la búsqueda +híbrida está habilitada o no. + +Tenga en cuenta que, si el número total de resultados del buscador principal se devuelve como un +valor aproximado (un límite inferior), esta corrección no se aplica. Ejemplos de uso =============== @@ -166,13 +260,25 @@ Uso de memoria -------------- - El uso de memoria aumenta porque se retienen múltiples resultados de búsqueda. -- Use ``rank.fusion.window_size`` para limitar el número máximo de resultados a fusionar. El buscador principal (el buscador ``default`` en primer lugar) recupera hasta ``window_size`` resultados, mientras que cada uno de los demás buscadores recupera ``window_size ÷ número de buscadores`` resultados. +- Use ``rank.fusion.window_size`` para limitar el número máximo de resultados a fusionar. El buscador principal (el buscador ``default`` en primer lugar) recupera hasta ``window_size`` resultados, mientras que cada uno de los demás buscadores recupera ``window_size ÷ número de buscadores`` resultados (``número de buscadores`` es el total incluyendo el buscador principal, y la división se trunca). +- Por ejemplo, con dos buscadores (``default`` y ``semantic_chunk``) y ``window_size=200``, el buscador principal recupera 200 resultados y el buscador semántico 100, por lo que se retienen como máximo 300 documentos. :: # Tamaño de ventana para la fusión rank.fusion.window_size=200 +.. warning:: + + ``rank.fusion.window_size`` no puede ser inferior a ``paging.search.page.max.size × 2``. Si + ``paging.search.page.max.size`` tiene su valor predeterminado ``100``, el límite inferior es + ``200``, que coincide con el valor predeterminado de ``rank.fusion.window_size``. Es decir, + **en la configuración predeterminada no es posible establecer window_size por debajo de su + valor predeterminado**. Si establece un valor menor, se registra una advertencia WARN al + iniciar y el valor se eleva a ``200``. Para reducirlo realmente es necesario reducir antes + ``paging.search.page.max.size``, pero esto también reduce el número máximo de resultados que + se pueden solicitar por página desde la pantalla de búsqueda y la API. + Tiempo de procesamiento ----------------------- @@ -182,9 +288,32 @@ Tiempo de procesamiento :: # Número de hilos para ejecución paralela - # (si es 0 o menos, availableProcessors × 1.5 + 1) + # (si es 0 o menos, availableProcessors × 3 ÷ 2 + 1) rank.fusion.threads=-1 +.. note:: + + La ejecución de los buscadores no tiene ningún tiempo de espera configurado. Si algún buscador + no devuelve respuesta, la solicitud de búsqueda espera hasta que este finalice. + +Comportamiento cuando falla un buscador +======================================= + +Si alguno de los buscadores falla con una excepción, sus resultados se tratan como vacíos: se +registra una advertencia WARN y la fusión continúa únicamente con los resultados de los +buscadores restantes. La propia solicitud de búsqueda no produce ningún error. + +Sin embargo, los errores de sintaxis de consulta (``InvalidQueryException``) y la superación del +límite de paginación (``ResultOffsetExceededException``) son excepciones a esta regla: estos se +devuelven como errores tal cual. Además, en las páginas profundas en las que no se realiza la +fusión (donde ``posición de inicio × 2`` es mayor o igual que ``rank.fusion.window_size``), una +excepción producida en el buscador principal se devuelve tal cual como error de la solicitud de +búsqueda. + +El buscador semántico devuelve resultados vacíos cuando no puede conectarse al proveedor de +embeddings o cuando falla el procesamiento de los embeddings. También en este caso no se produce +ningún error, y solo se obtienen los resultados de la búsqueda por palabras clave. + Solución de problemas ===================== @@ -195,10 +324,20 @@ Los resultados de búsqueda difieren de lo esperado **Verificaciones**: -1. Verificar los resultados de cada tipo de búsqueda individualmente -2. Ajustar el valor de ``rank.fusion.rank_constant`` -3. Ajustar el valor de ``rank.fusion.window_size`` -4. En páginas profundas (donde ``posición de inicio × 2`` es mayor o igual que ``rank.fusion.window_size``), la fusión no se realiza y solo se utiliza el buscador principal. Si desea resultados fusionados en más páginas, aumente ``rank.fusion.window_size``. +1. Verificar el campo ``searcher`` (consulte "Verificación de los resultados de la fusión"). Si + todos los documentos muestran únicamente ``["default"]``, el buscador semántico no está + devolviendo resultados. +2. Comprobar si la búsqueda semántica se está omitiendo. Además de las consultas que contienen + sintaxis de búsqueda (``"``, ``:``, ``AND``, etc.), en los filtrados por etiqueta, orden o + faceta, en la búsqueda por ubicación y en la búsqueda de documentos similares, el buscador + semántico no devuelve resultados y solo se obtienen los de la búsqueda por palabras clave. + Consulte :doc:`search-semantic` para más detalles sobre las condiciones de omisión. +3. Verificar los resultados de cada tipo de búsqueda individualmente +4. Ajustar el valor de ``rank.fusion.rank_constant`` +5. En páginas profundas (donde ``posición de inicio × 2`` es mayor o igual que + ``rank.fusion.window_size``; de forma predeterminada, a partir del resultado 101), la fusión + no se realiza y solo se utiliza el buscador principal. Si desea resultados fusionados en más + páginas, aumente ``rank.fusion.window_size``. La búsqueda es lenta -------------------- @@ -207,13 +346,19 @@ La búsqueda es lenta **Soluciones**: -1. Reducir ``rank.fusion.window_size``:: +1. Ajustar ``rank.fusion.threads``:: - rank.fusion.window_size=100 + rank.fusion.threads=4 -2. Ajustar ``rank.fusion.threads``:: +2. Reducir ``rank.fusion.window_size``. Sin embargo, no puede quedar por debajo de su límite + inferior (``paging.search.page.max.size × 2``), por lo que en la configuración predeterminada + se deben establecer los dos ajustes siguientes conjuntamente:: - rank.fusion.threads=4 + paging.search.page.max.size=50 + rank.fusion.window_size=100 + + Tenga en cuenta que el número máximo de resultados que se pueden solicitar por página también + se reduce. Tras aplicar la configuración es necesario reiniciar. Memoria insuficiente -------------------- @@ -222,12 +367,13 @@ Memoria insuficiente **Soluciones**: -1. Reducir ``rank.fusion.window_size`` +1. Reducir ``rank.fusion.window_size`` siguiendo el mismo procedimiento que en "La búsqueda es lenta" 2. Aumentar el tamaño del heap de JVM Referencia ========== +- :doc:`search-semantic` - Configuración de la búsqueda semántica (chunking de contenido) - :doc:`scripting-overview` - Descripción general de scripting - :doc:`search-advanced` - Configuración avanzada de búsqueda - :doc:`llm-overview` - Guía de integración LLM (Búsqueda semántica) diff --git a/fr/15.8/config/rank-fusion.rst b/fr/15.8/config/rank-fusion.rst index d9e07b2b..6e40ae82 100644 --- a/fr/15.8/config/rank-fusion.rst +++ b/fr/15.8/config/rank-fusion.rst @@ -47,6 +47,13 @@ Formule :: - ``rank(d)`` : Rang du document d dans chaque résultat de recherche (base 0) - ``Σ`` : Somme sur tous les moteurs de recherche dans lesquels le document d apparaît +.. note:: + + L'algorithme de fusion est fixé à RRF : aucun réglage ne permet de basculer vers un autre + algorithme. La pondération par moteur de recherche n'est pas non plus prise en charge — la + contribution de chaque moteur est additionnée avec le même poids. Le seul paramètre permettant + d'ajuster la tendance du classement est ``rank.fusion.rank_constant``. + Configuration ============= @@ -64,7 +71,7 @@ Configuration de base :: rank.fusion.rank_constant=20 # Nombre de threads pour le traitement parallèle - # (si 0 ou moins, availableProcessors × 1.5 + 1 est utilisé) + # (si 0 ou moins, availableProcessors × 3 ÷ 2 + 1 est utilisé) rank.fusion.threads=-1 # Nom du champ de score (champ stockant le score fusionné) @@ -79,29 +86,56 @@ Configuration de base :: - Description * - ``rank.fusion.window_size`` - ``200`` - - Nombre maximum de résultats récupérés depuis chaque moteur de recherche pour la fusion. Doit être >= ``paging.search.page.max.size × 2`` (``200`` par défaut) ; si une valeur inférieure est définie, elle est automatiquement relevée à ce minimum. + - Nombre maximum de résultats récupérés depuis chaque moteur de recherche pour la fusion. Doit être >= ``paging.search.page.max.size × 2`` (``200`` par défaut) ; si une valeur inférieure est définie, elle est automatiquement relevée à ce minimum (un avertissement WARN est alors consigné au démarrage). * - ``rank.fusion.rank_constant`` - ``20`` - La constante ``k`` dans la formule RRF. Une valeur plus élevée réduit la différence de score entre les résultats mieux et moins bien classés. * - ``rank.fusion.threads`` - ``-1`` - - Nombre de threads utilisés lors de l'exécution parallèle de plusieurs moteurs de recherche. Si ``0`` ou moins est spécifié, ``availableProcessors × 1.5 + 1`` est utilisé automatiquement. + - Nombre de threads du pool de threads fixe utilisé pour exécuter plusieurs moteurs de recherche en parallèle. Si ``0`` ou moins est spécifié, ``availableProcessors × 3 ÷ 2 + 1`` est utilisé automatiquement (le calcul étant effectué en arithmétique entière, la partie décimale est tronquée ; par exemple : 4 cœurs → 7, 5 cœurs → 8). * - ``rank.fusion.score_field`` - ``rf_score`` - Nom du champ du document résultat utilisé pour stocker le score fusionné. +.. note:: + + **Moment de prise en compte des réglages** + + Les quatre réglages ci-dessus nécessitent tous un redémarrage de |Fess| pour que leur + modification prenne effet. Les valeurs lues depuis ``fess_config.properties`` sont mises en + cache dans la JVM : modifier le fichier pendant que |Fess| est en cours d'exécution reste donc + sans effet. + + À titre indicatif, ``rank.fusion.window_size`` n'est lu qu'une seule fois au démarrage, et + ``rank.fusion.threads`` au moment de la création du pool de threads. Le pool de threads étant + créé lorsqu'un moteur de recherche autre que ``default`` (le moteur de recherche sémantique, + par exemple) est enregistré, aucun pool n'est créé lorsque la recherche sémantique est + désactivée. + Propriétés système JVM ---------------------- -Les moteurs de recherche à utiliser sont spécifiés en tant que propriété système JVM. Ajoutez la ligne -suivante dans ``fess.in.sh`` (ou ``fess.in.bat``) :: +Les moteurs de recherche à utiliser sont spécifiés en tant que propriété système JVM. Ajoutez la +ligne suivante dans ``fess.in.sh`` :: - # Spécifier les moteurs de recherche (séparés par des virgules) - -Drank.fusion.searchers=default,semantic_chunk + FESS_JAVA_OPTS="$FESS_JAVA_OPTS -Drank.fusion.searchers=default,semantic_chunk" + +Pour ``fess.in.bat``, écrivez plutôt :: + + set FESS_JAVA_OPTS=%FESS_JAVA_OPTS% -Drank.fusion.searchers=default,semantic_chunk Ce paramètre se comporte comme suit : -- Il est défini en tant qu'option JVM, et non dans ``fess_config.properties``. +- Il est défini en tant qu'option JVM, et non dans ``fess_config.properties``. Le nom de la clé + doit être exactement ``rank.fusion.searchers``. Les formes préfixées couramment employées pour + les autres réglages, ``-Dfess.config.`` ou ``-Dfess.system.`` (par exemple + ``-Dfess.config.rank.fusion.searchers``), ne sont pas reconnues. +- À la place d'une option JVM, vous pouvez également le saisir sur une seule ligne, sous la forme + ``rank.fusion.searchers=default,semantic_chunk``, dans le champ « Propriétés système » de la + page « Système > Général » de l'interface d'administration. Notez que la valeur de ce champ + n'est appliquée que si aucune propriété système du même nom n'est déjà définie. Une option + ``-D`` est donc prioritaire, et modifier une valeur déjà appliquée nécessite un redémarrage de + |Fess|. - ``default`` est le moteur qui effectue la recherche standard par mots-clés ; il est toujours disponible. - Le nom d'un moteur de recherche est dérivé du nom de sa classe d'implémentation : on en retire le suffixe ``Searcher``, puis on convertit le reste en snake_case minuscule @@ -131,8 +165,69 @@ Intégration avec la recherche hybride Le Rank Fusion est particulièrement efficace pour la recherche hybride, qui combine la recherche par mots-clés et la recherche sémantique. Pour utiliser la recherche sémantique, -configurez la fonctionnalité de chunking de contenu et définissez -``content_chunker.search.enabled=true``. Voir :doc:`search-semantic` pour plus de détails. +configurez la fonctionnalité de chunking de contenu, puis définissez +``content_chunker.search.enabled=true``. + +.. warning:: + + Les réglages ``content_chunker.*``, tels que ``content_chunker.enabled`` ou + ``content_chunker.search.enabled``, sont des **propriétés système** et non des réglages de + ``fess_config.properties``. Définissez-les dans ``conf/system.properties``, ou fournissez-les + en tant qu'option JVM sous la forme ``-Dfess.system.content_chunker.search.enabled=true``. + Les écrire dans ``fess_config.properties`` reste sans effet. Par ailleurs, + ``content_chunker.search.enabled`` n'étant évalué qu'au démarrage, un redémarrage de |Fess| + est nécessaire après son activation. + +Voir :doc:`search-semantic` pour plus de détails. + +Vérification des résultats de fusion +====================================== + +Deux champs ajoutés aux résultats de recherche permettent de vérifier que le Rank Fusion est +réellement à l'œuvre. + +.. list-table:: + :header-rows: 1 + :widths: 20 80 + + * - Champ + - Contenu + * - ``searcher`` + - Tableau des noms des moteurs de recherche ayant récupéré le document (par exemple ``["default", "semantic_chunk"]``). Lorsque les deux y figurent, le document a été trouvé à la fois par la recherche par mots-clés et par la recherche sémantique. + * - ``rf_score`` + - Score fusionné calculé par RRF. Le nom du champ peut être modifié via ``rank.fusion.score_field``. + +Ces deux valeurs sont ajoutées dynamiquement au moment de la recherche et ne sont pas stockées +dans l'index. Elles ne figurent pas non plus par défaut dans la réponse de ``/api/v2/search`` : +pour les consulter, ajoutez la ligne suivante dans ``fess_config.properties``, puis redémarrez +|Fess| :: + + query.additional.api.response.fields=rf_score,searcher + +.. note:: + + ``query.additional.api.response.fields`` ajoute des entrées à la liste blanche des champs + autorisés dans la réponse de l'API de recherche v2. N'y ajoutez pas de champs de contrôle + d'accès tels que ``role`` ou ``virtual_host`` : les informations de contrôle d'accès seraient + alors exposées dans la réponse de l'API de recherche. + +Impact sur le nombre de résultats +=================================== + +Lorsque le Rank Fusion est exécuté, le nombre total de résultats retourné n'est pas celui du +moteur principal (le moteur ``default``, enregistré en tête de liste) tel quel : il est corrigé +comme suit :: + + nombre total de résultats = nombre total de résultats du moteur principal + correction + +La correction correspond au nombre de documents figurant parmi les ``window_size ÷ 2`` premiers +résultats fusionnés, mais absents des ``window_size ÷ 2`` premiers résultats du moteur principal. +Autrement dit, le nombre de résultats augmente du nombre de documents trouvés uniquement par la +recherche sémantique. Pour une même requête, le nombre de résultats peut donc varier selon que la +recherche hybride est activée ou non. + +À noter : lorsque le nombre total de résultats du moteur principal est retourné sous forme de +valeur approchée (borne inférieure), cette correction n'est pas appliquée. Exemples d'utilisation ======================= @@ -168,13 +263,26 @@ Utilisation de la mémoire -------------------------- - L'utilisation de la mémoire augmente car plusieurs résultats de recherche sont conservés. -- Utilisez ``rank.fusion.window_size`` pour limiter le nombre maximum de résultats à fusionner. Le moteur principal (le moteur ``default`` en tête de liste) récupère jusqu'à ``window_size`` résultats, tandis que chacun des autres moteurs récupère ``window_size ÷ nombre de moteurs`` résultats. +- Utilisez ``rank.fusion.window_size`` pour limiter le nombre maximum de résultats à fusionner. Le moteur principal (le moteur ``default`` en tête de liste) récupère jusqu'à ``window_size`` résultats, tandis que chacun des autres moteurs récupère ``window_size ÷ nombre de moteurs`` résultats (le ``nombre de moteurs`` correspond au total, moteur principal inclus, et la division est tronquée). +- Par exemple, avec deux moteurs (``default`` et ``semantic_chunk``) et ``window_size=200``, le moteur principal récupère 200 résultats et le moteur sémantique 100 : au maximum 300 documents sont donc conservés. :: # Taille de la fenêtre pour la fusion rank.fusion.window_size=200 +.. warning:: + + ``rank.fusion.window_size`` ne peut pas descendre en dessous de + ``paging.search.page.max.size × 2``. Lorsque ``paging.search.page.max.size`` conserve sa valeur + par défaut ``100``, la borne inférieure vaut ``200``, soit exactement la valeur par défaut de + ``rank.fusion.window_size``. Autrement dit, **dans la configuration par défaut, window_size ne + peut pas être réduit en dessous de sa valeur par défaut**. Si une valeur plus petite est + définie, un avertissement WARN est consigné au démarrage et la valeur est relevée à ``200``. + Pour la réduire réellement, il faut d'abord abaisser ``paging.search.page.max.size``, ce qui + réduit du même coup le nombre maximum de résultats qu'un client peut demander par page dans + l'écran de recherche comme dans l'API. + Temps de traitement -------------------- @@ -184,9 +292,32 @@ Temps de traitement :: # Nombre de threads pour l'exécution parallèle - # (si 0 ou moins, availableProcessors × 1.5 + 1) + # (si 0 ou moins, availableProcessors × 3 ÷ 2 + 1) rank.fusion.threads=-1 +.. note:: + + Aucun délai d'expiration n'est appliqué à l'exécution des moteurs de recherche. Si l'un d'eux + ne répond pas, la requête de recherche attend qu'il ait terminé. + +Comportement en cas d'échec d'un moteur de recherche +====================================================== + +Lorsqu'un moteur de recherche échoue sur une exception, ses résultats sont traités comme vides : +un avertissement WARN est consigné, puis la fusion se poursuit avec les seuls résultats des autres +moteurs. La requête de recherche elle-même n'échoue pas. + +Font toutefois exception les erreurs de syntaxe de requête (``InvalidQueryException``) et les +dépassements de la limite de pagination (``ResultOffsetExceededException``) : celles-ci sont +retournées telles quelles en tant qu'erreurs. Par ailleurs, sur les pages profondes où la fusion +n'est pas effectuée (où ``position de début × 2`` est supérieur ou égal à +``rank.fusion.window_size``), une exception levée par le moteur principal est retournée telle +quelle en tant qu'erreur de la requête de recherche. + +Le moteur de recherche sémantique retourne des résultats vides lorsqu'il ne parvient pas à joindre +le fournisseur d'embedding ou que le calcul des embeddings échoue. Là encore, aucune erreur n'est +levée : seuls les résultats de la recherche par mots-clés sont retournés. + Dépannage ========= @@ -197,10 +328,21 @@ Les résultats de recherche diffèrent des attentes **Vérifications** : -1. Vérifier les résultats de chaque type de recherche individuellement -2. Ajuster la valeur de ``rank.fusion.rank_constant`` -3. Ajuster la valeur de ``rank.fusion.window_size`` -4. Sur les pages profondes (où ``position de début × 2`` est supérieur ou égal à ``rank.fusion.window_size``), la fusion n'est pas effectuée et seul le moteur principal est utilisé. Pour obtenir des résultats fusionnés sur davantage de pages, augmentez ``rank.fusion.window_size``. +1. Vérifier le champ ``searcher`` (voir « Vérification des résultats de fusion »). Si tous les + documents ne contiennent que ``["default"]``, le moteur de recherche sémantique ne retourne + aucun résultat. +2. Vérifier que la recherche sémantique n'est pas ignorée. Outre les requêtes contenant une + syntaxe de recherche (``"``, ``:``, ``AND``, etc.), le filtrage par label, par tri ou par + facette, la recherche par géolocalisation et la recherche de documents similaires font que le + moteur de recherche sémantique ne retourne aucun résultat : seuls les résultats de la + recherche par mots-clés sont alors renvoyés. Voir :doc:`search-semantic` pour le détail des + conditions d'exclusion. +3. Vérifier les résultats de chaque type de recherche individuellement +4. Ajuster la valeur de ``rank.fusion.rank_constant`` +5. Sur les pages profondes (où ``position de début × 2`` est supérieur ou égal à + ``rank.fusion.window_size``, soit à partir du 101e résultat avec les valeurs par défaut), la + fusion n'est pas effectuée et seul le moteur principal est utilisé. Pour obtenir des résultats + fusionnés sur davantage de pages, augmentez ``rank.fusion.window_size``. La recherche est lente ----------------------- @@ -209,13 +351,19 @@ La recherche est lente **Solutions** : -1. Réduire ``rank.fusion.window_size`` :: +1. Ajuster ``rank.fusion.threads`` :: - rank.fusion.window_size=100 + rank.fusion.threads=4 -2. Ajuster ``rank.fusion.threads`` :: +2. Réduire ``rank.fusion.window_size``. Cette valeur ne pouvant pas descendre en dessous de sa + borne inférieure (``paging.search.page.max.size × 2``), les deux réglages suivants doivent être + définis ensemble dans la configuration par défaut :: - rank.fusion.threads=4 + paging.search.page.max.size=50 + rank.fusion.window_size=100 + + Notez que le nombre maximum de résultats pouvant être demandés par page diminue lui aussi. Un + redémarrage est nécessaire après ces modifications. Mémoire insuffisante --------------------- @@ -224,12 +372,14 @@ Mémoire insuffisante **Solutions** : -1. Réduire ``rank.fusion.window_size`` +1. Réduire ``rank.fusion.window_size`` en suivant la même procédure que dans « La recherche est + lente » 2. Augmenter la taille du tas JVM Référence ========= +- :doc:`search-semantic` - Configuration de la recherche sémantique (chunking de contenu) - :doc:`scripting-overview` - Aperçu du scripting - :doc:`search-advanced` - Configuration avancée de la recherche - :doc:`llm-overview` - Guide d'intégration LLM (Recherche sémantique) diff --git a/ja/15.8/config/rank-fusion.rst b/ja/15.8/config/rank-fusion.rst index cc50dfdd..8b11a42c 100644 --- a/ja/15.8/config/rank-fusion.rst +++ b/ja/15.8/config/rank-fusion.rst @@ -45,6 +45,12 @@ RRFは、各検索結果におけるドキュメントの順位の逆数を合 - ``rank(d)``: 各検索結果におけるドキュメントdの順位(0始まり) - ``Σ``: ドキュメントdが出現したすべてのサーチャーにわたる合計 +.. note:: + + 融合アルゴリズムはRRF固定で、他のアルゴリズムに切り替える設定はありません。 + また、サーチャーごとの重み付けもサポートしていません。各サーチャーの寄与は同じ重みで + 合計されます。ランキングの傾向を調整できるのは ``rank.fusion.rank_constant`` のみです。 + 設定 ==== @@ -61,7 +67,7 @@ fess_config.properties # RRFのrank_constant(kパラメーター) rank.fusion.rank_constant=20 - # 並列処理のスレッド数(0以下の場合、利用可能なCPUコア数 × 1.5 + 1 が使用されます) + # 並列処理のスレッド数(0以下の場合、利用可能なCPUコア数 × 3 ÷ 2 + 1 が使用されます) rank.fusion.threads=-1 # スコアフィールド名(融合後のスコアを格納するフィールド) @@ -76,29 +82,52 @@ fess_config.properties - 説明 * - ``rank.fusion.window_size`` - ``200`` - - 融合対象として各サーチャーから取得する結果の最大件数。\ ``paging.search.page.max.size × 2``\ (デフォルトでは ``200``)以上である必要があり、下回る場合はこの最小値に自動的に引き上げられます。 + - 融合対象として各サーチャーから取得する結果の最大件数。\ ``paging.search.page.max.size × 2``\ (デフォルトでは ``200``)以上である必要があり、下回る場合はこの最小値に自動的に引き上げられます(起動時にWARNログを出力)。 * - ``rank.fusion.rank_constant`` - ``20`` - RRF計算式における定数 ``k``\ 。値を大きくすると、上位と下位の順位の差によるスコア差が小さくなります。 * - ``rank.fusion.threads`` - ``-1`` - - 複数サーチャーを並列実行する際のスレッド数。\ ``0`` 以下を指定すると ``利用可能なCPUコア数 × 1.5 + 1`` が自動的に使用されます。 + - 複数サーチャーを並列実行する固定スレッドプールのスレッド数。\ ``0`` 以下を指定すると ``利用可能なCPUコア数 × 3 ÷ 2 + 1`` が自動的に使用されます(整数演算のため小数点以下は切り捨て。例: 4コア→7、5コア→8)。 * - ``rank.fusion.score_field`` - ``rf_score`` - 融合後のスコアを格納する結果ドキュメントのフィールド名。 +.. note:: + + **設定の反映タイミング** + + 上記4つの設定は、いずれも変更の反映に |Fess| の再起動が必要です。\ ``fess_config.properties`` + から読み込まれた値はJVM内にキャッシュされるため、稼働中にファイルを書き換えても反映されません。 + + なお ``rank.fusion.window_size`` は起動時に一度だけ、\ ``rank.fusion.threads`` は + スレッドプールを作成する時点で読み込まれます。スレッドプールは ``default`` 以外のサーチャー + (セマンティックサーチャーなど)が登録されたときに作成されるため、セマンティック検索が + 無効な場合はスレッドプール自体が作成されません。 + JVMシステムプロパティ --------------------- 使用するサーチャーは、JVMシステムプロパティで指定します。 -``fess.in.sh`` (または ``fess.in.bat``) に以下のように記述します:: +``fess.in.sh`` に以下のように記述します:: - # 使用するサーチャーの指定(カンマ区切り) - -Drank.fusion.searchers=default,semantic_chunk + FESS_JAVA_OPTS="$FESS_JAVA_OPTS -Drank.fusion.searchers=default,semantic_chunk" + +``fess.in.bat`` の場合は次のように記述します:: + + set FESS_JAVA_OPTS=%FESS_JAVA_OPTS% -Drank.fusion.searchers=default,semantic_chunk このプロパティの動作は以下のとおりです: -- ``fess_config.properties`` ではなく、JVMオプションとして設定します。 +- ``fess_config.properties`` ではなく、JVMオプションとして設定します。キー名は + ``rank.fusion.searchers`` そのものを指定してください。他の設定でよく使われる + ``-Dfess.config.`` や ``-Dfess.system.`` を付けた形式(``-Dfess.config.rank.fusion.searchers`` + など)は認識されません。 +- JVMオプションの代わりに、管理画面の「システム > 全般」にある「システムプロパティ」欄へ + ``rank.fusion.searchers=default,semantic_chunk`` のように1行で記述することもできます。 + ただしこの欄の値は、同名のシステムプロパティがまだ設定されていない場合にのみ適用されます。 + そのため ``-D`` で指定済みの場合はJVMオプションが優先され、いったん適用された値を変更する + 場合は |Fess| の再起動が必要です。 - ``default`` は標準のキーワード検索を行うサーチャーで、常に利用できます。 - サーチャー名は、実装クラス名から ``Searcher`` を取り除き、スネークケースの小文字に変換した ものです(``SemanticChunkSearcher`` → ``semantic_chunk``)。コア内蔵のセマンティック @@ -124,9 +153,64 @@ JVMシステムプロパティ Rank Fusionは、キーワード検索とセマンティック検索を組み合わせた ハイブリッド検索で特に効果を発揮します。 -セマンティック検索を利用するには、コンテンツチャンク機能を設定し、 -``content_chunker.search.enabled=true`` を設定します。詳細は :doc:`search-semantic` を -参照してください。 +セマンティック検索を利用するには、コンテンツチャンク機能を設定したうえで +``content_chunker.search.enabled=true`` を設定します。 + +.. warning:: + + ``content_chunker.enabled`` や ``content_chunker.search.enabled`` などの + ``content_chunker.*`` の設定は、``fess_config.properties`` ではなく + **システムプロパティ** です。\ ``conf/system.properties`` に記述するか、 + ``-Dfess.system.content_chunker.search.enabled=true`` のようにJVMオプションとして + 指定してください。\ ``fess_config.properties`` に記述しても反映されません。 + また ``content_chunker.search.enabled`` は起動時にのみ評価されるため、 + 有効化後は |Fess| の再起動が必要です。 + +詳細は :doc:`search-semantic` を参照してください。 + +融合結果の確認 +============== + +Rank Fusionが実際に動作しているかは、検索結果に付与される以下の2つのフィールドで確認できます。 + +.. list-table:: + :header-rows: 1 + :widths: 20 80 + + * - フィールド + - 内容 + * - ``searcher`` + - そのドキュメントを取得したサーチャー名の配列(例: ``["default", "semantic_chunk"]``)。両方が含まれていれば、キーワード検索とセマンティック検索の双方でヒットしたことを意味します。 + * - ``rf_score`` + - RRFで算出した融合後のスコア。フィールド名は ``rank.fusion.score_field`` で変更できます。 + +どちらも検索時に動的に付与される値で、インデックスには保存されません。 +また、既定では ``/api/v2/search`` のレスポンスに含まれないため、確認するには +``fess_config.properties`` に以下を設定して |Fess| を再起動してください:: + + query.additional.api.response.fields=rf_score,searcher + +.. note:: + + ``query.additional.api.response.fields`` は、v2検索APIのレスポンスに含めてよい + フィールドの許可リストに項目を追加する設定です。\ ``role`` や ``virtual_host`` などの + アクセス制御用フィールドを追加すると、アクセス制御情報が検索APIの応答に露出するため、 + 追加しないでください。 + +ヒット件数への影響 +================== + +Rank Fusionが実行されると、返される総ヒット件数はメインサーチャー(先頭に登録された +``default`` サーチャー)の件数そのままではなく、次のように補正されます:: + + 総ヒット件数 = メインサーチャーの総ヒット件数 + 補正値 + +補正値は、融合後の上位 ``window_size ÷ 2`` 件のうち、メインサーチャーの上位 +``window_size ÷ 2`` 件に含まれていなかったドキュメントの件数です。つまり、セマンティック検索 +だけが見つけたドキュメントの分だけ件数が増えます。 +そのため、同じクエリでもハイブリッド検索の有効・無効でヒット件数が変わることがあります。 + +なお、メインサーチャーの総ヒット件数が概算値(下限値)として返される場合、この補正は行われません。 使用例 ====== @@ -162,13 +246,23 @@ Rank Fusionは、キーワード検索とセマンティック検索を組み合 ------------ - 複数の検索結果を保持するため、メモリ使用量が増加します。 -- ``rank.fusion.window_size`` で融合対象の最大件数を制限できます。メインサーチャー(先頭の ``default`` サーチャー)は最大で ``window_size`` 件、その他のサーチャーはそれぞれ ``window_size ÷ サーチャー数`` 件を取得します。 +- ``rank.fusion.window_size`` で融合対象の最大件数を制限できます。メインサーチャー(先頭の ``default`` サーチャー)は最大で ``window_size`` 件、その他のサーチャーはそれぞれ ``window_size ÷ サーチャー数`` 件を取得します(``サーチャー数`` はメインサーチャーを含む総数で、除算は切り捨てです)。 +- 例えばサーチャーが2つ(``default`` と ``semantic_chunk``)で ``window_size=200`` の場合、メインサーチャーが200件、セマンティックサーチャーが100件を取得するため、保持されるドキュメントは最大300件になります。 :: # 融合対象のウィンドウサイズ rank.fusion.window_size=200 +.. warning:: + + ``rank.fusion.window_size`` は ``paging.search.page.max.size × 2`` を下回れません。 + ``paging.search.page.max.size`` が既定の ``100`` の場合、下限は ``200`` となり、これは + ``rank.fusion.window_size`` の既定値と同じです。つまり **既定の構成では window_size を + 既定値より小さくできません**\ 。小さい値を設定しても起動時にWARNログが出力され、``200`` + に引き上げられます。実際に小さくするには ``paging.search.page.max.size`` を先に下げる + 必要がありますが、これは検索画面やAPIで1ページに要求できる最大件数も同時に下がります。 + 処理時間 -------- @@ -177,9 +271,29 @@ Rank Fusionは、キーワード検索とセマンティック検索を組み合 :: - # 並列実行のスレッド数(0以下の場合、利用可能なCPUコア数 × 1.5 + 1) + # 並列実行のスレッド数(0以下の場合、利用可能なCPUコア数 × 3 ÷ 2 + 1) rank.fusion.threads=-1 +.. note:: + + サーチャーの実行にタイムアウトは設定されていません。応答が返らないサーチャーがあると、 + 検索リクエストはその完了まで待機します。 + +サーチャー障害時の動作 +====================== + +いずれかのサーチャーが例外で失敗した場合、そのサーチャーの結果は空として扱われ、 +WARNログを出力したうえで、残りのサーチャーの結果だけで融合が続行されます。 +検索リクエスト自体はエラーになりません。 + +ただし、クエリ構文エラー(``InvalidQueryException``)とページング上限超過 +(``ResultOffsetExceededException``)は例外で、これらはそのままエラーとして返されます。 +また、融合が行われない深いページ(``開始位置 × 2`` が ``rank.fusion.window_size`` 以上に +なる位置)では、メインサーチャーで発生した例外はそのまま検索リクエストのエラーになります。 + +セマンティックサーチャーは、埋め込みプロバイダに接続できない場合や埋め込み処理に失敗した場合、 +結果を空として返します。この場合もエラーにはならず、キーワード検索のみの結果になります。 + トラブルシューティング ====================== @@ -190,10 +304,17 @@ Rank Fusionは、キーワード検索とセマンティック検索を組み合 **確認事項**: -1. 各検索タイプの結果を個別に確認 -2. ``rank.fusion.rank_constant`` の値を調整 -3. ``rank.fusion.window_size`` の値を調整 -4. 深いページ(``開始位置 × 2`` が ``rank.fusion.window_size`` 以上になる位置)では融合が行われず、メインサーチャーのみで検索されます。より多くのページで融合結果を利用したい場合は ``rank.fusion.window_size`` を大きくしてください。 +1. ``searcher`` フィールドを確認する(「融合結果の確認」を参照)。すべてのドキュメントが + ``["default"]`` のみの場合、セマンティックサーチャーが結果を返していません。 +2. セマンティック検索がスキップされていないか確認する。検索構文(``"`` ``:`` ``AND`` など)を + 含むクエリのほか、ラベル・ソート・ファセットによる絞り込み、位置情報検索、類似ドキュメント検索 + では、セマンティックサーチャーは結果を返さずキーワード検索のみの結果になります。 + スキップ条件の詳細は :doc:`search-semantic` を参照してください。 +3. 各検索タイプの結果を個別に確認 +4. ``rank.fusion.rank_constant`` の値を調整 +5. 深いページ(``開始位置 × 2`` が ``rank.fusion.window_size`` 以上になる位置。既定では + 101件目以降)では融合が行われず、メインサーチャーのみで検索されます。より多くのページで + 融合結果を利用したい場合は ``rank.fusion.window_size`` を大きくしてください。 検索が遅い ---------- @@ -202,13 +323,17 @@ Rank Fusionは、キーワード検索とセマンティック検索を組み合 **解決方法**: -1. ``rank.fusion.window_size`` を減らす:: +1. ``rank.fusion.threads`` を調整する:: - rank.fusion.window_size=100 + rank.fusion.threads=4 -2. ``rank.fusion.threads`` を調整:: +2. ``rank.fusion.window_size`` を減らす。ただし下限(``paging.search.page.max.size × 2``) + を下回れないため、既定の構成では次の2つをセットで設定します:: - rank.fusion.threads=4 + paging.search.page.max.size=50 + rank.fusion.window_size=100 + + 1ページに要求できる最大件数も下がる点に注意してください。設定後は再起動が必要です。 メモリ不足 ---------- @@ -217,12 +342,13 @@ Rank Fusionは、キーワード検索とセマンティック検索を組み合 **解決方法**: -1. ``rank.fusion.window_size`` を減らす +1. 「検索が遅い」と同じ手順で ``rank.fusion.window_size`` を減らす 2. JVMヒープサイズを増やす 参考情報 ======== +- :doc:`search-semantic` - セマンティック検索(コンテンツチャンク)の設定 - :doc:`scripting-overview` - スクリプティング概要 - :doc:`search-advanced` - 検索の詳細設定 - :doc:`llm-overview` - LLM統合ガイド(セマンティック検索) diff --git a/ko/15.8/config/rank-fusion.rst b/ko/15.8/config/rank-fusion.rst index 02c5d836..cc375691 100644 --- a/ko/15.8/config/rank-fusion.rst +++ b/ko/15.8/config/rank-fusion.rst @@ -45,6 +45,12 @@ RRF는 각 검색 결과에서 문서의 순위 역수를 합산하여 스코어 - ``rank(d)``: 각 검색 결과에서 문서 d의 순위 (0부터 시작) - ``Σ``: 문서 d가 등장한 모든 검색기에 걸친 합계 +.. note:: + + 융합 알고리즘은 RRF로 고정되어 있으며, 다른 알고리즘으로 전환하는 설정은 없습니다. + 또한 검색기별 가중치도 지원하지 않습니다. 각 검색기의 기여도는 동일한 가중치로 + 합산됩니다. 랭킹 경향을 조정할 수 있는 것은 ``rank.fusion.rank_constant`` 뿐입니다. + 설정 ==== @@ -61,7 +67,7 @@ fess_config.properties # RRF의 rank_constant (k 파라미터) rank.fusion.rank_constant=20 - # 병렬 처리 스레드 수 (0 이하인 경우 availableProcessors × 1.5 + 1 이 사용됩니다) + # 병렬 처리 스레드 수 (0 이하인 경우 availableProcessors × 3 ÷ 2 + 1 이 사용됩니다) rank.fusion.threads=-1 # 스코어 필드명 (융합 후 스코어를 저장하는 필드) @@ -76,29 +82,52 @@ fess_config.properties - 설명 * - ``rank.fusion.window_size`` - ``200`` - - 융합 대상으로 각 검색기에서 가져오는 결과의 최대 건수. ``paging.search.page.max.size × 2`` (기본값은 ``200``) 이상이어야 하며, 작은 값이 설정된 경우 자동으로 최소값으로 올려집니다. + - 융합 대상으로 각 검색기에서 가져오는 결과의 최대 건수. ``paging.search.page.max.size × 2`` (기본값은 ``200``) 이상이어야 하며, 작은 값이 설정된 경우 자동으로 최소값으로 올려집니다(시작 시 WARN 로그가 출력됩니다). * - ``rank.fusion.rank_constant`` - ``20`` - RRF 계산식의 상수 ``k``. 값을 크게 할수록 상위 순위와 하위 순위 간의 스코어 차이가 작아집니다. * - ``rank.fusion.threads`` - ``-1`` - - 여러 검색기를 병렬 실행할 때의 스레드 수. ``0`` 이하를 지정하면 ``availableProcessors × 1.5 + 1`` 이 자동으로 사용됩니다. + - 여러 검색기를 병렬 실행하는 고정 스레드 풀의 스레드 수. ``0`` 이하를 지정하면 ``availableProcessors × 3 ÷ 2 + 1`` 이 자동으로 사용됩니다(정수 연산이므로 소수점 이하는 버림. 예: 4코어 → 7, 5코어 → 8). * - ``rank.fusion.score_field`` - ``rf_score`` - 융합 후 스코어를 저장하는 결과 문서의 필드명. +.. note:: + + **설정 반영 시점** + + 위 4개 설정은 모두 변경 사항을 반영하려면 |Fess|\ 를 재시작해야 합니다. + ``fess_config.properties`` 에서 읽어들인 값은 JVM 내에 캐시되므로, 가동 중에 파일을 + 수정해도 반영되지 않습니다. + + 참고로 ``rank.fusion.window_size`` 는 시작 시 한 번만, ``rank.fusion.threads`` 는 + 스레드 풀을 생성하는 시점에 읽힙니다. 스레드 풀은 ``default`` 이외의 검색기(시맨틱 서처 등)가 + 등록될 때 생성되므로, 시맨틱 검색이 비활성화되어 있으면 스레드 풀 자체가 생성되지 않습니다. + JVM 시스템 프로퍼티 ------------------- 사용할 검색기는 JVM 시스템 프로퍼티로 지정합니다. -``fess.in.sh`` (또는 ``fess.in.bat``) 에 다음과 같이 작성합니다:: +``fess.in.sh`` 에 다음과 같이 작성합니다:: - # 사용할 검색기 지정 (쉼표 구분) - -Drank.fusion.searchers=default,semantic_chunk + FESS_JAVA_OPTS="$FESS_JAVA_OPTS -Drank.fusion.searchers=default,semantic_chunk" + +``fess.in.bat`` 의 경우에는 다음과 같이 작성합니다:: + + set FESS_JAVA_OPTS=%FESS_JAVA_OPTS% -Drank.fusion.searchers=default,semantic_chunk 이 프로퍼티의 동작은 다음과 같습니다: -- ``fess_config.properties`` 가 아닌 JVM 옵션으로 설정합니다. +- ``fess_config.properties`` 가 아닌 JVM 옵션으로 설정합니다. 키 이름은 + ``rank.fusion.searchers`` 그 자체를 지정하세요. 다른 설정에서 흔히 사용되는 + ``-Dfess.config.`` 나 ``-Dfess.system.`` 을 붙인 형식(``-Dfess.config.rank.fusion.searchers`` + 등)은 인식되지 않습니다. +- JVM 옵션 대신 관리 화면의 "시스템 > 일반"에 있는 "시스템 속성" 칸에 + ``rank.fusion.searchers=default,semantic_chunk`` 와 같이 한 줄로 기술할 수도 있습니다. + 다만 이 칸의 값은 같은 이름의 시스템 프로퍼티가 아직 설정되어 있지 않은 경우에만 적용됩니다. + 따라서 ``-D`` 로 이미 지정되어 있으면 JVM 옵션이 우선하며, 한 번 적용된 값을 변경하려면 + |Fess|\ 를 재시작해야 합니다. - ``default`` 는 표준 키워드 검색을 수행하는 검색기로 항상 사용할 수 있습니다. - 검색기 이름은 구현 클래스명에서 끝의 ``Searcher`` 를 제거한 뒤 스네이크 케이스 소문자로 변환한 형태입니다(``SemanticChunkSearcher`` → ``semantic_chunk``). 코어에 통합된 시맨틱 @@ -125,8 +154,64 @@ JVM 시스템 프로퍼티 Rank Fusion은 키워드 검색과 시맨틱 검색을 결합한 하이브리드 검색에서 특히 효과적입니다. -시맨틱 검색을 사용하려면 콘텐츠 청킹 기능을 설정하고 ``content_chunker.search.enabled=true`` 를 -설정하세요. 자세한 내용은 :doc:`search-semantic` 을 참조하세요. +시맨틱 검색을 사용하려면 콘텐츠 청킹 기능을 설정한 뒤 +``content_chunker.search.enabled=true`` 를 설정하세요. + +.. warning:: + + ``content_chunker.enabled`` 나 ``content_chunker.search.enabled`` 등 + ``content_chunker.*`` 설정은 ``fess_config.properties`` 가 아니라 + **시스템 프로퍼티**\ 입니다. ``conf/system.properties`` 에 작성하거나 + ``-Dfess.system.content_chunker.search.enabled=true`` 와 같이 JVM 옵션으로 + 지정하세요. ``fess_config.properties`` 에 작성해도 반영되지 않습니다. + 또한 ``content_chunker.search.enabled`` 는 시작 시에만 평가되므로 + 활성화한 뒤에는 |Fess|\ 를 재시작해야 합니다. + +자세한 내용은 :doc:`search-semantic` 을 참조하세요. + +융합 결과 확인 +=============== + +Rank Fusion이 실제로 동작하고 있는지는 검색 결과에 부여되는 다음 두 가지 필드로 확인할 수 있습니다. + +.. list-table:: + :header-rows: 1 + :widths: 20 80 + + * - 필드 + - 내용 + * - ``searcher`` + - 해당 문서를 가져온 검색기 이름의 배열(예: ``["default", "semantic_chunk"]``). 양쪽이 모두 포함되어 있으면 키워드 검색과 시맨틱 검색 양쪽에서 히트했다는 의미입니다. + * - ``rf_score`` + - RRF로 산출한 융합 후 스코어. 필드명은 ``rank.fusion.score_field`` 로 변경할 수 있습니다. + +둘 다 검색 시 동적으로 부여되는 값이며 인덱스에는 저장되지 않습니다. +또한 기본적으로는 ``/api/v2/search`` 응답에 포함되지 않으므로, 확인하려면 +``fess_config.properties`` 에 다음을 설정하고 |Fess|\ 를 재시작하세요:: + + query.additional.api.response.fields=rf_score,searcher + +.. note:: + + ``query.additional.api.response.fields`` 는 v2 검색 API 응답에 포함해도 되는 + 필드의 허용 목록에 항목을 추가하는 설정입니다. ``role`` 이나 ``virtual_host`` 등 + 접근 제어용 필드를 추가하면 접근 제어 정보가 검색 API 응답에 노출되므로 + 추가하지 마세요. + +히트 건수에 대한 영향 +====================== + +Rank Fusion이 실행되면 반환되는 총 히트 건수는 메인 검색기(맨 앞에 등록된 +``default`` 검색기)의 건수 그대로가 아니라 다음과 같이 보정됩니다:: + + 총 히트 건수 = 메인 검색기의 총 히트 건수 + 보정값 + +보정값은 융합 후 상위 ``window_size ÷ 2`` 건 중에서 메인 검색기의 상위 +``window_size ÷ 2`` 건에 포함되어 있지 않았던 문서의 건수입니다. 즉, 시맨틱 검색만 +찾아낸 문서의 수만큼 건수가 늘어납니다. +그래서 같은 쿼리라도 하이브리드 검색의 활성화 여부에 따라 히트 건수가 달라질 수 있습니다. + +또한 메인 검색기의 총 히트 건수가 개략값(하한값)으로 반환되는 경우에는 이 보정이 수행되지 않습니다. 사용 예 ======== @@ -162,13 +247,24 @@ Rank Fusion은 키워드 검색과 시맨틱 검색을 결합한 -------------- - 여러 검색 결과를 보유하므로 메모리 사용량이 증가합니다. -- ``rank.fusion.window_size`` 로 융합 대상 최대 건수를 제한할 수 있습니다. 메인 검색기(맨 앞의 ``default`` 검색기)는 최대 ``window_size`` 건, 그 외의 검색기는 각각 ``window_size ÷ 검색기 수`` 건을 가져옵니다. +- ``rank.fusion.window_size`` 로 융합 대상 최대 건수를 제한할 수 있습니다. 메인 검색기(맨 앞의 ``default`` 검색기)는 최대 ``window_size`` 건, 그 외의 검색기는 각각 ``window_size ÷ 검색기 수`` 건을 가져옵니다(``검색기 수`` 는 메인 검색기를 포함한 총 개수이며, 나눗셈은 버림입니다). +- 예를 들어 검색기가 2개(``default`` 와 ``semantic_chunk``)이고 ``window_size=200`` 인 경우, 메인 검색기가 200건, 시맨틱 서처가 100건을 가져오므로 보유되는 문서는 최대 300건이 됩니다. :: # 융합 대상 윈도우 사이즈 rank.fusion.window_size=200 +.. warning:: + + ``rank.fusion.window_size`` 는 ``paging.search.page.max.size × 2`` 보다 작을 수 없습니다. + ``paging.search.page.max.size`` 가 기본값 ``100`` 인 경우 하한은 ``200`` 이 되며, 이는 + ``rank.fusion.window_size`` 의 기본값과 동일합니다. 즉 **기본 구성에서는 window_size 를 + 기본값보다 작게 설정할 수 없습니다**. 더 작은 값을 설정해도 시작 시 WARN 로그가 출력되고 + ``200`` 으로 올려집니다. 실제로 더 작게 하려면 ``paging.search.page.max.size`` 를 먼저 + 낮춰야 하지만, 이렇게 하면 검색 화면이나 API에서 한 페이지에 요청할 수 있는 최대 건수도 + 함께 낮아집니다. + 처리 시간 ---------- @@ -177,9 +273,29 @@ Rank Fusion은 키워드 검색과 시맨틱 검색을 결합한 :: - # 병렬 실행 스레드 수 (0 이하인 경우 availableProcessors × 1.5 + 1) + # 병렬 실행 스레드 수 (0 이하인 경우 availableProcessors × 3 ÷ 2 + 1) rank.fusion.threads=-1 +.. note:: + + 검색기 실행에는 타임아웃이 설정되어 있지 않습니다. 응답을 반환하지 않는 검색기가 있으면 + 검색 요청은 그 검색기가 완료될 때까지 대기합니다. + +검색기 장애 시 동작 +==================== + +검색기 중 하나가 예외로 실패한 경우, 해당 검색기의 결과는 비어 있는 것으로 처리되며 +WARN 로그를 출력한 뒤 나머지 검색기의 결과만으로 융합이 계속 진행됩니다. +검색 요청 자체는 오류가 되지 않습니다. + +다만 쿼리 구문 오류(``InvalidQueryException``)와 페이징 상한 초과 +(``ResultOffsetExceededException``)는 예외이며, 이들은 그대로 오류로 반환됩니다. +또한 융합이 수행되지 않는 깊은 페이지(``시작 위치 × 2`` 가 ``rank.fusion.window_size`` +이상이 되는 위치)에서는 메인 검색기에서 발생한 예외가 그대로 검색 요청의 오류가 됩니다. + +시맨틱 서처는 임베딩 프로바이더에 연결할 수 없는 경우나 임베딩 처리에 실패한 경우 +결과를 비어 있는 상태로 반환합니다. 이 경우에도 오류가 되지 않고 키워드 검색만의 결과가 됩니다. + 문제 해결 ========== @@ -190,10 +306,17 @@ Rank Fusion은 키워드 검색과 시맨틱 검색을 결합한 **확인 사항**: -1. 각 검색 유형의 결과를 개별적으로 확인 -2. ``rank.fusion.rank_constant`` 값을 조정 -3. ``rank.fusion.window_size`` 값을 조정 -4. 깊은 페이지(``시작 위치 × 2`` 가 ``rank.fusion.window_size`` 이상이 되는 위치)에서는 융합이 수행되지 않고 메인 검색기만으로 검색됩니다. 더 많은 페이지에서 융합 결과를 사용하려면 ``rank.fusion.window_size`` 를 크게 늘려 주세요. +1. ``searcher`` 필드를 확인합니다("융합 결과 확인" 참조). 모든 문서가 ``["default"]`` 만 + 포함하고 있다면 시맨틱 서처가 결과를 반환하지 않은 것입니다. +2. 시맨틱 검색이 건너뛰어지지 않았는지 확인합니다. 검색 구문(``"`` ``:`` ``AND`` 등)을 + 포함하는 쿼리 외에, 라벨·정렬·패싯에 의한 필터링, 위치 정보 검색, 유사 문서 검색에서는 + 시맨틱 서처가 결과를 반환하지 않고 키워드 검색만의 결과가 됩니다. + 건너뛰는 조건에 대한 자세한 내용은 :doc:`search-semantic` 을 참조하세요. +3. 각 검색 유형의 결과를 개별적으로 확인 +4. ``rank.fusion.rank_constant`` 값을 조정 +5. 깊은 페이지(``시작 위치 × 2`` 가 ``rank.fusion.window_size`` 이상이 되는 위치. 기본값에서는 + 101번째 이후)에서는 융합이 수행되지 않고 메인 검색기만으로 검색됩니다. 더 많은 페이지에서 + 융합 결과를 사용하려면 ``rank.fusion.window_size`` 를 크게 늘려 주세요. 검색이 느림 ------------ @@ -202,13 +325,17 @@ Rank Fusion은 키워드 검색과 시맨틱 검색을 결합한 **해결 방법**: -1. ``rank.fusion.window_size`` 를 줄이기:: +1. ``rank.fusion.threads`` 를 조정:: - rank.fusion.window_size=100 + rank.fusion.threads=4 -2. ``rank.fusion.threads`` 를 조정:: +2. ``rank.fusion.window_size`` 를 줄이기. 다만 하한(``paging.search.page.max.size × 2``) + 보다 작게 할 수 없으므로, 기본 구성에서는 다음 두 가지를 세트로 설정합니다:: - rank.fusion.threads=4 + paging.search.page.max.size=50 + rank.fusion.window_size=100 + + 한 페이지에 요청할 수 있는 최대 건수도 함께 낮아진다는 점에 주의하세요. 설정 후에는 재시작이 필요합니다. 메모리 부족 ------------ @@ -217,12 +344,13 @@ Rank Fusion은 키워드 검색과 시맨틱 검색을 결합한 **해결 방법**: -1. ``rank.fusion.window_size`` 를 줄이기 +1. "검색이 느림"과 동일한 절차로 ``rank.fusion.window_size`` 를 줄이기 2. JVM 힙 크기 늘리기 참고 정보 ========== +- :doc:`search-semantic` - 시맨틱 검색(콘텐츠 청킹) 설정 - :doc:`scripting-overview` - 스크립팅 개요 - :doc:`search-advanced` - 고급 검색 설정 - :doc:`llm-overview` - LLM 통합 가이드 (시맨틱 검색) diff --git a/zh-cn/15.8/config/rank-fusion.rst b/zh-cn/15.8/config/rank-fusion.rst index 5aa336b4..d926ace6 100644 --- a/zh-cn/15.8/config/rank-fusion.rst +++ b/zh-cn/15.8/config/rank-fusion.rst @@ -44,6 +44,12 @@ RRF 通过对每个搜索结果中文档排名的倒数求和来计算分数。 - ``rank(d)``: 文档 d 在各搜索结果中的排名(从 0 开始) - ``Σ``: 对文档 d 出现的所有搜索器求和 +.. note:: + + 融合算法固定为 RRF,没有可切换到其他算法的设置。 + 此外,也不支持按搜索器设置权重。各搜索器的贡献会以相同的权重进行合计。 + 唯一能够调整排名倾向的设置是 ``rank.fusion.rank_constant``\ 。 + 配置 ==== @@ -60,7 +66,7 @@ fess_config.properties # RRF 的 rank_constant(k 参数) rank.fusion.rank_constant=20 - # 并行处理的线程数(0 或以下时,使用可用 CPU 核心数 × 1.5 + 1) + # 并行处理的线程数(0 或以下时,使用可用 CPU 核心数 × 3 ÷ 2 + 1) rank.fusion.threads=-1 # 分数字段名(存储融合后分数的字段) @@ -75,29 +81,50 @@ fess_config.properties - 说明 * - ``rank.fusion.window_size`` - ``200`` - - 从各搜索器中获取用于融合的最大结果数量。必须 >= ``paging.search.page.max.size × 2``\ (默认为 ``200``);若设定值低于此最小值,将自动提升至该最小值。 + - 从各搜索器中获取用于融合的最大结果数量。必须 >= ``paging.search.page.max.size × 2``\ (默认为 ``200``);若设定值低于此最小值,将自动提升至该最小值(启动时会输出 WARN 日志)。 * - ``rank.fusion.rank_constant`` - ``20`` - RRF 计算公式中的常数 ``k``\ 。值越大,高排名与低排名结果之间的分数差越小。 * - ``rank.fusion.threads`` - ``-1`` - - 并行运行多个搜索器时的线程数。指定 ``0`` 或以下时,将自动使用 ``可用 CPU 核心数 × 1.5 + 1``\ 。 + - 并行运行多个搜索器的固定线程池的线程数。指定 ``0`` 或以下时,将自动使用 ``可用 CPU 核心数 × 3 ÷ 2 + 1``\ (由于是整数运算,小数部分会被舍去。例如:4 核 → 7,5 核 → 8)。 * - ``rank.fusion.score_field`` - ``rf_score`` - 用于存储融合后分数的结果文档字段名。 +.. note:: + + **配置的生效时机** + + 以上 4 项配置的更改均需要重启 |Fess| 才能生效。从 ``fess_config.properties`` + 读取的值会被缓存在 JVM 内,因此在运行过程中改写该文件不会生效。 + + 另外,``rank.fusion.window_size`` 仅在启动时读取一次,\ ``rank.fusion.threads`` + 则在创建线程池时读取。线程池是在注册了 ``default`` 以外的搜索器 + (例如语义搜索器)时创建的,因此在语义搜索未启用的情况下,线程池本身不会被创建。 + JVM 系统属性 ------------ 使用的搜索器通过 JVM 系统属性指定。 -在 ``fess.in.sh``\ (或 ``fess.in.bat``)中添加如下内容:: +在 ``fess.in.sh`` 中添加如下内容:: - # 指定使用的搜索器(逗号分隔) - -Drank.fusion.searchers=default,semantic_chunk + FESS_JAVA_OPTS="$FESS_JAVA_OPTS -Drank.fusion.searchers=default,semantic_chunk" + +如果是 ``fess.in.bat``\ ,则按如下方式添加:: + + set FESS_JAVA_OPTS=%FESS_JAVA_OPTS% -Drank.fusion.searchers=default,semantic_chunk 此属性的行为如下: -- 以 JVM 选项形式设置,而非在 ``fess_config.properties`` 中配置。 +- 以 JVM 选项形式设置,而非在 ``fess_config.properties`` 中配置。键名请直接指定 + ``rank.fusion.searchers`` 本身。其他设置中常用的 ``-Dfess.config.`` 或 ``-Dfess.system.`` + 前缀形式(例如 ``-Dfess.config.rank.fusion.searchers``\ )不会被识别。 +- 除了 JVM 选项之外,也可以在管理界面“系统 > 常规”的“系统属性”栏中,以 + ``rank.fusion.searchers=default,semantic_chunk`` 这样的形式写成一行。 + 但该栏中的值仅在同名系统属性尚未设置时才会被应用。 + 因此,若已通过 ``-D`` 指定,则 JVM 选项优先;而要更改已经应用的值, + 需要重启 |Fess|\ 。 - ``default`` 是执行标准关键词搜索的搜索器,始终可用。 - 搜索器的名称由其实现类名去掉末尾的 ``Searcher``\ ,再转换为小写蛇形命名(snake_case)得来 (``SemanticChunkSearcher`` → ``semantic_chunk``)。核心集成的语义搜索器 @@ -120,8 +147,62 @@ JVM 系统属性 ================ Rank Fusion 在结合关键词搜索与语义搜索的 -混合搜索中尤为有效。要使用语义搜索,请配置内容分块功能并设置 -``content_chunker.search.enabled=true``\ 。详情请参阅 :doc:`search-semantic`\ 。 +混合搜索中尤为有效。要使用语义搜索,请在配置内容分块功能之后设置 +``content_chunker.search.enabled=true``\ 。 + +.. warning:: + + ``content_chunker.enabled`` 和 ``content_chunker.search.enabled`` 等 + ``content_chunker.*`` 配置属于\ **系统属性**\ ,而不是 ``fess_config.properties``\ 。 + 请将其写入 ``conf/system.properties``\ ,或以 + ``-Dfess.system.content_chunker.search.enabled=true`` 这样的形式指定为 JVM 选项。 + 即使写入 ``fess_config.properties`` 也不会生效。 + 另外,``content_chunker.search.enabled`` 仅在启动时评估,因此启用后需要重启 |Fess|\ 。 + +详情请参阅 :doc:`search-semantic`\ 。 + +融合结果的确认 +============== + +要确认 Rank Fusion 是否确实在工作,可以查看搜索结果中附加的以下两个字段。 + +.. list-table:: + :header-rows: 1 + :widths: 20 80 + + * - 字段 + - 内容 + * - ``searcher`` + - 检索到该文档的搜索器名称数组(例如 ``["default", "semantic_chunk"]``)。若两者都包含在内,则表示该文档在关键词搜索和语义搜索中均被命中。 + * - ``rf_score`` + - 通过 RRF 计算出的融合后分数。字段名可通过 ``rank.fusion.score_field`` 更改。 + +这两个字段都是在搜索时动态附加的值,不会保存到索引中。 +此外,默认情况下它们不会包含在 ``/api/v2/search`` 的响应中,若要确认,请在 +``fess_config.properties`` 中进行以下设置并重启 |Fess|:: + + query.additional.api.response.fields=rf_score,searcher + +.. note:: + + ``query.additional.api.response.fields`` 用于向“允许包含在 v2 搜索 API 响应中的字段” + 许可列表中追加条目。如果追加 ``role`` 或 ``virtual_host`` 等访问控制用字段, + 访问控制信息将暴露在搜索 API 的响应中,因此请勿追加这类字段。 + +对命中数量的影响 +================ + +执行 Rank Fusion 时,返回的总命中数量并非直接使用主搜索器(注册在首位的 ``default`` +搜索器)的数量,而是按如下方式进行修正:: + + 总命中数量 = 主搜索器的总命中数量 + 修正值 + +修正值是指:在融合后的前 ``window_size ÷ 2`` 条结果中,未包含在主搜索器前 +``window_size ÷ 2`` 条结果内的文档数量。也就是说,命中数量会增加仅由语义搜索找到的 +文档数量。 +因此,即使是相同的查询,启用与不启用混合搜索时的命中数量也可能不同。 + +另外,当主搜索器的总命中数量以概算值(下限值)返回时,不会进行此修正。 使用示例 ======== @@ -157,13 +238,23 @@ Rank Fusion 在结合关键词搜索与语义搜索的 -------- - 由于需要保留多个搜索结果,内存使用量会增加。 -- 可使用 ``rank.fusion.window_size`` 限制融合目标的最大数量。主搜索器(排在首位的 ``default`` 搜索器)最多获取 ``window_size`` 条结果,其他搜索器各获取 ``window_size ÷ 搜索器数量`` 条结果。 +- 可使用 ``rank.fusion.window_size`` 限制融合目标的最大数量。主搜索器(排在首位的 ``default`` 搜索器)最多获取 ``window_size`` 条结果,其他搜索器各获取 ``window_size ÷ 搜索器数量`` 条结果(``搜索器数量`` 是包含主搜索器在内的总数,除法会向下取整)。 +- 例如,当有 2 个搜索器(``default`` 和 ``semantic_chunk``)且 ``window_size=200`` 时,主搜索器获取 200 条、语义搜索器获取 100 条,因此最多会保留 300 条文档。 :: # 融合目标的窗口大小 rank.fusion.window_size=200 +.. warning:: + + ``rank.fusion.window_size`` 不能低于 ``paging.search.page.max.size × 2``\ 。 + 当 ``paging.search.page.max.size`` 为默认值 ``100`` 时,下限即为 ``200``\ ,这与 + ``rank.fusion.window_size`` 的默认值相同。也就是说,\ **在默认配置下无法将 window_size + 设置为小于默认值**\ 。即使设置了更小的值,启动时也会输出 WARN 日志并将其提升至 ``200``\ 。 + 若要实际减小该值,需要先降低 ``paging.search.page.max.size``\ ,但这同时也会降低搜索界面 + 和 API 中每页可请求的最大结果数量。 + 处理时间 -------- @@ -172,9 +263,27 @@ Rank Fusion 在结合关键词搜索与语义搜索的 :: - # 并行执行的线程数(0 或以下时,使用可用 CPU 核心数 × 1.5 + 1) + # 并行执行的线程数(0 或以下时,使用可用 CPU 核心数 × 3 ÷ 2 + 1) rank.fusion.threads=-1 +.. note:: + + 搜索器的执行没有设置超时。如果存在不返回响应的搜索器,搜索请求将一直等待其完成。 + +搜索器故障时的行为 +================== + +当任一搜索器因异常而失败时,该搜索器的结果会被视为空,在输出 WARN 日志之后, +仅使用其余搜索器的结果继续进行融合。搜索请求本身不会变成错误。 + +但查询语法错误(``InvalidQueryException``)和分页上限超出 +(``ResultOffsetExceededException``)除外,它们会直接作为错误返回。 +此外,在不进行融合的深层页面(``起始位置 × 2`` 大于等于 ``rank.fusion.window_size`` 的位置), +主搜索器中发生的异常会直接作为搜索请求的错误返回。 + +语义搜索器在无法连接到嵌入提供商或嵌入处理失败时,会返回空结果。 +这种情况下同样不会产生错误,而是仅返回关键词搜索的结果。 + 故障排除 ======== @@ -185,10 +294,17 @@ Rank Fusion 在结合关键词搜索与语义搜索的 **检查事项**: -1. 分别确认各搜索类型的结果 -2. 调整 ``rank.fusion.rank_constant`` 的值 -3. 调整 ``rank.fusion.window_size`` 的值 -4. 在翻页较深的页面(``起始位置 × 2`` 大于等于 ``rank.fusion.window_size`` 的位置),不会执行融合,仅使用主搜索器进行搜索。若希望在更多页面上获得融合结果,请增大 ``rank.fusion.window_size``\ 。 +1. 确认 ``searcher`` 字段(请参阅“融合结果的确认”)。如果所有文档都仅为 + ``["default"]``\ ,则说明语义搜索器没有返回结果。 +2. 确认语义搜索是否被跳过。除了包含搜索语法(如 ``"`` ``:`` ``AND`` 等)的查询之外, + 在通过标签、排序、分面进行筛选,以及位置信息搜索、相似文档搜索时,语义搜索器也不会返回 + 结果,仅返回关键词搜索的结果。 + 跳过条件的详细信息请参阅 :doc:`search-semantic`\ 。 +3. 分别确认各搜索类型的结果 +4. 调整 ``rank.fusion.rank_constant`` 的值 +5. 在翻页较深的页面(``起始位置 × 2`` 大于等于 ``rank.fusion.window_size`` 的位置,默认情况下 + 为第 101 条之后)不会执行融合,仅使用主搜索器进行搜索。若希望在更多页面上获得融合结果, + 请增大 ``rank.fusion.window_size``\ 。 搜索缓慢 -------- @@ -197,13 +313,17 @@ Rank Fusion 在结合关键词搜索与语义搜索的 **解决方法**: -1. 减小 ``rank.fusion.window_size``:: +1. 调整 ``rank.fusion.threads``:: - rank.fusion.window_size=100 + rank.fusion.threads=4 -2. 调整 ``rank.fusion.threads``:: +2. 减小 ``rank.fusion.window_size``\ 。但由于不能低于下限 + (``paging.search.page.max.size × 2``),在默认配置下需要将以下两项成对设置:: - rank.fusion.threads=4 + paging.search.page.max.size=50 + rank.fusion.window_size=100 + + 请注意,每页可请求的最大结果数量也会随之下降。设置后需要重启。 内存不足 -------- @@ -212,12 +332,13 @@ Rank Fusion 在结合关键词搜索与语义搜索的 **解决方法**: -1. 减小 ``rank.fusion.window_size`` +1. 按照“搜索缓慢”中的相同步骤减小 ``rank.fusion.window_size`` 2. 增加 JVM 堆大小 参考信息 ======== +- :doc:`search-semantic` - 语义搜索(内容分块)的配置 - :doc:`scripting-overview` - 脚本概述 - :doc:`search-advanced` - 高级搜索设置 - :doc:`llm-overview` - LLM 集成指南(语义搜索)