クエリの理解
読了まで約74 分分、10 節 節の 12 例 例。
この章を読み終えると、検索の前に買い物客のクエリを変更できるようになる。具体的には、綴りを訂正する、単位の書き方をそろえる、同義語で拡張する、商品クラスを予測する、大規模言語モデルで書き換える、そのモデルが想像した商品で検索する、フォローアップの発話を単独で成り立つクエリに変換する、という操作である。さらに、それぞれの変更が、その変更を受け取る検索器の役に立つかどうかを、人間による判定にもとづいて判断できるようになる。
買い物客がストアの検索ボックスに入力する短いクエリの中には、目的の商品に一致しないものがある。ligth bulbは単語の綴りを誤っている。7qt slow cookerはサイズを、0個の商品が含む語として書いている。midcentury tv unitについては、第7章で数えると25個の完全一致の商品があり、そのうち0個がmidcenturyを、0個がunitを含んでいる。
机を検索した後にin whiteと入力した買い物客は白い机を求めているが、語だけからはそれが分からない。クエリ理解とは、こうしたずれを埋めるために、検索システムが検索の前にクエリに対して行うすべての処理を指す。訂正、正規化、拡張、分類、書き換えがそれにあたる。第5章から第7章では検索器を変更した。この章では検索器を固定したままクエリを変更する。固定する検索器は、lib.lexicalにある本書の語幹処理なしのベースラインであるBM25と、クエリの埋め込みを各商品の埋め込みと比較する意味検索である。埋め込みはどちらもSnowflake/snowflake-arctic-embed-m-v1.5があらかじめ計算している。
手法のうち三つはストアのLLMを使う。そのLLMはgemma4:12b-it-q4_K_Mで、GoogleがApache 2.0ライセンスで公開しているオープンモデルである(モデルカード)。例のコードがこのモデルを呼び出すことはない。recordings/llm_rewrites.pyとrecordings/llm_conversations.pyの二つのスクリプトが、温度0、固定シードで一度だけ実行し、出力を録画データとして保存した。例はそれをlib.recordedを通じて読み込む。各録画データのmanifest.jsonには完全なプロンプトが入っている。録画データは、第4章と同じオープンモデルと設定を用いている。LLMが見るのは買い物客の言葉だけで、商品は一切見ない。この章のすべてのスコアには人間による判定を用いる。
すべての設定は50件の訓練クエリで選び、30件のテストクエリは報告のために取っておく。この章では、テストクエリ上で行う5件の比較を、結果を読む前に計画して確定させた。それぞれの比較は、変更を一つだけ加えた検索器を、入力されたままのクエリを使う同じ検索器と比べて測定するものである。
- 同義語リストを用いたBM25
- 予測したクラスへのブーストを加えた意味検索
- LLMによる書き換えに対するBM25
- LLMによる書き換えに対する意味検索
- HyDEを用いた意味検索。HyDEは、クエリの埋め込みと、LLMが想像した商品の埋め込みとを平均する
計画した比較はそれぞれ本書の規則を満たさなければならない。対応のある並べ替え検定のp値が0.01を下回ることである。この値は0.05を計画した比較の数で割ったものである。これと並べて、対応のあるt検定と99%のブートストラップ区間も示す。綴りの訂正、単位の正規化、フォローアップの書き換えは、いずれも対象となるクエリが少なすぎて検定できないため、それぞれの節は探索的なものである。
カタログの語彙に照らしてスペルを訂正する
最初のギャップはタイプミスであり、ligth bulbがその例である。BM25では、スペルを誤った語は同じ綴りの誤りを含む商品としか一致せず、第6章が示すように、クエリの埋め込みを、意図した商品から遠ざけることもある。検索クエリにはこの種の誤りが多く含まれる。ウェブ検索を調べた研究であるCucerzan and Brill (2004)は、検索エンジンに送られるクエリのおよそ10〜15パーセントに誤りが含まれると報告している。古典的な訂正器はノイジーチャネルモデルである。入力された語 t に対し、P(c) × P(t | c) を最大にする訂正候補 c を選ぶ(Kernighan et al., 1990)。P(c) は候補の語がどれだけ一般的かを表す。誤りモデルである P(t | c) は、c を意図した買い物客が t と入力する確率を表す。Kernighan らは、タイプミスから1回の編集で得られる語、すなわち削除、挿入、置換、隣り合う2文字の入れ替えで得られる語を候補とする。ある文字列を別の文字列に変えるのに必要な挿入、削除、置換の回数をその編集距離と呼ぶ(Manning et al., 2008)。ここで用いる訂正器は、入れ替えも1回の編集として数える。教科書は2つの原則を平易に述べている。正しい綴りのうち最も近いものを選び、近さが同程度なら、より一般的なものを選ぶ、という原則である(Manning et al., 2008)。Norvig はこの種の訂正器を数行で書いている(Norvig)。
correction(t) = argmax over candidates c of P(c) × P(t | c)
正しい語として扱う語の一覧である語彙が、何が訂正されるかを決める。ウェブ検索エンジンはクエリログから語彙を作るため、選ばれる訂正は他のユーザーのクエリで最も多く使われているものになる(Manning et al.)。このストアにはログがないので、語彙はカタログのテキストから作る。語彙の出どころはブランド名に関わる。商品検索の訂正器は、本物のスペルミスと、慣例にない綴りの新しいブランドとを見分けなければならないからである(Guo et al., 2024)。
ここで用いる訂正器は最も単純な誤りモデルを使う。語彙にある語はそのまま残し、1回の編集は2回の編集に勝ち、編集回数が同じ候補どうしでは、各候補がどれだけ一般的かを表す P(c) で優劣を決める。これを全80件のクエリに適用し、どれが変更されるかを見る。
1"""A spelling corrector built from the catalog's word counts, run on every query and checked against2lib.queries.correct_query. The prose's point rests on the "queries changed" line and on the line that says whether both correctors agree."""3import re4from collections import Counter56from lib.queries import correct_query7from lib.store import load_products, load_queries, product_text89texts = product_text(load_products()).str.lower()10counts = Counter(re.findall(r"[a-z]+", " ".join(texts))) # the lexicon, and how common each word is111213def edits1(word):14 """Every string one edit away: a deletion, a swap of two neighbouring letters, a replacement or an insertion."""15 splits = [(word[:cut], word[cut:]) for cut in range(len(word) + 1)]16 letters = "abcdefghijklmnopqrstuvwxyz"17 return ({left + right[1:] for left, right in splits if right}18 | {left + right[1] + right[0] + right[2:] for left, right in splits if len(right) > 1}19 | {left + letter + right[1:] for left, right in splits if right for letter in letters}20 | {left + letter + right for left, right in splits for letter in letters})212223def correct(word):24 """Keep a word the catalog uses. Otherwise take the commonest catalog word one edit away, else two."""25 if not word.isalpha() or word in counts:26 return word27 candidates = {edit for edit in edits1(word) if edit in counts} or {28 two for edit in edits1(word) for two in edits1(edit) if two in counts}29 # the most common candidate; on a tie in counts, the alphabetically first one30 return max(sorted(candidates), key=counts.get) if candidates else word313233queries = load_queries()34corrected = queries["query"].map(lambda query: " ".join(correct(word) for word in query.lower().split()))35changed = queries[corrected != queries["query"].str.lower()]36print(f"catalog words: {len(counts):,}")37print("queries changed:", len(changed))38print("of them, train queries:", (changed["split"] == "train").sum())39for query_id, query in changed["query"].items():40 print(f" {query} ({changed.at[query_id, 'split']}), corrected: {corrected[query_id]}")41same = corrected.equals(queries["query"].map(lambda query: correct_query(query, counts)))42print("same as lib.queries.correct_query:", same)43for word in ["tye", "tie", "the", "kohler", "whitehaven", "malachi", "luau"]: # P(c), as counts44 print(f"catalog count of {word}:", counts[word])
python catalog-spelling-corrector.pycatalog words: 19,680
queries changed: 4
of them, train queries: 3
foutains with brick look (train), corrected: fountains with brick look
twin over full bunk beds cool desins (train), corrected: twin over full bunk beds cool designs
ligth bulb (train), corrected: light bulb
tye dye duvet cover (test), corrected: the dye duvet cover
same as lib.queries.correct_query: True
catalog count of tye: 0
catalog count of tie: 45
catalog count of the: 20389
catalog count of kohler: 71
catalog count of whitehaven: 60
catalog count of malachi: 5
catalog count of luau: 4
カタログは19,680種類の異なる語を使っており、訂正器は4件のクエリを変更する。そのうち3件は訓練クエリである。共有関数lib.queries.correct_queryも同じ訂正を行い、訂正器は第6章のスペルのプローブと同じやり方で各訓練クエリを綴る。つまり、第6章がこの本のために書いた、タイプミスのクエリを正しく綴ったコピーを用いる。
訂正器はブランド名には手を加えない。カタログがそれらを使っているからである。kohlerは71回、whitehavenは60回使われている。残される語の中には稀なものもある。malachiは5回、luauは4回使われている。稀な語を除く語彙であれば、この2語はどちらもタイプミスとして扱われるだろう。
訂正器の失敗はテストクエリに現れる。tye dye duvet coverはthe dye duvet coverになる。tyeはtie(カタログに45回)からもthe(20389)からも1回の編集の距離にあり、P(c) が一般的な語を選ぶからである。またrefrigerator with ice an water in doorはanをそのまま残す。このanは実在語エラーであり、「flew form Heathrow」のように、すべての語が正しく綴られているタイプミスである(Manning et al., 2008)。どちらも文脈を必要とする。tyeとanについて、1回の編集の範囲にある各カタログ語が、クエリの次の語であるdyeまたはwaterの直前に現れる回数を数える。
1"""For the misspelled word in two test queries, `tye` and the real-word error `an`, counts how often each nearby catalog word comes before the query's next2word, and shows the context-free corrector's choice. The prose's point rests on the "catalog count of ... the3corrector's choice" lines."""4import re5from collections import Counter67from lib.queries import correct_word, edits1, word_counts8from lib.store import load_products, product_text910texts = product_text(load_products()).str.lower()11counts = word_counts(texts) # the corrector's lexicon12words_per_product = [re.findall(r"[a-z]+", text) for text in texts]13pairs = Counter(pair for words in words_per_product for pair in zip(words, words[1:])) # neighbouring words1415# tye in "tye dye duvet cover", an in "refrigerator with ice an water in door": each word, the word after it16for word, after in [("tye", "dye"), ("an", "water")]:17 # the typed word and each catalog word one edit away, ranked by how often each comes before the next word18 options = sorted(((pairs[(edit, after)], edit) for edit in edits1(word) | {word} if edit in counts), reverse=True)19 for count, edit in options[:3]:20 print(f"catalog count of {edit} {after}:", count)21 choice = correct_word(word, counts) # what the corrector without context picks22 print(f"the corrector's choice for {word}: {choice}")23 print(f"catalog count of {choice} {after}, the corrector's choice:", pairs[(choice, after)])
python spelling-context-counts.pycatalog count of tie dye: 18
catalog count of type dye: 0
catalog count of tyke dye: 0
the corrector's choice for tye: the
catalog count of the dye, the corrector's choice: 0
catalog count of and water: 59
catalog count of a water: 20
catalog count of in water: 9
the corrector's choice for an: an
catalog count of an water, the corrector's choice: 0
dyeの前には、カタログのテキストにtieが18回現れ、訂正器の選択であるtheは0回である。waterの前には、andが59回現れ、aの20回を上回る。一方、訂正器の選択であるanは0回である。この2つのクエリでは、各候補を隣接する語で採点する訂正器ならtieとandを選ぶだろう。これで、訂正後の各クエリを自身の判定に照らして採点でき、変更が役立つかどうかが分かる。
1"""Scores each typo query, and the variant spelling tye dye, with BM25, and with recorded embeddings where the corrected2text has one, as typed and as corrected. The prose's point rests on the nDCG@10 lines for queries 20 and 224 (train) and the corrected BM25 line for 459 (test)."""3from lib.lexical import LexicalSearch4from lib.metrics import ndcg_at_k5from lib.queries import correct_query, word_counts6from lib.recorded import probes7from lib.semantic import SemanticSearch8from lib.store import load_products, load_queries, product_text, qrels910products, queries, judgments = load_products(), load_queries(), qrels()11counts = word_counts(product_text(products))12bm25, semantic = LexicalSearch(products), SemanticSearch()13probe_queries, probe_vectors = probes() # recorded embeddings of the four typo queries, spelled correctly14spelling = probe_queries[probe_queries["kind"] == "spelling"]15# the probes' embeddings, keyed by the correctly spelled text, so a corrected query can find its own16spelled = {row["query"]: probe_vectors[index] for index, row in spelling.iterrows()}17typo_queries = spelling["of_query_id"].astype(int).tolist()18print("typo queries:", len(typo_queries))19print("of them, test queries:", (queries.loc[typo_queries, "split"] == "test").sum())2021for query_id in typo_queries + [459]: # the typo queries, then the one variant spelling, tye dye22 typed = queries.at[query_id, "query"]23 corrected = correct_query(typed, counts)24 label = f"{query_id} ({queries.at[query_id, 'split']})"25 print(f"{label}: {typed} -> {corrected}")26 for name, text in [("typed", typed), ("corrected", corrected)]:27 ranking = list(bm25.search(text, k=10).index)28 print(f"{label}, bm25 ndcg@10 {name}: {ndcg_at_k(ranking, judgments[query_id], 10):.3f}")29 if corrected == typed.lower():30 print(f"{label}: the corrector changes nothing")31 elif corrected in spelled:32 for name, vector in [("typed", semantic.query_vectors[query_id]), ("corrected", spelled[corrected])]:33 ranking = list(semantic.search_vector(vector, k=10).index)34 print(f"{label}, semantic ndcg@10 {name}: {ndcg_at_k(ranking, judgments[query_id], 10):.3f}")35 else:36 print(f"{label}: no recorded embedding of the corrected text")
python measure-spelling-corrections.pytypo queries: 4
of them, test queries: 1
305 (train): ligth bulb -> light bulb
305 (train), bm25 ndcg@10 typed: 0.945
305 (train), bm25 ndcg@10 corrected: 0.945
305 (train), semantic ndcg@10 typed: 1.000
305 (train), semantic ndcg@10 corrected: 1.000
20 (train): foutains with brick look -> fountains with brick look
20 (train), bm25 ndcg@10 typed: 0.356
20 (train), bm25 ndcg@10 corrected: 0.507
20 (train), semantic ndcg@10 typed: 0.353
20 (train), semantic ndcg@10 corrected: 0.645
224 (train): twin over full bunk beds cool desins -> twin over full bunk beds cool designs
224 (train), bm25 ndcg@10 typed: 0.488
224 (train), bm25 ndcg@10 corrected: 0.488
224 (train), semantic ndcg@10 typed: 0.565
224 (train), semantic ndcg@10 corrected: 0.616
406 (test): refrigerator with ice an water in door -> refrigerator with ice an water in door
406 (test), bm25 ndcg@10 typed: 0.501
406 (test), bm25 ndcg@10 corrected: 0.501
406 (test): the corrector changes nothing
459 (test): tye dye duvet cover -> the dye duvet cover
459 (test), bm25 ndcg@10 typed: 0.953
459 (test), bm25 ndcg@10 corrected: 0.953
459 (test): no recorded embedding of the corrected text
訂正が最も効くのはfoutains with brick look(訓練)である。意味検索は0.353から0.645に、BM25は0.356から0.507になる。
残る2つの訓練用タイプミスのうち、twin over full bunk beds cool desinsは意味検索だけを0.565から0.616へ動かし、ligth bulbはどちらの検索器も動かさない。refrigerator with ice an water in doorでは訂正器は何も変更せず、正しい修正でもBM25を改善できない。入力されたanと正しいandのどちらも、bm25sはストップワードとして除外する(an, and)。andで綴った第6章のクエリのコピーは0.501となり、入力どおりのクエリと同じ値である。
tye dye duvet coverでは、BM25はどちらの場合も0.953となる。theはストップワードであり、tyeはどの商品にも一致しないので、両方のバージョンが同じ語を検索するからである。意味検索は訂正後のテキストでは採点できない。記録データにその埋め込みが含まれていないからである。このストアにはタイプミスのクエリが4件あり、そのうちテストクエリは1件である。これほど少ない件数で得られる両側並べ替え検定の最小の p 値は0.125である。
実践ルール: 語彙はカタログから作り、クエリログができたらそれも使って作る。訂正するのは語彙にない語だけにして、ブランド名を残す。語を訂正する前に隣接する語を確認すること。文脈のない訂正器は、異体の綴りを一般的な語に変え、実在語エラーを見逃す。各訂正は、タイプミスのクエリ自身の判定で採点する。訂正器を検証する前に、このストアにあるより多くのタイプミスのクエリを集めること。
この部分はまだ翻訳されていないため、英語で表示している。
Normalize units the way the catalog writes them
A typo has one right spelling; a size, as in 7qt slow cooker, often has several. Normalization maps the different ways of writing one thing to a single form, on the products and on the query alike. Sizes in this catalog need it. Chapter 5 found that 7qt and 7 qt never match each other, because the tokenizer drops the one-character 7. A normalizer that joins each number to its unit, written one way, turns both into one term, 7qt. It has to run on the product text when you build the index, and on every query. It also has to produce terms the tokenizer keeps whole. The tokenizer splits words at a decimal point, so 3.7qt would become 7qt. To prevent that, the shared function lib.queries.normalize_units writes the point as an underscore, which the tokenizer keeps inside a word. It also leaves in alone when a number or one follows, as in 3 in 1.
A rule written from the queries would cover qt, in, inch and ". Before you trust it, count how the catalog writes inches. We count them first, print the terms the tokenizer makes of a few normalized texts, and build BM25 three times: over the text as written, normalized by that first rule, and normalized by normalize_units, which also handles the catalog's two apostrophes, '', for inches. We score every query, train or test, that gives a number with a unit:
1"""Counts how the catalog writes inches, prints the terms the tokenizer makes of normalized texts, and scores BM25 on2every query with a unit under three rules. The prose's point rests on the "bm25 ndcg@10" lines for queries 62 and 482."""3from lib.lexical import LexicalSearch4from lib.lexical_by_hand import tokenize5from lib.metrics import ndcg_at_k6from lib.queries import INCH_SPELLINGS, normalize_units, unit_rules7from lib.store import load_products, load_queries, product_text, qrels89products, queries, judgments = load_products(), load_queries(), qrels()10text = product_text(products).str.lower()11# the catalog's spellings of inches after a number; -? also takes a hyphen, as in 48-inch12for name, unit in [("''", r"''"), ('"', r"\""), ("inch", r"-?inch")]:13 print(f"products that write a number then {name}:", text.str.contains(rf"\d\s*{unit}").sum())1415# the first rule, written from the queries' units: lib's inch spellings (inches, inch, in, ") without the two apostrophes; quarts are always included16first_try = unit_rules([spelling for spelling in INCH_SPELLINGS if spelling != "''"]) # written from queries17# None leaves the text as written, with no normalization18rules = {"as written": None, "first try": first_try, "normalized": unit_rules()}19checks = [("3.7-quart slow cooker", "normalized"), ("3 in 1 sofa bed", "normalized"), ("1 in twin", "normalized"),20 ("48 '' range hood", "first try"), ("48 '' range hood", "normalized")]21for example, name in checks: # what the tokenizer reads22 print(f"terms of {example}, {name}:", " ".join(tokenize(normalize_units(example, rules[name]))))2324searches = {}25for name, rule in rules.items():26 rewritten = products.copy()27 if rule is not None:28 for column in ["name", "product_class", "category", "description"]: # the columns product_text joins29 rewritten[column] = rewritten[column].map(lambda value: normalize_units(value, rule))30 searches[name] = LexicalSearch(rewritten)3132# queries with a number and a unit: qt, in, inch or a double quote33with_units = queries[queries["query"].str.contains(r"\d\s*(?:qt|in\b|inch|\")")]34print("queries with a unit:", len(with_units))35print("of them, test queries:", (with_units["split"] == "test").sum())36for query_id, query in with_units["query"].items():37 label = f"{query_id} ({queries.at[query_id, 'split']})"38 print(f"{label}: {query} -> {normalize_units(query)}")39 for name, rule in rules.items():40 typed = query if rule is None else normalize_units(query, rule)41 ranking = list(searches[name].search(typed, k=10).index)42 print(f"{label}, bm25 ndcg@10 {name}: {ndcg_at_k(ranking, judgments[query_id], 10):.3f}")
python normalize-units-both-sides.pyproducts that write a number then '': 3014
products that write a number then ": 65
products that write a number then inch: 215
terms of 3.7-quart slow cooker, normalized: 3_7qt slow cooker
terms of 3 in 1 sofa bed, normalized: sofa bed
terms of 1 in twin, normalized: 1in twin
terms of 48 '' range hood, first try: 48 range hood
terms of 48 '' range hood, normalized: 48in range hood
queries with a unit: 4
of them, test queries: 2
62 (train): 7qt slow cooker -> 7qt slow cooker
62 (train), bm25 ndcg@10 as written: 0.554
62 (train), bm25 ndcg@10 first try: 0.930
62 (train), bm25 ndcg@10 normalized: 0.930
101 (train): 48 in entry table with side by side drawer -> 48in entry table with side by side drawer
101 (train), bm25 ndcg@10 as written: 0.569
101 (train), bm25 ndcg@10 first try: 0.569
101 (train), bm25 ndcg@10 normalized: 0.569
285 (test): 48" sliding single track , barn door for laundry -> 48in sliding single track , barn door for laundry
285 (test), bm25 ndcg@10 as written: 0.592
285 (test), bm25 ndcg@10 first try: 0.592
285 (test), bm25 ndcg@10 normalized: 0.592
482 (test): 48 inch kitchen hood -> 48in kitchen hood
482 (test), bm25 ndcg@10 as written: 1.000
482 (test), bm25 ndcg@10 first try: 0.824
482 (test), bm25 ndcg@10 normalized: 1.000
The catalog's usual way to write inches is the one a rule written from the queries misses: two apostrophes after a number, in 3014 products, against 65 for " and 215 for inch.
The tokenizer reads 3.7-quart slow cooker, normalized, as 3_7qt slow cooker, and 3 in 1 sofa bed as sofa bed. normalize_units still misreads 1 in twin as 1in twin, which is why the terms are worth printing.
Normalizing lifts the train query 7qt slow cooker: BM25's nDCG@10 goes from 0.554 to 0.930, and the first rule gives 0.930. The test query 48 inch kitchen hood shows what the first rule loses by missing the two apostrophes. It scores 1.000 as written and 0.824 under the first rule. The query becomes 48in, while the first rule leaves a hood written 48 '' as 48 range hood, and the full rule makes it 48in range hood. With the full rule, the hood query scores 1.000.
The other train query, 48 in entry table with side by side drawer, scores 0.569 as written and 0.569 normalized, and the test query about a sliding barn door scores 0.592 and 0.592. That makes 4 queries with a unit, 2 of them test queries: too few to test.
Working rule: Write normalization rules from the catalog's text, not from the queries, by counting every way it writes each unit. Print the terms the tokenizer makes of the normalized text, because a rule that looks right can produce terms that match the wrong products. Apply the same rules to products and queries in one release, and rebuild the index. When the catalog keeps sizes in fields, such as the width in attributes, match the size against the field instead, as chapter 6 suggests.
この部分はまだ翻訳されていないため、英語で表示している。
Expand queries with a synonym list
Some gaps are neither typos nor units but different words for one thing, as when the exact products for midcentury tv unit say stand. Query expansion adds terms to a query so that it can match products that use other words for the same thing. Expansion generally increases recall, the share of the relevant products that a search finds (Manning et al., 2008). It can also significantly decrease precision, the share of found products that are relevant, particularly when the query contains ambiguous terms (Manning et al., 2008). A word that expansion adds can match products the shopper didn't ask for, and move the query away from its meaning, which is called query drift. Expansion terms can come from a hand-built list of synonyms, or from the results. Pseudo-relevance feedback assumes the top results are relevant and adds their terms to the query, which makes drift its known risk (Manning et al., 2008).
Here lib.queries.SYNONYMS holds 14 groups of interchangeable words, such as stand and unit, written by reading the train queries whose exact products miss a query word. When a query contains a word or phrase from a group, expand appends the group's other members, and BM25 searches the result. Measure it on the train queries, then make the first of the chapter's planned comparisons on the test queries:
1"""Expands each query with the synonym list, scores BM25 on the train and test queries as typed and expanded, and2runs the list's planned test comparison. The prose's point rests on the "synonyms, bm25" lines of that comparison."""3from lib.lexical import LexicalSearch4from lib.metrics import evaluate5from lib.queries import PLANNED_TEST_COMPARISONS, SYNONYMS, THRESHOLD, expand, report_planned6from lib.store import load_products, load_queries, qrels78products, judgments = load_products(), qrels()9bm25 = LexicalSearch(products)10print("synonym groups:", len(SYNONYMS))11scores = {}12for split in ["train", "test"]:13 queries = load_queries(split)14 expanded = queries.assign(query=queries["query"].map(expand))15 changed = queries.index[expanded["query"] != queries["query"]]16 print(f"{split} queries the list changes:", len(changed))17 for name, frame in [("typed", queries), ("expanded", expanded)]:18 scores[split, name] = evaluate(bm25.run(frame), qrels(split))19 print(f"{split} ndcg@10 {name}: {scores[split, name]['ndcg@10'].mean():.3f}")20 print(f"{split} judged@10 {name}: {scores[split, name]['judged@10'].mean():.3f}")21for query in queries.loc[changed, "query"]: # the test queries the list changes22 print(f"test query changed: {query}")23 # expand returns the query, a space, then the added words, so this slice keeps only the added words24 print(f"words the list adds to it: {expand(query)[len(query) + 1:]}")2526change = (scores["train", "expanded"]["ndcg@10"] - scores["train", "typed"]["ndcg@10"]).round(3)27print(f"train queries better, worse: {(change > 0).sum()}, {(change < 0).sum()}") # for choosing, not evidence28print(f"share of the net train gain from the largest gain: {change.max() / change.sum():.3f}")29for kind, query_id in [("gain", change.idxmax()), ("loss", change.idxmin())]:30 query = load_queries().at[query_id, "query"]31 # the same slice: everything after the query and the space that expand puts between them32 added = expand(query)[len(query) + 1:]33 print(f"largest train {kind}: {query}")34 print(f"largest train {kind}, words added: {added}")35 print(f"largest train {kind}, change: {change[query_id]:+.3f}")36named = [product_id for product_id in bm25.search(expand(query), k=10).index if added in products.at[product_id, "name"]]37print(f"largest train loss, top 10 names with {added}:", len(named)) # query and added: the largest loss's38print("largest train loss, of those, unjudged:", sum(product_id not in judgments[query_id] for product_id in named))3940print("\nplanned test comparisons:", len(PLANNED_TEST_COMPARISONS))41print(f"p-value threshold: {THRESHOLD:.2f}")42report_planned("synonyms, bm25", scores["test", "expanded"]["ndcg@10"], scores["test", "typed"]["ndcg@10"])
python synonym-expansion-train-and-test.pysynonym groups: 14
train queries the list changes: 14
train ndcg@10 typed: 0.695
train judged@10 typed: 0.930
train ndcg@10 expanded: 0.722
train judged@10 expanded: 0.944
test queries the list changes: 1
test ndcg@10 typed: 0.725
test judged@10 typed: 0.927
test ndcg@10 expanded: 0.725
test judged@10 expanded: 0.927
test query changed: indoor multi tiered plant stand
words the list adds to it: unit
train queries better, worse: 6, 5
share of the net train gain from the largest gain: 0.473
largest train gain: midcentury tv unit
largest train gain, words added: stand mid century
largest train gain, change: +0.632
largest train loss: wire basket with dividers
largest train loss, words added: hamper
largest train loss, change: -0.176
largest train loss, top 10 names with hamper: 4
largest train loss, of those, unjudged: 4
planned test comparisons: 5
p-value threshold: 0.01
synonyms, bm25, mean difference: 0.000
synonyms, bm25, wins, losses, ties: 0, 0, 30
synonyms, bm25, permutation p: 1.000
synonyms, bm25, established at 0.01: no
synonyms, bm25, t-test p: 1.000
synonyms, bm25, t-test agrees: yes
synonyms, bm25, 99% interval: 0.000 to 0.000
synonyms, bm25, interval agrees: yes
The list changes 14 train queries. Mean nDCG@10 goes from 0.695 to 0.722, and judged@10, the share of the top 10 with a judgment, rises too, from 0.930 to 0.944.
Of the changed train queries, 6, 5 score better and worse, respectively, and one query, midcentury tv unit, accounts for 0.473 of the net gain, gaining +0.632 with stand mid century added. The list was written from these queries, so even these numbers flatter it.
The largest loss, -0.176, shows drift: wire basket with dividers gets hamper, and 4 products whose names contain hamper enter its top 10. Of those, 4 are unjudged, so the metric counts them as irrelevant, which for hampers is a fair guess.
On the test queries, the list changes 1 query, indoor multi tiered plant stand, by adding unit. Judged@10 stays at 0.927, and the difference isn't established (planned comparisons). On the queries it was written from, the list helped about as many queries as it hurt, and queries it wasn't written for rarely contain its words.
Working rule: Keep a synonym list for vocabulary gaps you have seen, write each entry from a failing query, and read the products each entry adds before you keep it. Never report a list's gain on the queries you wrote it from, and keep an entry only if a planned comparison on the test queries shows a gain. Test any expansion of semantic retrieval first: the LLM's rewrites, which add synonyms and also broaden and drop words, hurt it. When the gaps are too many to list, try stemming or learned sparse retrieval instead.
商品テキストでクエリ分類器を学習する
クエリの語を書き換える代わりに、そのクエリがどの種類の商品を求めているかを予測する方法がある。クエリ分類(query classification)は、クエリをストアの分類体系(タクソノミー)のクラスに割り当てる。たとえばRange Hoodsがそのようなクラスである。商品検索では、「クエリを事前に定義された商品タクソノミーに対応づけることは、eコマースのクエリ理解パイプラインにおける重要なステップである」(Skinner and Kallumadi, 2019)。予測されたクラスは、検索をカタログの適切な部分へ向ける手がかりになる。分類器の学習には通常、ラベル付きクエリが必要である。Skinner and Kallumadi は、既存の商品タクソノミーの対応づけがクエリ分類を改善し、ラベル付きデータの必要量を減らしうると報告している。彼らは、クラスが既知である商品タイトルで事前学習を行い、その後、少数のラベル付きクエリでファインチューニングしている。
このストアはさらに踏み込み、ラベル付きクエリを一切使わない。そもそも持っていないからである。WANDS は各クエリにquery_classを与えており、それは「クエリが属するカテゴリ」(WANDS)である。しかし第2章で示すとおり、これは予測値であり、誤った値も含まれる。しかも、本書で使う WANDS のサンプルは1クラスにつき高々1件のクエリしか持たない(examples/data/wands/README.md)ため、学習に使えるクエリが2件そろうクラスは存在しない。そこで、product_classを持つ商品で学習し、その分類器をクエリに適用する。
ナイーブベイズ(naive Bayes)分類器は、商品テキストからクラスをわずか数行で学習できる。言葉で言えば、ナイーブベイズは、商品の中でそのクラスが多く、かつクエリの語がそのクラスの商品テキストの中で多く現れるとき、そのクラスをクエリにとって尤もらしいと判断する。語は互いに独立であると仮定する。これが「ナイーブ」の意味である。各カウントには1を加える。これにより、あるクラスで一度も見られなかった語があっても、そのクラスが候補から外れることはない。
predicted class = argmax over classes c of log P(c) + sum over the query's words w of log P(w | c)
P(w | c) = (count of w in class c's text + 1) / (number of words in class c's text + vocabulary size)
これを商品テキストの語数から手作業で構築し、1.9.1の scikit-learn のMultinomialNBと照合したうえで、その予測をquery_class、および各クエリの exact 商品のクラスと比較する。
1"""A naive Bayes query classifier built by hand from product text, checked against scikit-learn's MultinomialNB and2compared with each query's exact products. The prose's point rests on the two "queries where most exact products3have" lines and on the agreement line with MultinomialNB."""4import numpy as np56from lib.queries import class_rows, train_classifier7from lib.store import load_labels, load_products, load_queries, product_text89products, queries, labels = load_products(), load_queries(), load_labels()10rows = class_rows(products) # one row per (product, class) for products with a class11vectorizer, model = train_classifier(products) # the same, by scikit-learn's MultinomialNB12words = vectorizer.transform(product_text(rows)) # word counts: one row per (product, class), one column per word13classes = np.array(sorted(rows["label"].unique()))14print("product classes:", len(classes))15print("products without a class:", (products["product_class"] == "").sum())16print("products with several classes:", products["product_class"].str.contains("|", regex=False).sum())17# query classes whose name matches no product class18missing = queries["query_class"].dropna()[lambda names: ~names.isin(classes)]19print("query classes that no product has:", len(missing))20print("query classes that no product has, names:", "; ".join(missing))2122# Naive Bayes: log P(class) + sum over the query's words of log P(word | class), each word count smoothed by 123word_counts = np.vstack([np.asarray(words[(rows["label"] == name).to_numpy()].sum(axis=0)) for name in classes])24log_prior = np.log(rows["label"].value_counts()[classes].to_numpy() / len(rows))25log_likelihood = np.log((word_counts + 1) / (word_counts.sum(axis=1, keepdims=True) + word_counts.shape[1]))26query_words = vectorizer.transform(queries["query"])27predicted = classes[np.asarray(query_words @ log_likelihood.T + log_prior).argmax(axis=1)]28print("same predictions as MultinomialNB:", (predicted == model.predict(query_words)).sum(), "of", len(queries))2930queries = queries.assign(predicted=predicted)31print("predicted class equals query_class:", (queries["predicted"] == queries["query_class"]).sum())32# judgment grade 2 is exact; a product's classes are joined by |, so they're split before matching33exact = labels[labels["grade"] == 2].join(products["product_class"].str.split("|"), on="product_id")34for column, name in [("predicted", "predicted class"), ("query_class", "query_class")]:35 share = [exact.loc[exact["query_id"] == query_id, "product_class"].apply(lambda names: label in names).mean()36 for query_id, label in queries[column].items()]37 print(f"queries where most exact products have the {name}:", (np.array(share) > 0.5).sum())38# outdoor light fixtures, desk and chair set, and pool floats39for query_id in [133, 255, 410]:40 query, split, label = queries.loc[query_id, ["query", "split", "predicted"]]41 print(f"{query_id} ({split}): {query} -> {label}"42 f" (query_class: {queries.at[query_id, 'query_class']})")43print("predicted class for 7qt slow cooker:", queries.at[62, "predicted"]) # its query_class has no products
python query-classes-by-hand.pyproduct classes: 410
products without a class: 800
products with several classes: 620
query classes that no product has: 1
query classes that no product has, names: Crock Pots & Slow Cookers
same predictions as MultinomialNB: 80 of 80
predicted class equals query_class: 60
queries where most exact products have the predicted class: 63
queries where most exact products have the query_class: 63
133 (test): outdoor light fixtures -> Light Bulbs (query_class: Outdoor Wall Lights)
255 (test): desk and chair set -> Desks (query_class: Office Chairs)
410 (train): pool floats -> Deck Boxes (query_class: Lawn Games)
predicted class for 7qt slow cooker: Slow Cookers
商品が使うクラスは410種類である。800件の商品はクラスを持たないため除外し、620件の商品は複数のクラスを持つため、それぞれクラスごとに1行の学習データとして扱う。
手作業で構築した分類器は、80 of 80件のクエリでMultinomialNBと同じ予測を行う。その予測がquery_classと一致するのはそのうち60件であるが、query_classもまた推測にすぎない。判定と照らすと、2つの推測は引き分けである。63件のクエリでは exact 商品の大半が予測されたクラスを持ち、63件ではquery_classを持つ。この分類器が語だけでクエリを読むことは、次の3つの予測に表れている。outdoor light fixturesはLight Bulbsに、desk and chair setはDesksに、pool floatsはDeck Boxesになる。
サンプルの設計は、この検証で示せることを制限する。各クラスを検証するクエリは高々1件であるため、クラスごとの精度は測れない。また、80件のクエリが410クラスの一部しかカバーしないため、残りのクラスについては、この集計結果から何も言えない。これらのクエリでクエリ分類器を学習することはそもそもできず、2つの分類器を比べられるのも、それぞれがこの少数のクエリを正しく当てるかどうかという点だけである。さらに、1個のクエリクラス(Crock Pots & Slow Cookers)は、どの商品クラスの名前にも一致しないため、商品で学習した分類器にはこれを予測できない。
実践ルール: ラベル付きクエリがないときは、自社商品のクラスでクエリ分類器を学習し、他の分類器の推測ではなく、判定済みの exact 商品のクラスと照らして検証する。ログからラベル付きクエリが得られるようになったら、それで学習する。予測されたクラスはランキングのための手がかりとして扱い、ラベルとして扱ってはならない。
絞り込みではなく予測クラスをブーストする
ここでの予測クラスは、商品テキストで学習したナイーブベイズ分類器によるものである。予測クラスを検索に作用させる方法は二つある。フィルタは、予測クラスに属する商品だけを残す。ブーストは、予測クラスに属する商品のスコアに一定量を加えるので、ほかの商品を除外することなく、それらの商品の順位が上がる。フィルタの性能は分類器の性能を超えない。予測クラスの外にある関連商品は、すべて結果から消えてしまうからである。
フィルタにどれだけの代償があるかは、ストアの train 判定からわかる。train クエリでは、501 of 1937 件の正解商品が、そのクエリの予測クラスの外にある。ストアで最も優れたランカーであり、したがって打ち負かすべきランカーでもあるセマンティック検索の類似度にブーストを加える。train クエリで五つのブースト重みとフィルタを試す。最良のブーストを test クエリに適用し、この章の計画済みの比較のうち二つ目を行う。
1"""Counts the exact train products outside each query's predicted class, scores a class filter and several boosts on2the train queries, and takes the best boost to the test queries as a planned comparison. The prose's point rests on3the "exact train products outside the predicted class" line and on the planned comparison's lines."""4from lib.metrics import evaluate5from lib.queries import THRESHOLD, class_boost_run, in_class, report_planned, train_classifier6from lib.semantic import SemanticSearch7from lib.store import load_products, load_queries, qrels89products, queries = load_products(), load_queries()10vectorizer, model = train_classifier(products) # trained on product text, never on queries11predicted = dict(zip(queries.index, model.predict(vectorizer.transform(queries["query"]))))12semantic = SemanticSearch()13train, train_judgments = load_queries("train"), qrels("train")1415exact, outside = 0, 016for query_id, judged in train_judgments.items():17 member = in_class(products, predicted[query_id])18 exact += sum(grade == 2 for grade in judged.values())19 outside += sum(grade == 2 and not member[product_id] for product_id, grade in judged.items())20print(f"exact train products outside the predicted class: {outside} of {exact}")2122base = evaluate(semantic.run(train), train_judgments)23print(f"train ndcg@10 semantic: {base['ndcg@10'].mean():.3f}")24print(f"train judged@10 semantic: {base['judged@10'].mean():.3f}")25train_scores = {}26for weight in [None, 0.01, 0.02, 0.05, 0.1, 0.2]: # None: keep only the predicted class27 train_scores[weight] = evaluate(class_boost_run(semantic, train.index, predicted, products, weight), train_judgments)28 name = "filter" if weight is None else f"boost {weight}"29 print(f"train ndcg@10 {name}: {train_scores[weight]['ndcg@10'].mean():.3f}")30# every weight except None, the filter31boosts = [weight for weight in train_scores if weight is not None]32best = max(boosts, key=lambda weight: train_scores[weight]["ndcg@10"].mean())33for name, weight in [("filter", None), ("best boost", best)]:34 print(f"train judged@10 {name}: {train_scores[weight]['judged@10'].mean():.3f}")35print("best boost on train:", best)3637print(f"\nthe planned test comparison, threshold {THRESHOLD:.2f}:")38test, test_judgments = load_queries("test"), qrels("test")39boosted = evaluate(class_boost_run(semantic, test.index, predicted, products, best), test_judgments)40plain = evaluate(semantic.run(test), test_judgments)41print(f"test judged@10 semantic: {plain['judged@10'].mean():.3f}")42print(f"test judged@10 boosted: {boosted['judged@10'].mean():.3f}")43report_planned("class boost, semantic", boosted["ndcg@10"], plain["ndcg@10"])
python class-boost-train-and-test.pyexact train products outside the predicted class: 501 of 1937
train ndcg@10 semantic: 0.772
train judged@10 semantic: 0.964
train ndcg@10 filter: 0.675
train ndcg@10 boost 0.01: 0.773
train ndcg@10 boost 0.02: 0.774
train ndcg@10 boost 0.05: 0.768
train ndcg@10 boost 0.1: 0.742
train ndcg@10 boost 0.2: 0.692
train judged@10 filter: 0.866
train judged@10 best boost: 0.966
best boost on train: 0.02
the planned test comparison, threshold 0.01:
test judged@10 semantic: 0.990
test judged@10 boosted: 0.993
class boost, semantic, mean difference: 0.005
class boost, semantic, wins, losses, ties: 7, 4, 19
class boost, semantic, permutation p: 0.174
class boost, semantic, established at 0.01: no
class boost, semantic, t-test p: 0.164
class boost, semantic, t-test agrees: yes
class boost, semantic, 99% interval: -0.002 to 0.017
class boost, semantic, interval agrees: yes
train クエリでは、フィルタは通常のランカーより成績が悪い。nDCG@10は 0.772 から 0.675 に下がり、judged@10は 0.964 から 0.866 に下がる。つまり、フィルタをかけると上位 10 件に、誰も判定していない商品も多く入る。
小さなブーストは train のスコアをほとんど動かさず、大きなブーストはスコアを下げる。nDCG@10 は、0.01 では 0.773、0.2 では 0.692 である。train での最良のブーストは 0.02 であり、そのときの nDCG@10 は 0.774、judged@10 は 0.966 である。
test クエリでは、judged@10 はブーストなしで 0.990、ブーストありで 0.993 であり、ブーストによる向上は確認されていない(計画済みの比較)。
実践ルール: 予測クラスでフィルタしてはならない。train クエリで調整した重みでブーストし、計画済みの比較で向上が確認された場合にのみブーストを残す。このストアでは確認されていないので、セマンティック検索はブーストなしのままにする。クラスによるフィルタを勧めるのは、買い物客がクラスを選んだ場合に限る。例えば、カテゴリをクリックした場合である。
この部分はまだ翻訳されていないため、英語で表示している。
Rewrite queries with an LLM
Query rewriting replaces the query with a text written to retrieve better. Where the corrector, the unit rules and the synonym list each fix one kind of gap, an LLM can fix spelling, expand abbreviations and add synonyms in one step, with no list to maintain. In rewrite-retrieve-read, the rewritten query goes to the retriever in place of the original (Ma et al., 2023). Studies report gains. With query2doc, which appends an LLM-written passage, a pseudo-document, to the query, BM25 improved by 3% to 15% on ad-hoc IR datasets, with text-davinci-003 writing the passages for MS MARCO and TREC DL queries (Wang et al., 2023). Other studies report failures. A comparison of 11 expansion methods, 12 datasets and 24 retrievers found that expansion helps weaker models and generally harms stronger ones (Weller et al., 2024). Another study found that LLM-based expansion can significantly degrade retrieval when the LLM lacks the knowledge or the query is highly ambiguous (Abe et al., 2025).
The rewrites that the examples read were recorded with the store's LLM, the open model named in the chapter's opening, run locally on each query alone. The prompt's instruction is: "Rewrite this search query from an online furniture and home-goods store so that a search engine finds what the shopper wants. Fix spelling, expand abbreviations and add common synonyms for the product type, but keep every requirement the shopper stated and add none of your own. Return a single line." The rest of the prompt gives the query and asks for JSON, and the recording's manifest holds it in full. The recording script embedded each rewrite as a query, with the same embedding model as the products. BM25 searches the rewrite's text, and semantic retrieval its embedding. The train queries come first, to see what the rewrites change before any test:
1"""Prints the store's recorded LLM rewrites for a few train queries, then scores BM25 and semantic retrieval on the2train queries, typed and rewritten. The prose's point rests on the nDCG@10 lines for both retrievers."""3from lib.lexical import LexicalSearch4from lib.metrics import evaluate5from lib.recorded import llm_rewrites, manifest6from lib.semantic import SemanticSearch7from lib.store import load_products, load_queries, qrels89recording = manifest("llm-rewrites")10print("model:", recording["model"])11print("embedding model:", recording["embedding_model"])12print("rewrite prompt, first line:", recording["prompts"]["rewrite"].split("\n")[0])13table, rewrite_vectors, _ = llm_rewrites()14rewrites = table.set_index("query_id")["rewrite"]15# the embeddings come in the table's row order, not query order: row maps each query_id to its row16row = {query_id: position for position, query_id in enumerate(table["query_id"])}17# a spelling fix, a product code, and malachi sled18for query_id in [20, 205, 313]:19 print(f"rewrite of {load_queries().at[query_id, 'query']}: {rewrites[query_id]}")2021queries, judgments = load_queries("train"), qrels("train")22products = load_products()23# judgment grade 2 is exact24exact = [product_id for product_id, grade in judgments[313].items() if grade == 2]25print("exact products for malachi sled:", "; ".join(products.loc[exact, "name"]))26bm25, semantic = LexicalSearch(products), SemanticSearch()27runs = {"bm25, typed": bm25.run(queries),28 "bm25, rewrite": bm25.run(queries.assign(query=rewrites[queries.index].to_numpy())),29 "semantic, typed": semantic.run(queries),30 "semantic, rewrite": {query_id: list(semantic.search_vector(rewrite_vectors[row[query_id]]).index)31 for query_id in queries.index}}32scores = {name: evaluate(run, judgments) for name, run in runs.items()}33for name, frame in scores.items():34 print(f"train ndcg@10 {name}: {frame['ndcg@10'].mean():.3f}")35 print(f"train judged@10 {name}: {frame['judged@10'].mean():.3f}")36for retriever in ["bm25", "semantic"]: # for choosing, not evidence37 change = (scores[f"{retriever}, rewrite"]["ndcg@10"] - scores[f"{retriever}, typed"]["ndcg@10"]).round(3)38 print(f"train queries better, worse, {retriever}: {(change > 0).sum()}, {(change < 0).sum()}")39 print(f"largest train loss, {retriever}: {queries.at[change.idxmin(), 'query']}")40 print(f"largest train loss, {retriever}, change: {change.min():+.3f}")
python llm-rewrites-on-train.pymodel: gemma4:12b-it-q4_K_M
embedding model: Snowflake/snowflake-arctic-embed-m-v1.5
rewrite prompt, first line: Rewrite this search query from an online furniture and home-goods store so that a search engine finds what the shopper wants. Fix spelling, expand abbreviations and add common synonyms for the product type, but keep every requirement the shopper stated and add none of your own. Return a single line.
rewrite of foutains with brick look: fountains with brick look, brick style water features, masonry fountains, faux brick fountains
rewrite of ines shag rug w003096809: Ines shag rug w003096809 area rug carpet
rewrite of malachi sled: Malachi sled sofa couch settee loveseat
exact products for malachi sled: malachi sled end table; malachi 44 '' console table; malachi sled coffee table
train ndcg@10 bm25, typed: 0.695
train judged@10 bm25, typed: 0.930
train ndcg@10 bm25, rewrite: 0.646
train judged@10 bm25, rewrite: 0.868
train ndcg@10 semantic, typed: 0.772
train judged@10 semantic, typed: 0.964
train ndcg@10 semantic, rewrite: 0.759
train judged@10 semantic, rewrite: 0.924
train queries better, worse, bm25: 23, 24
largest train loss, bm25: malachi sled
largest train loss, bm25, change: -0.644
train queries better, worse, semantic: 18, 25
largest train loss, semantic: wall design shelf
largest train loss, semantic, change: -0.653
Spelling comes out right (fountains with brick look, brick style water features, masonry fountains, faux brick fountains), and codes survive (Ines shag rug w003096809 area rug carpet). For malachi sled, a product line, the LLM guessed a sofa: it wrote Malachi sled sofa couch settee loveseat, while the exact products are malachi sled end table; malachi 44 '' console table; malachi sled coffee table.
On the train queries, the rewrite lowers nDCG@10 for both retrievers: BM25 from 0.695 to 0.646, and semantic retrieval from 0.772 to 0.759. Judged@10 falls for both, from 0.930 to 0.868 and from 0.964 to 0.924, so the rewrites surface products nobody judged, and part of each fall in nDCG@10 may come from them.
The losses aren't one bad query: the numbers of queries that score better and worse are 23, 24 for BM25 and 18, 25 for semantic retrieval. BM25's largest loss is malachi sled, the product line the LLM turned into a sofa, at -0.644, and semantic retrieval's is wall design shelf, at -0.653.
These train numbers shape expectations and prove nothing. The third and fourth of the chapter's 5 planned comparisons were fixed in advance, so they go to the test queries whatever the train queries show, and each counts as established if p is below 0.01. Before the test numbers arrive, pick one: does the rewrite help BM25, the weaker retriever, hurt semantic retrieval, the stronger one, or do neither?
1"""Scores BM25 and semantic retrieval on the test queries, as typed and rewritten, as the chapter's planned comparisons,2then repeats both on condensed runs as an exploratory check. The prose's point rests on the "established at 0.01" lines."""3from lib.lexical import LexicalSearch4from lib.metrics import evaluate5from lib.queries import THRESHOLD, condensed, report_planned, rewrite_runs6from lib.semantic import SemanticSearch7from lib.significance import compare8from lib.store import load_products, load_queries, qrels910queries, judgments = load_queries("test"), qrels("test") # scored on the human judgments11# for each retriever, its run on the rewrite, then its run on the query as typed12runs = rewrite_runs(queries, LexicalSearch(load_products()), SemanticSearch())1314print(f"the planned test comparisons, threshold {THRESHOLD:.2f}:")15for retriever, (rewritten, typed) in runs.items():16 name = f"llm rewrite, {retriever}"17 after, before = evaluate(rewritten, judgments), evaluate(typed, judgments)18 for form, frame in [("typed", before), ("rewrite", after)]:19 print(f"{name}, test ndcg@10 {form}: {frame['ndcg@10'].mean():.3f}")20 print(f"{name}, test judged@10 {form}: {frame['judged@10'].mean():.3f}")21 report_planned(name, after["ndcg@10"], before["ndcg@10"])2223 # Exploratory, never established: the same comparison on condensed runs, which drop unjudged products24 # rewritten comes first in each pair, as rewrite_runs returns them; the rewrite is "after"25 after, before = (evaluate(condensed(run, judgments), judgments)["ndcg@10"] for run in (rewritten, typed))26 # confidence = 1 - THRESHOLD: a 99% interval, at the level the planned comparisons use27 result = compare(after, before, confidence=1 - THRESHOLD)28 print(f"{name}, condensed ndcg@10 typed: {before.mean():.3f}")29 print(f"{name}, condensed ndcg@10 rewrite: {after.mean():.3f}")30 print(f"{name}, condensed, exploratory mean difference: {result['mean difference']:.3f}")31 print(f"{name}, condensed, exploratory permutation p: {result['permutation p']:.3f}")32 low, high = result["ci low"], result["ci high"]33 print(f"{name}, condensed, exploratory {1 - THRESHOLD:.0%} interval: {low:.3f} to {high:.3f}")
python llm-rewrites-on-test.pythe planned test comparisons, threshold 0.01:
llm rewrite, bm25, test ndcg@10 typed: 0.725
llm rewrite, bm25, test judged@10 typed: 0.927
llm rewrite, bm25, test ndcg@10 rewrite: 0.669
llm rewrite, bm25, test judged@10 rewrite: 0.903
llm rewrite, bm25, mean difference: -0.056
llm rewrite, bm25, wins, losses, ties: 13, 15, 2
llm rewrite, bm25, permutation p: 0.060
llm rewrite, bm25, established at 0.01: no
llm rewrite, bm25, t-test p: 0.060
llm rewrite, bm25, t-test agrees: yes
llm rewrite, bm25, 99% interval: -0.143 to 0.005
llm rewrite, bm25, interval agrees: yes
llm rewrite, bm25, condensed ndcg@10 typed: 0.778
llm rewrite, bm25, condensed ndcg@10 rewrite: 0.725
llm rewrite, bm25, condensed, exploratory mean difference: -0.053
llm rewrite, bm25, condensed, exploratory permutation p: 0.044
llm rewrite, bm25, condensed, exploratory 99% interval: -0.150 to -0.002
llm rewrite, semantic, test ndcg@10 typed: 0.830
llm rewrite, semantic, test judged@10 typed: 0.990
llm rewrite, semantic, test ndcg@10 rewrite: 0.749
llm rewrite, semantic, test judged@10 rewrite: 0.947
llm rewrite, semantic, mean difference: -0.081
llm rewrite, semantic, wins, losses, ties: 7, 19, 4
llm rewrite, semantic, permutation p: 0.000
llm rewrite, semantic, established at 0.01: yes
llm rewrite, semantic, t-test p: 0.000
llm rewrite, semantic, t-test agrees: yes
llm rewrite, semantic, 99% interval: -0.132 to -0.035
llm rewrite, semantic, interval agrees: yes
llm rewrite, semantic, condensed ndcg@10 typed: 0.834
llm rewrite, semantic, condensed ndcg@10 rewrite: 0.791
llm rewrite, semantic, condensed, exploratory mean difference: -0.043
llm rewrite, semantic, condensed, exploratory permutation p: 0.002
llm rewrite, semantic, condensed, exploratory 99% interval: -0.079 to -0.014
For BM25, nDCG@10 falls from 0.725 to 0.669, a difference that isn't established (planned comparisons). Judged@10 falls too, from 0.927 to 0.903.
Semantic retrieval shows an established loss: nDCG@10 falls from 0.830 to 0.749, with a permutation p-value that rounds to 0.000. Judged@10 falls as well, from 0.990 to 0.947.
Because judged@10 fell, we repeat both comparisons on condensed lists, which drop unjudged products before scoring. That check was chosen after seeing the drop, so it is exploratory and can't establish anything.
For semantic retrieval, condensed nDCG@10 still falls, from 0.834 to 0.791, a difference of -0.043, a permutation p of 0.002, and a 99% interval from -0.079 to -0.014. So the loss doesn't rest on unjudged products alone.
For BM25, condensed nDCG@10 goes from 0.778 to 0.725, with a permutation p of 0.044.
The rewrite didn't help BM25: it moved the other way from what Weller et al. and query2doc report, though not by an established amount. The rewrite's harm to semantic retrieval is what Weller et al. found for strong retrievers. Both results hold for this model, this prompt and these queries.
The queries that move most show what a rewrite does. Read them with the number of unjudged products in each rewritten top 10, which the metric counts as irrelevant:
1"""For each retriever, finds the test queries whose nDCG@10 moves most under the rewrite, and counts the unjudged2products in each rewritten top 10. The prose's point rests on the largest-loss and largest-gain lines, and on the3spelling-only check for BM25's largest gain."""4from bm25s.stopwords import STOPWORDS_EN56from lib.lexical import LexicalSearch7from lib.metrics import evaluate, ndcg_at_k8from lib.queries import rewrite_runs9from lib.recorded import llm_rewrites, probes10from lib.semantic import SemanticSearch11from lib.store import load_products, load_queries, qrels1213queries, judgments = load_queries("test"), qrels("test")14bm25 = LexicalSearch(load_products())15rewrites = llm_rewrites()[0].set_index("query_id")["rewrite"]16largest = {}17for retriever, (rewritten, typed) in rewrite_runs(queries, bm25, SemanticSearch()).items():18 change = evaluate(rewritten, judgments)["ndcg@10"] - evaluate(typed, judgments)["ndcg@10"]19 for kind, query_id in [("loss", change.idxmin()), ("gain", change.idxmax())]:20 label, largest[(retriever, kind)] = f"{retriever}, largest {kind}", query_id21 print(f"{label}: {queries.at[query_id, 'query']}")22 print(f"{label}, change: {change[query_id]:+.3f}")23 print(f"{label}, rewrite: {rewrites[query_id]}")24 unjudged = sum(product_id not in judgments[query_id] for product_id in rewritten[query_id][:10])25 print(f"{label}, unjudged products in the rewrite's top 10: {unjudged}")2627# BM25's largest gain: score the query with only its spelling fixed (chapter 6's probe), apart from the added words28query_id = largest[("bm25", "gain")]29# the spelling probes, keyed by the test query each one corrects30spelled = probes()[0].dropna(subset=["of_query_id"]).set_index("of_query_id")["query"]31if query_id in spelled.index:32 for name, text in [("typed", queries.at[query_id, "query"]), ("spelling fixed only", spelled[query_id])]:33 ranking = list(bm25.search(text, k=10).index)34 print(f"bm25, largest gain, ndcg@10 {name}: {ndcg_at_k(ranking, judgments[query_id], 10):.3f}")35 # bm25s's English stop words, which it drops before matching36 print("bm25 stop words among an and and:", ", ".join(word for word in ["an", "and"] if word in STOPWORDS_EN))
python rewrite-largest-changes.pybm25, largest loss: fold in half table
bm25, largest loss, change: -0.471
bm25, largest loss, rewrite: folding table, collapsible table, drop leaf table, gateleg table
bm25, largest loss, unjudged products in the rewrite's top 10: 3
bm25, largest gain: refrigerator with ice an water in door
bm25, largest gain, change: +0.159
bm25, largest gain, rewrite: refrigerator with ice and water in door, fridge with door dispenser, refrigerator with external water and ice dispenser
bm25, largest gain, unjudged products in the rewrite's top 10: 1
semantic, largest loss: pull out sleeper loveseat
semantic, largest loss, change: -0.304
semantic, largest loss, rewrite: pull out sleeper loveseat sofa couch convertible sofa sofa bed
semantic, largest loss, unjudged products in the rewrite's top 10: 4
semantic, largest gain: nautical platters
semantic, largest gain, change: +0.055
semantic, largest gain, rewrite: nautical platters serving trays seafood platters maritime serving boards
semantic, largest gain, unjudged products in the rewrite's top 10: 0
bm25, largest gain, ndcg@10 typed: 0.501
bm25, largest gain, ndcg@10 spelling fixed only: 0.501
bm25 stop words among an and and: an, and
Both largest losses come from a rewrite that drops or broadens what the shopper asked for. BM25's largest loss, -0.471 for fold in half table, comes from folding table, collapsible table, drop leaf table, gateleg table, which drops in half and adds other kinds of table; 3 of its top 10 are unjudged. Semantic retrieval's largest loss, -0.304 for pull out sleeper loveseat, comes from pull out sleeper loveseat sofa couch convertible sofa sofa bed, which widens a loveseat to any sofa; 4 of its top 10 are unjudged.
BM25's largest gain, +0.159 for refrigerator with ice an water in door, comes from refrigerator with ice and water in door, fridge with door dispenser, refrigerator with external water and ice dispenser. The rewrite fixes an, but with only that fix BM25 scores 0.501, the same as the query as typed, 0.501, because both spellings are stop words. The gain comes from the words the rewrite adds. Semantic retrieval's largest gain is +0.055, for nautical platters, rewritten as nautical platters serving trays seafood platters maritime serving boards.
Working rule: Don't put an LLM rewrite in front of a strong retriever without a planned comparison on the test queries. Read the per-query losses for dropped requirements and broadened products, which the prompt's "keep every requirement" doesn't prevent. The store's semantic retrieval, the ranker to beat, keeps searching the query as typed.
仮想の商品による検索(HyDE)
書き換えが LLM に、より良いクエリを求めるのに対し、HyDE(hypothetical document embeddings の略)は、そのクエリに答えるであろう文書を想像して書くよう求める。LLM がクエリに答えるものとして書いた仮想文書をエンコーダが埋め込むと、そのベクトルは、実在する文書が分布するコーパス埋め込み空間の近傍に位置する(Gao et al., 2023)。作り話の細部が真実である必要はない。著者らは、エンコーダの密なボトルネックが幻覚による細部を取り除くと論じているが、これは彼らの主張であって、測定結果ではない。主要な結果では InstructGPT(text-davinci-003)を温度 0.7 でサンプリングして用いている。パッセージランキングのベンチマークである TREC DL19 では、関連性ラベルなしで訓練された埋め込みモデル Contriever の nDCG@10 が、0 から 100 の尺度で 44.5 から 61.3 に向上した(Gao et al., Table 1)。ラベルで微調整した Contriever では、結果は LLM に依存した。小さい LLM では nDCG@10 がわずかに低下した。これは、能力の低い指示追従モデルが、微調整された検索器の全体的な性能を損なうことがあるためである。一方 InstructGPT では向上し、最も大きかった DL19 では 62.1 から 67.4 になった(Table 4)。
いくつかの拡張手法は、元のクエリを混ぜたまま保持する。HyDE は、仮想文書の埋め込みをクエリ自身の埋め込みと平均する(Gao et al., section 3.2)。適合性フィードバックは、最初の検索結果に対する判定からクエリを改善する手法であり、Rocchio の方式では、元のベクトルを和に残したまま、クエリベクトルを適合と判定された結果の方向へ動かす(Manning et al., 2008)。BM25 向けの query2doc は、生成したパッセージの前にクエリを 5 回繰り返し、元の語の重みが保たれるようにしている(Wang et al., 2023)。
HyDE の記録には、クエリごとに 1 つの仮想商品が含まれている。これは店の LLM がクエリだけから書いたもので、名前、クラス、説明から成り、商品として埋め込まれる。ここでの hyde 関数は、これをクエリの埋め込みと平均し、第 6 章が平均化の後に勧めているとおり、結果を長さ 1 に戻す。2 つの埋め込みは 1 点で異なる。クエリの埋め込みには埋め込みモデルのクエリ用プロンプトが付き、商品の埋め込みには、すべての商品と同様に、それが付かない。
hyde(query) = (embedding(hypothetical product) + embedding(query)) / 2, then scaled to length 1
train クエリでは、仮想商品の埋め込み単独も試す。また BM25 については、仮想商品のテキスト単独と、query2doc の重み付けに従ってその前にクエリを 5 回繰り返したものも試す。そのうえで、この章の計画済みの比較の最後を実行する。
1"""Scores HyDE, its parts and their combinations with BM25 and semantic retrieval on the train queries, then runs HyDE2against semantic retrieval as the chapter's last planned comparison on the test queries. The prose's point rests on3the train lines for the hypothetical product alone and on the planned comparison's lines."""4import numpy as np56from lib.lexical import LexicalSearch7from lib.metrics import evaluate8from lib.queries import THRESHOLD, report_planned9from lib.recorded import llm_rewrites10from lib.semantic import SemanticSearch11from lib.store import load_products, load_queries, qrels1213# the hypothetical products' embeddings come in the table's row order; zip pairs each with its query_id14table, _, hypothetical_vectors = llm_rewrites()15hypothetical, vectors = table.set_index("query_id")["hypothetical"], dict(zip(table["query_id"], hypothetical_vectors))16bm25, semantic = LexicalSearch(load_products()), SemanticSearch()171819def hyde(query_id):20 """Gao et al.'s average of the hypothetical product's embedding and the query's, scaled back to length 1."""21 average = (vectors[query_id] + semantic.query_vectors[query_id]) / 222 return average / np.linalg.norm(average)232425def runs(queries):26 ids, typed = queries.index, queries["query"]27 return {"semantic": semantic.run(queries),28 "hypothetical alone": {query_id: list(semantic.search_vector(vectors[query_id]).index) for query_id in ids},29 "hyde": {query_id: list(semantic.search_vector(hyde(query_id)).index) for query_id in ids},30 "bm25": bm25.run(queries),31 "bm25, hypothetical alone": bm25.run(queries.assign(query=ids.map(hypothetical))),32 "bm25, query five times plus hypothetical": bm25.run(queries.assign( # query2doc's weighting33 query=[" ".join([typed[query_id]] * 5 + [hypothetical[query_id]]) for query_id in ids]))}343536train = {name: evaluate(run, qrels("train")) for name, run in runs(load_queries("train")).items()}37for name, frame in train.items():38 print(f"train ndcg@10 {name}: {frame['ndcg@10'].mean():.3f}")39 print(f"train judged@10 {name}: {frame['judged@10'].mean():.3f}")40change = (train["hypothetical alone"]["ndcg@10"] - train["semantic"]["ndcg@10"]).round(3) # for choosing, not evidence41print(f"train queries better, worse, hypothetical alone: {(change > 0).sum()}, {(change < 0).sum()}")4243print(f"\nthe planned test comparison, threshold {THRESHOLD:.2f}:")44test = {name: evaluate(run, qrels("test")) for name, run in runs(load_queries("test")).items()45 if name in ["semantic", "hyde"]}46for name, frame in test.items():47 print(f"test judged@10 {name}: {frame['judged@10'].mean():.3f}")48report_planned("hyde, semantic", test["hyde"]["ndcg@10"], test["semantic"]["ndcg@10"])
python hyde-train-and-test.pytrain ndcg@10 semantic: 0.772
train judged@10 semantic: 0.964
train ndcg@10 hypothetical alone: 0.704
train judged@10 hypothetical alone: 0.890
train ndcg@10 hyde: 0.769
train judged@10 hyde: 0.946
train ndcg@10 bm25: 0.695
train judged@10 bm25: 0.930
train ndcg@10 bm25, hypothetical alone: 0.644
train judged@10 bm25, hypothetical alone: 0.854
train ndcg@10 bm25, query five times plus hypothetical: 0.694
train judged@10 bm25, query five times plus hypothetical: 0.912
train queries better, worse, hypothetical alone: 13, 29
the planned test comparison, threshold 0.01:
test judged@10 semantic: 0.990
test judged@10 hyde: 0.970
hyde, semantic, mean difference: -0.031
hyde, semantic, wins, losses, ties: 8, 14, 8
hyde, semantic, permutation p: 0.108
hyde, semantic, established at 0.01: no
hyde, semantic, t-test p: 0.121
hyde, semantic, t-test agrees: yes
hyde, semantic, 99% interval: -0.115 to 0.001
hyde, semantic, interval agrees: yes
train クエリでは、仮想商品単独により、意味検索の nDCG@10 は 0.772 から 0.704 に下がり、スコアが上がったクエリ数と下がったクエリ数は 13, 29 である。Judged@10 も同様に下がり、0.964 から 0.890 になる。
クエリと平均すると、スコアは 0.769、judged@10 は 0.946 である。BM25 でも同じ挙動を示す。クエリでは 0.695、仮想テキスト単独では 0.644、その前にクエリを 5 回繰り返した場合は 0.694 であり、judged@10 はそれぞれ 0.930、0.854、0.912 である。
クエリを残すと、仮想商品が失う分は回復するが、train クエリでは、どちらの検索器でも、この組み合わせはクエリ単独に何も上乗せしない。train の数値は設計の指針にすぎず、証拠となるのは計画済みの test 比較だけである。
test クエリでは、judged@10 は 0.990 から 0.970 になり、HyDE は意味検索との間に確立された差を示さない(計画済みの比較)。この結果は、店の 120 億パラメータのモデル gemma4:12b-it-q4_K_M を温度 0 で実行して得た、クエリごと 1 つの仮想商品に関するものである。Gao et al. ははるかに大きな LLM からサンプリングしており、微調整した検索器を向上させたのはそのモデルだけであった。
実践ルール: HyDE を試すときは、必ずクエリ自身の埋め込みを平均に加える。最大の効果が期待できるのは、ラベルなしで訓練されたエンコーダである。微調整されたエンコーダでは、Gao et al. が効果を確認したのは最大の LLM だけであり、店のモデル、プロンプト、エンコーダの組み合わせでは効果が見られなかった。店のエンコーダのように、これらのクエリですでに BM25 を上回っているエンコーダでは、クエリごとに LLM 呼び出しの費用を払う前に、HyDE を検証せよ。店では HyDE を使っていない。
フォローアップを単独で成立するクエリに変える
本章の冒頭で挙げた最後のギャップは会話に由来する。買い物客の次のメッセージは、直前のメッセージに依存することが多い。たとえば in white は、机の検索を絞り込むものである。検索システムが受け取るのは1つのテキストだけなので、フォローアップは単独で成立するクエリに変える必要がある。これは、それ以前のやり取りがなくても意味が通り、買い物客がなお求めている内容を保持したクエリである。会話型クエリ書き換えは、文脈に依存する質問を、同じ答えを持つ自己完結した質問に変換する手法であり、CANARD データセットにはそのような書き換えが40,527件収められている(Elgohary et al., 2019)。会話型検索の評価である TREC CAsT 2019 では、人手による書き換えが最良の自動システムを相対値で35%上回った(Dalton et al., 2020)。その後のプロンプト型 LLM を用いた研究では、「情報量の多いクエリ書き換えは、人手による書き換えと比べて、特にスパース検索器において、検索性能を大幅に向上させうる」ことが示された(Ye et al., 2023)。CAsT の後継である TREC iKAT 2025 では、ほとんどの run がパイプラインに LLM を用い、単一または複数のクエリ書き換えを行っていた(TREC iKAT 2025 overview)。
WANDS には会話が含まれていないため、本書のために店舗の会話を作成した。12 件のフォローアップがあり、それぞれがテスト用クエリを色、形、サイズ、仕上げのいずれか1つの属性で絞り込む。2つのターンだけを見た店舗の LLM が、それぞれを単独で成立するクエリに書き換えた。たとえば coat rack for bedroom の次に something in black が来る場合、これは black coat rack for bedroom に書き換えられる。判定は最初のクエリに対して商品を評価しており、絞り込み後のクエリに対するものではないため、nDCG ではフォローアップを採点できない。そこで、各上位10件について3種類の商品を数える。1つ目は絞り込みを保持する商品で、attributes またはテキストにその値を含むもの、たとえば black である(この例では attributes だけで数えた件数も表示する)。2つ目は適切な種類の商品で、最初のクエリに対して判定者が完全一致または部分一致と評価したものである。3つ目は両方を満たす商品である。フォローアップ単独を、2つのターンを連結したものおよび単独で成立するクエリと比較する。いずれもクエリとして埋め込み、最初のクエリをベースラインとする。さらに、単独で成立するクエリの上位100件に、その値を明記した商品だけを残すフィルタを加える。値は記録された会話から取得したが、実際のシステムではフォローアップから抽出しなければならない。
1"""Counts, in each conversation's top 10, the products that keep the refinement and the products of the right kind, for2the follow-up alone, the joined turns, the standalone query, and the standalone query filtered by the value. The prose's3point rests on the "refinement in text or attributes" and "right kind with the refinement" lines."""4import numpy as np56from lib.queries import mentions7from lib.recorded import llm_conversations8from lib.semantic import SemanticSearch9from lib.store import load_products, load_queries, product_text, qrels1011products, judgments, semantic = load_products(), qrels("test"), SemanticSearch()12attributes, text = products["attributes"], product_text(products) # the embeddings read only the text13conversations, vectors = llm_conversations() # follow-ups we wrote for the book, not shoppers'14print("conversations:", len(conversations))15# row 4, the fifth conversation, which the example prints16example = conversations.iloc[4]17print(f"first query: {load_queries().at[example['query_id'], 'query']}")18print(f"follow-up: {example['follow_up']}")19print(f"standalone: {example['standalone']}")2021shares, filtered_lengths = {}, [] # shares: (top 10, measure) -> one share per conversation22for row, (first, value) in enumerate(zip(conversations["query_id"], conversations["value"])):23 # the standalone query's top 100, the pool the filter draws from24 standalone = semantic.search_vector(vectors["standalone"][row], k=100).index25 stated = mentions(standalone, value, attributes) | mentions(standalone, value, text)26 tops = {"first query": semantic.search(first, k=10).index,27 "follow-up alone": semantic.search_vector(vectors["follow_up"][row], k=10).index,28 "turns joined": semantic.search_vector(vectors["joined"][row], k=10).index,29 "standalone": standalone[:10],30 "standalone, filtered": standalone[stated][:10]} # given the value, which a live system extracts31 filtered_lengths.append(len(tops["standalone, filtered"]))32 for name, top in tops.items():33 in_attributes = mentions(top, value, attributes)34 in_either = in_attributes | mentions(top, value, text)35 # the first query's grade 1 (partial) or 2 (exact); a product with no judgment counts as 036 right_kind = np.array([judgments[first].get(product_id, 0) >= 1 for product_id in top], dtype=bool)37 for measure, hits in [("refinement in attributes", in_attributes), ("refinement in text or attributes", in_either),38 ("right kind", right_kind), ("right kind with the refinement", in_either & right_kind)]:39 shares.setdefault((name, measure), []).append(hits.sum() / 10) # empty places count as misses40for (name, measure), values in shares.items():41 print(f"{name}, {measure}: {np.mean(values):.3f}")4243kept = np.subtract(shares["standalone", "refinement in text or attributes"], shares["turns joined", "refinement in text or attributes"])44print(f"standalone against turns joined, more, fewer, same: {(kept > 0).sum()}, {(kept < 0).sum()}, {(kept == 0).sum()}")45print("conversations the filter leaves with fewer than 10 products:", sum(length < 10 for length in filtered_lengths))
python follow-up-refinements.pyconversations: 12
first query: coat rack for bedroom
follow-up: something in black
standalone: black coat rack for bedroom
first query, refinement in attributes: 0.125
first query, refinement in text or attributes: 0.200
first query, right kind: 0.958
first query, right kind with the refinement: 0.175
follow-up alone, refinement in attributes: 0.433
follow-up alone, refinement in text or attributes: 0.950
follow-up alone, right kind: 0.058
follow-up alone, right kind with the refinement: 0.058
turns joined, refinement in attributes: 0.208
turns joined, refinement in text or attributes: 0.383
turns joined, right kind: 0.933
turns joined, right kind with the refinement: 0.325
standalone, refinement in attributes: 0.200
standalone, refinement in text or attributes: 0.392
standalone, right kind: 0.958
standalone, right kind with the refinement: 0.350
standalone, filtered, refinement in attributes: 0.583
standalone, filtered, refinement in text or attributes: 0.900
standalone, filtered, right kind: 0.675
standalone, filtered, right kind with the refinement: 0.675
standalone against turns joined, more, fewer, same: 5, 4, 3
conversations the filter leaves with fewer than 10 products: 3
フォローアップ単独では、上位10件のうち 0.950 が絞り込みを保持しているが、適切な種類の商品は 0.058 にとどまる。最初のクエリを含む形であれば、どれも適切な種類の商品を見つけられる。連結したターンでは 0.933、単独で成立するクエリでは 0.958 である。
これらの会話では、連結したターンも単独で成立するクエリも、絞り込みを求めていない最初のクエリより頻繁に絞り込みを保持する。0.383 と 0.392 に対し、最初のクエリは 0.200 である。
attributes だけで数えると割合は低くなり、0.208、0.200、0.125 となる。多くの商品が値をテキストにしか記載しておらず、埋め込みが読むのはそのテキストだけだからである。以下の結論は、属性またはテキストで数えた件数に基づく。この件数は過大になりうる。round legs に言及する商品も丸型として数えられるためである。
LLM による書き換えは、ターンの連結を上回らない。連結したターンと比べて、単独で成立するクエリが絞り込み済みの商品を多く、少なく、または同数保持する会話は 5, 4, 3 である。また、適切な種類で、かつ絞り込みも保持する商品が、単独で成立するクエリの上位10件に占める割合は 0.350 であり、連結したターンでは 0.325 である。
フィルタによってこの割合は 0.675 に上がるが、商品が10件に満たない会話が 3 件残る。
これら 12 件の会話は買い物客のものではなく私たちが作成したものである。したがって、この件数は診断であり、検証ではない。
実践ルール: フォローアップを単独で検索してはならない。少なくとも以前のターンと連結するか、単独で成立するように書き換える。絞り込みがカタログに明記された値を指す場合は、その値を抽出してブーストまたはフィルタに用い、残る商品が少なすぎるときはフィルタなしのリストに戻す。これらを信頼する前に、自社のログから得た会話で測定すること。
本番環境で起こる問題
LLM による書き換えはすべて、クエリの経路上でのモデル呼び出しである。 本章の例は、あらかじめオフラインで一度だけ記録した書き換えを読み込んでいる。しかし実際の検索ボックスでは、買い物客が待っている間にクエリごとにモデルが呼び出される。query2doc の著者らは、この手法には LLM の推論が必要であり、それがかなり遅くなりうると述べている(Wang et al., 2023)。さらに、クエリが長くなると BM25 による検索も遅くなる。これは測定値ではなく経験則であるが、頻出クエリの書き換えはオフラインで行って結果をキャッシュし、テストで改善が確認されたクエリに限ってオンラインでモデルを呼び出すのがよい。
書き換えは、特定のモデルと特定のプロンプトに属する。 モデルのバージョンが変わったり、プロンプトの文言が変わったりすると、どの書き換えも変わりうる。ストアに記録された manifest には、モデルのダイジェストと各プロンプトの全文が保存されている。そのどちらかが変わった場合は、あらためて測定する必要がある。
レキシコンはカタログに追随させなければならない。 先月のカタログから作った訂正器は、今月のブランド名を誤字として扱うことがある。レキシコンはインデックスと同時に再構築し、訂正器が変更したクエリはすべて元のクエリと並べてログに残す。そうすれば、tye → the のような過剰訂正を見つけられる。機械翻訳されたクエリでは、綴りの誤りによって検索が返す商品が変わる(Hanneman et al., 2024)。したがって、訂正器が見逃した誤りは、1 つのクエリに対する結果の不安定さとして現れると予想できる。
分類器はタクソノミーに従う。 商品クラスの名称変更、分割、統合を行ったときは、分類器を再学習する。どの商品クラスにも対応しないクエリクラス、たとえば Crock Pots & Slow Cookers は、予測されることがない。7qt slow cooker に対して、分類器は代わりに Slow Cookers を予測する。
書き換えられたクエリは、未判定の商品を上位に押し上げる。 本章で nDCG@10 によってスコアを付けた LLM ベースの変更は、すべて judged@10 を低下させた。書き換えを採用する前に、その上位 10 件に含まれる未判定の商品に判定を付けるか、第 2 章のように凝縮スコアで確認する。
実践ルール: 入力されたままのクエリと書き換え後のクエリの両方をログに残し、LLM による書き換えをキャッシュし、モデルとプロンプトを出力とともにバージョン管理し、カタログが変わるたびにレキシコンと分類器を再構築する。
この章で下した判断
以下の設定はすべて、train クエリで選んだものである。表には、この章で計画した 5 件の比較をテストクエリで行った結果を、1 列に 1 件ずつ示す。各比較は、変更を 1 つ加えた検索器を、入力されたままのクエリを使う同じ検索器と比べたものである。
| 指標 | BM25、同義語 | セマンティック検索、クラスブースト | BM25、LLM による書き換え | セマンティック検索、LLM による書き換え | セマンティック検索、HyDE |
|---|---|---|---|---|---|
| 平均差 | 0.000 | 0.005 | -0.056 | -0.081 | -0.031 |
| 勝ち、負け、引き分け | 0, 0, 30 | 7, 4, 19 | 13, 15, 2 | 7, 19, 4 | 8, 14, 8 |
| 置換検定の p 値 | 1.000 | 0.174 | 0.060 | 0.000 | 0.108 |
| 確立 | no | no | no | yes | no |
| t 検定の p 値 | 1.000 | 0.164 | 0.060 | 0.000 | 0.121 |
| 99% 区間 | 0.000 to 0.000 | -0.002 to 0.017 | -0.143 to 0.005 | -0.132 to -0.035 | -0.115 to 0.001 |
| t 検定の一致 | yes | yes | yes | yes | yes |
| 区間の一致 | yes | yes | yes | yes | yes |
- スペル:カタログが使っていない語だけを訂正する。 訂正器はストアの train のタイプミスを直せるが、タイプミスを含むクエリは数が少なすぎてテストできない。また、
tye dyeやice an waterを扱うには文脈が必要である。ストアはまだこれを実行していない。 - 単位:商品とクエリで、カタログ自身の表記から選んだ 1 つの書き方に統一する。 小数はそのまま保つ。サイズに関するクエリは数が少なすぎてテストできないため、ベースラインの BM25 は変更しない。
- 同義語:train クエリで見つかった語彙の不一致を埋める一覧を用意する。 対象は BM25 のみである。この一覧が変更したテストクエリは 1 件で、確立した差は見られなかったため、ベースラインは展開を行わない。
- クエリクラス:商品テキストで学習したナイーブベイズを使う。 サンプルにはクラスごとに多くても 1 件のクエリしかないためである。予測されたクラスはヒントとして扱う。フィルタは train で負け、最良のブーストもテストで確立しないため、セマンティック検索はブーストなしのままとする。
- LLM による書き換え:使わない。 セマンティック検索では負けが確立しており、BM25 では変化が確立していない。
- HyDE:使わない。 クエリと平均すると確立した差は見られず、仮想の商品だけを使うと train で負ける。
- 追質問:単独では決して検索しない。 発話を連結すると、LLM が作る単独クエリとほぼ同程度の結果になる。絞り込まれた値によるフィルタが次の段階であり、そのためには抽出した値とフォールバックが要る。
- 検索器は入力されたままのクエリを受け取る。 セマンティック検索は引き続き打ち負かすべきランカーであり、ステミングなしの BM25 は引き続きベースラインである。
- この章で示したこと: train クエリで正しそうに見える変更は、テストクエリでの計画した比較を通過しなければならない。ここで試した変更のうち、改善として通過したものはなかった。確立した差は LLM による書き換えだけで、それはセマンティック検索での負けである。
この版における本章
第2026.11.10版2026年11月19日時点で例が通過この章の12 例件のうち12件が合格
英語版の書籍(版2026.11.10)から翻訳した。