📐 Mapping Meaning into High-Dimensional Space: The Foundations of Semantic Retrieval
Traditional lexical search engines (like standard SQL `LIKE` queries or basic inverted index Elasticsearch matchers) rely entirely on exact keyword overlaps, failing completely when users search using synonyms, paraphrases, or conceptual descriptions. Embedding Models and Semantic Search transform words, sentences, or entire documents into dense vectors of floating-point numbers (e.g., 768 or 1536 dimensions) using deep transformer architectures. In this latent vector space, semantic similarity corresponds to geometric proximity, allowing systems to retrieve conceptually related documents even when zero search keywords overlap.
from sentence_transformers import SentenceTransformer
import torch
# Load a high-performing multilingual embedding model
model = SentenceTransformer("text-embedding-3-small") # Or open-source "intfloat/multilingual-e5-large"
# Catalog items in different languages
catalog_items = [
"Waterproof running shoes for marathon training", # English
"Chaussures de course imperméables pour l'entraînement", # French
"Zapatillas de running impermeables para maratón" # Spanish
]
# User search query in Japanese
user_query = "マラソン用の防水ランニングシューズ"
# Generate dense vector embeddings
item_embeddings = model.encode(catalog_items, normalize_embeddings=True)
query_embedding = model.encode([user_query], normalize_embeddings=True)
# Compute Cosine Similarity (Dot product of normalized vectors)
similarities = torch.tensor(query_embedding) @ torch.tensor(item_embeddings).T
for item, score in zip(catalog_items, similarities[0]):
print(f"Score: {score:.4f} | Item: {item}")
from pymilvus import connections, Collection
# Connect to Milvus vector cluster
connections.connect("default", host="localhost", port="19530")
collection = Collection("patent_prior_art")
collection.load()
# Search parameters for HNSW index
search_params = {"metric_type": "COSINE", "params": {"ef": 64}}
results = collection.search(
data=[query_embedding],
anns_field="embedding",
param=search_params,
limit=10,
output_fields=["patent_id", "abstract"]
)
for hit in results:
print(f"Patent ID: {hit.entity.get('patent_id')} | Score: {hit.distance:.4f}")
from sklearn.cluster import DBSCAN
import numpy as np
# Unlabeled adversary behavioral descriptions
threat_reports = [
"Adversary executed PowerShell script to download payload from C2 server.",
"Attacker launched encoded PowerShell command to download backdoor executable.",
"Suspicious PowerShell invocation observed bypassing execution policy.",
"Phishing email delivered malicious VBA macro executing cmd.exe."
]
embeddings = model.encode(threat_reports)
# Cluster semantically similar threat behaviors using DBSCAN
clustering = DBSCAN(eps=0.15, min_samples=2, metric="cosine").fit(embeddings)
for report, cluster_id in zip(threat_reports, clustering.labels_):
print(f"Cluster {cluster_id}: {report}")
# Matryoshka embeddings allow truncating dimensions without retraining the model.
full_embedding = model.encode("Enterprise quarterly financial report") # e.g. 1536 dimensions
# Stage 1: Ultra-fast initial recall using truncated 128-dimension prefix
fast_recall_vector = full_embedding[:128]
# Stage 2: High-precision reranking using full 1536 dimensions on top-50 candidates
precision_vector = full_embedding[:]
job_description = "Seeking a Senior Cloud Architect with extensive Kubernetes, Terraform, and AWS microservices experience."
candidate_cv = "Experienced DevOps Engineer proficient in container orchestration (Docker/K8s), infrastructure-as-code (CloudFormation), and distributed systems on AWS."
jd_emb = model.encode(job_description, normalize_embeddings=True)
cv_emb = model.encode(candidate_cv, normalize_embeddings=True)
match_score = np.dot(jd_emb, cv_emb)
print(f"Semantic Candidate Match Score: {match_score:.4f}")
# Computes similarity matrix between 500 internal policies and 50 new SEC rules
policy_embeddings = model.encode(internal_policies)
sec_embeddings = model.encode(sec_new_rules)
similarity_matrix = sec_embeddings @ policy_embeddings.T
# Identifies internal policies needing revision based on low similarity scores to new regulations
new_ticket = "Checkout page is throwing a 500 internal server error when clicking pay."
existing_open_tickets = [
"Getting payment gateway 500 error during checkout process.",
"Unable to reset my account password via email link."
]
new_emb = model.encode(new_ticket, normalize_embeddings=True)
open_embs = model.encode(existing_open_tickets, normalize_embeddings=True)
scores = open_embs @ new_emb
if scores.max() > 0.88:
print("[!] Duplicate ticket detected. Auto-merging into parent incident.")
# Using medical domain embedding model (e.g., "pritamdeka/SBERT-pubmed-sentence-transformers")
clinical_note = "Patient presents with acute substernal chest pressure radiating to left arm."
snomed_concepts = [
"Myocardial infarction (disorder)",
"Gastroesophageal reflux disease",
"Musculoskeletal chest wall pain"
]
# Computes semantic alignment against authorized medical ontology database codes.
script_scene = "EXT. CYBERPUNK TOKYO - NIGHT. Neon signs flicker in heavy acid rain. A flying vehicle zooms past."
# Queries vector database of 500,000 stock video clips to retrieve matching cinematic visuals.
nl_query = "Function to calculate exponential backoff with jitter in Python"
# Retrieves exact implementation of retry decorator from internal company GitHub repositories.