Top-1 Most Similar Document Retrieval

Basics
BasicsRAGVector SearchOpenAIAnthropicGoogle

Problem

Given a 1D query_vec of shape (D,) and a 2D document embedding matrix doc_vecs of shape (N, D) (all non-zero vectors), implement top1_doc_index(query_vec, doc_vecs) returning the int index of the document with the highest cosine similarity to query_vec.

Why It Matters: Nearest-neighbor vector lookup over a matrix of document embeddings is the core retrieval operation inside every RAG search engine.

Function Signature

import numpy as np

def top1_doc_index(query_vec, doc_vecs) -> int:
    """Return index of the document with highest cosine similarity to query_vec."""

Sample Input & Output

Example 1: Clear Semantic Winner

Input:

query_vec = [1.0, 0.0]
doc_vecs = [[0.0, 1.0], [0.9, 0.1], [-1.0, 0.0]]

Expected Output:

1

Explanation: Cosine similarities are [0.0, 0.9939, -1.0], so document index 1 wins.

Example 2: Magnitude-Invariant Retrieval

Input:

query_vec = [1.0, 1.0]
doc_vecs = [[100.0, 0.0], [0.5, 0.5]]

Expected Output:

1

Explanation: Although doc 0 has a huge norm (100), its cosine similarity is 0.707, whereas doc 1 is perfectly aligned (1.0).

Constraints & Edge Cases

  • Return the 0-based int index of the highest-similarity document.
  • Normalize both query_vec and each row of doc_vecs before taking the dot product.
  • Return a Python int (int(np.argmax(scores))).

Constraints & Evaluation Criteria

  • Return the 0-based `int` index of the highest-similarity document.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
q=[1,0], 3 docs
Expected Output / Criteria
1