Most teams build their first retrieval system the same way: slice every document into fixed 512-token chunks, push them into a vector database, and hope the embedding model does the hard work. That hope gets you through a demo. It does not survive contact with real users.

In production, a legal contract falls apart when you sever a liability clause from its exceptions. API documentation turns useless when a code sample gets detached from its function signature. A customer support thread becomes noise when you rip a single complaint out of its conversational history. The problem is rarely the language model sitting at the end of the pipeline. The problem is what you feed it.

We learned this the hard way. Our initial retrieval layer looked standard but behaved inconsistently. So we rebuilt it around a simple idea: treat retrieval as measured infrastructure, not magic. Here is exactly what changed, and how we pushed recall to 95 percent while cutting the 95th-percentile latency from 850 ms to 320 ms.

The Fixed-Chunk Trap

Uniform token counts are easy to code and easy to explain. That convenience masks a basic truth: documents have structure. When you ignore that structure, you destroy signal.

Consider a ten-page master service agreement. A fixed 512-token slice will land mid-obligation, splitting a clause from the very cap table that limits it. The retrieval step then returns half a thought. The generator hallucinates the rest. In API documentation, a chunk that is too large dilutes the embedding with boilerplate headers, burying the specific method a developer needs. In support tickets, a fixed window treats a conversation as a bag of sentences, stripping away the back-and-forth that reveals what actually failed.

We stopped treating chunk size as a hyperparameter we guessed. We started treating it as a mapping exercise between the document type and the information architecture inside it.

Match Your Chunking to the Data

The fix is not one perfect chunk size. The fix is three distinct strategies tuned to three distinct data shapes.

Legal documents now go through recursive splitting. The algorithm first looks for the largest natural boundaries—sections, then subsections, then numbered clauses—and only falls back to smaller splits when necessary. This keeps a termination clause attached to its survival conditions. The retrieval step sees complete logical units, which sharply reduces the model’s temptation to invent missing exceptions.

API and code documentation get structure-aware chunking. Markdown headers, code fences, and parameter tables are parsed as atomic units. We do not split inside a code block. We keep docstrings adjacent to their signatures. The result is that a query for a specific class method retrieves the full context a developer needs: the description, the typed parameters, and the working example.

Support and conversational data use semantic chunking. Instead of counting tokens, we look for shifts in topic or intent. If a customer describes a bug in message three and pastes a stack trace in message seven, we chunk by meaning, not by message index. The retrieval layer then returns the full arc of the problem rather than a orphaned sentence.

Why Vector Search Alone Fails

Even perfect chunks die in a pure vector search. Dense embeddings excel at capturing meaning and synonymy, but they are notoriously fuzzy on exact strings. If an engineer searches for the precise error code ERR_CONNECTION_REFUSED, vector similarity might return a dozen conceptual neighbors and miss the exact match buried at rank fourteen.

Keyword search with BM25 has the opposite problem. It finds exact tokens but misses semantic intent. A user asking “why is my database down” will never match a document that says “troubleshooting connection timeouts.”

We now run both. Vector and keyword results are fed into Reciprocal Rank Fusion, which blends the two ranked lists without requiring calibrated scores. The fused list is then passed through a cross-encoder reranker. The reranker is slower than the initial retrieval, but it is far more precise because it judges query-document relevance directly rather than through compressed embeddings. That hybrid pipeline alone lifted our recall by 15 percent.

Fixing Bad Queries Before They Hit the Index

ユーザーは理想的な検索クエリを入力するわけではありません。途切れたログ行を貼り付けたり、「壊れている」とだけ入力したり、ドキュメントにはない専門用語を使ったりします。生のクエリをそのまま信じることは、ノイズを信じることと同じです。

現在、私たちは検索レイヤーに送る前に、すべての入力クエリを3〜5つのバリエーションに拡張しています。あるバリエーションは直接的な言い換え、別のものは想定される理想的なドキュメントのタイトル、3つ目は会話のフィラー(無駄な言葉)を取り除いて技術的なキーワードだけを抽出したものです。それぞれのバリエーションが埋め込み(embedding)され、検索されます。その後、候補プールを重複排除して統合します。

これは無料ではありません。追加の埋め込み呼び出しにはコストがかかり、数ミリ秒の遅延が生じます。しかし、再現率(recall)への効果は劇的でした。検索前にクエリを拡張することで、78%から96%へと向上したのです。検索精度が向上すれば、生成のウィンドウが縮小し、モデルが正しいコンテキストに基づいた回答を行えるようになるため、最終的にはダウンストリームでのコスト削減につながりました。検索ステップをわずかに高コストにすることは、長くてハルシネーション(幻覚)を含む生成ステップを繰り返すよりも安上がりなのです。

推測をやめ、検索を始めよう。

適切なチャンキング、ハイブリッド検索、クエリ拡張を導入した後も、組み合わせの爆発という問題に直面しました。チャンクサイズ、チャンクのオーバーラップ、top-kの検索深度、リランカーのカットオフ、融合の重み付けなど、すべてが相互に影響し合います。手動のグリッドサーチでは数週間かかり、それでも局所解に陥る可能性がありました。

私たちは、この探索空間を調査するためにベイズ最適化(Bayesian optimization)に切り替えました。すべての組み合わせを網羅的にテストするのではなく、検索アルゴリズムが「どの設定が良好なパフォーマンスを示す可能性が高いか」という確信を維持しながら、有望な領域へと段階的に絞り込んでいく手法です。

出力されるのは、単一の完璧な設定ではありません。それは「パレートの境界(Pareto frontier)」としての選択肢の集合です。一方の端には、高スループットのAPIサポートエンドポイント向けに最適化された、軽量な構成があります。これは高速な推論、適度な再現率、そして可能な限り低いレイテンシを実現します。もう一方の端には、法務レビュー向けの積極的な構成があります。こちらは、ミリ秒単位の速度を犠牲にしてでも、より深い検索、より強力なリランキング、より密なオーバーラップを行い、徹底さを追求します。境界が明確であるため、「万能な設定」を装うのではなく、製品に合わせて最適なポイントを選択できるのです。

実際の数値はどうなっているか

これらの変更により、システムは脆弱なプロトタイプから、測定可能なプロダクションパイプラインへと進化しました。

Recall@10は78%から95%に向上しました。これは、コーパス内に正解が存在する場合、20回中19回は見つけ出せることを意味します。

95パーセンタイルにおけるレイテンシは、850msから320msに低下しました。ハイブリッドスタックは理論上は重そうに聞こえますが、よりスマートなインデックス作成、軽量なリランカー、そして必要なときにのみ積極的なチャンクを提供する仕組みにより、システム全体が高速化されました。

ハルシネーション率は、ホールドアウトされたゴールデンデータセットを用いて人間がアノテーションした結果、12%から3%に減少しました。モデルが完全で関連性の高いコンテキストを受け取れるようになると、事実を捏造することがなくなります。

クエリあたりのコストは$0.008から$0.005に低下しました。検索精度が向上すれば、LLMへのプロンプトはより短く焦点が絞られたものになり、リカバリの回数も減ります。クエリ拡張による追加の埋め込みコストは、生成プロセスでの節約分によってはるかに上回る効果が得られます。

ゴールデンデータセットを構築し、検索をコードのように扱う

この話から一つだけ学んでほしいとすれば、それは「測定の規律」です。私たちは、実際の質問と検証済みの回答場所を含む、小さなゴールデンデータセットを構築しました。変更をプロダクションに適用する前に、必ずそのデータセットに対してテストを実行します。再現率とレイテンシは、ノートブックで目視するのではなく、リアルタイムで監視されます。

検索は研究用のデモではありません。インフラストラクチャです。スタックの他の部分と同様に、ユニットテスト、回帰ベンチマーク、および自動最適化を行う価値があります。トークン数への固執ではなく、ドキュメントの構造に基づいてチャンク化してください。ベクトル検索とキーワード検索をリランカーで組み合わせましょう。ユーザーが実際に書くクエリを拡張しましょう。そして、直感ではなく検索アルゴリズムに調整を任せるのです。

私たちが説明したパイプラインは理論上のものではありません。元の記事はこちらから読むことができます。また、この分野に関心のあるコミュニティと検索エンジニアリングについて議論したい場合は、GyaanSetu AI groupが公開されています。