← All Exercises

Rank Documents by Cosine Similarity

intermediatejavascript~30min

Background

Vector retrieval decides which context reaches the model. Ranking by cosine similarity on normalized vectors is the baseline every semantic search must beat.

Problem

Compute cosine similarity between a query vector and document vectors, then return the top-k document ids with their scores.

Input

JSON object: { query: number[], docs: [{ id, vector: number[] }], k: number }

Output

JSON array of { id, score } sorted by score desc, then id

Sample tests

Sample 1

Input: {"query":[1,0],"docs":[{"id":"d1","vector":[1,0]},{"id":"d2","vector":[0,1]},{"id":"d3","vector":[0.9,0.1]}],"k":2}
Expected: [{"id":"d1","score":1},{"id":"d3","score":0.9939}]

Sample 2

Input: {"query":[1,1],"docs":[{"id":"d1","vector":[-1,-1]}],"k":1}
Expected: [{"id":"d1","score":-1}]

Your solution

Learning objective

Implement the retrieval ranking that grounds a RAG pipeline.