A similarity metric turns a comparison between vectors into a score: larger values indicate closer matches. In vector search, the score ranks stored chunks against a query embedding and can determine whether a result is relevant enough for model context. section 5.4.1 section 5.4.3
A production search interface uses the score alongside retrieval controls:
- Return the top-k chunks after ranking candidates by similarity. section 5.4.1
- Discard results below score_threshold so weak matches do not consume context or confuse the response. section 5.4.1
- Apply metadata filters before ranking, such as restricting results to legal-department documents. section 5.4.1
- Return the score with chunk text, document identity, and metadata so callers can make inclusion and citation decisions. section 5.4.1
Cosine distance in pgvector
pgvector computes cosine distance with the <=> operator, where 0 means identical and larger values mean less similar. The implementation calculates 1 - distance, exposing a higher-is-better similarity score to the rest of the application. section 5.4.3
Listing 5.17 VectorStore abstract base class: search operation and result model
@dataclass
class SearchResult:
chunk_id: str
document_id: str
text: str
score: float #A
metadata: Dict[str, str]
class VectorStore(ABC):
# ... write operations from Listing 5.16 ...
@abstractmethod
def search(
self,
index_name: str,
query_embedding: List[float],
top_k: int = 5,
metadata_filters: Optional[Dict[str, str]] = None,
score_threshold: Optional[float] = None
) -> List[SearchResult]: #B
"""Find chunks most similar to the query embedding."""
passInspect the VectorStore search contract and SearchResult model, including query embeddings, top-k retrieval, metadata filters, thresholds, and returned scores. section 5.4.1













