惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
Google DeepMind News
Google DeepMind News
J
Java Code Geeks
S
SegmentFault 最新的问题
Martin Fowler
Martin Fowler
罗磊的独立博客
T
The Blog of Author Tim Ferriss
N
Netflix TechBlog - Medium
大猫的无限游戏
大猫的无限游戏
Hugging Face - Blog
Hugging Face - Blog
Last Week in AI
Last Week in AI
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
H
Heimdal Security Blog
N
News and Events Feed by Topic
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
P
Privacy International News Feed
T
Tailwind CSS Blog
AWS News Blog
AWS News Blog
雷峰网
雷峰网
PCI Perspectives
PCI Perspectives
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
IT之家
IT之家
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Register - Security
The Register - Security
N
News | PayPal Newsroom
C
CERT Recently Published Vulnerability Notes
Microsoft Security Blog
Microsoft Security Blog
Attack and Defense Labs
Attack and Defense Labs
T
Tenable Blog
博客园 - 【当耐特】
Vercel News
Vercel News
GbyAI
GbyAI
博客园 - 司徒正美
量子位
T
Threat Research - Cisco Blogs
The Cloudflare Blog
The Last Watchdog
The Last Watchdog
MyScale Blog
MyScale Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Hacker News - Newest:
Hacker News - Newest: "LLM"
TaoSecurity Blog
TaoSecurity Blog
T
Troy Hunt's Blog
Y
Y Combinator Blog
P
Proofpoint News Feed
L
LINUX DO - 最新话题
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Jina AI
Jina AI
Recent Commits to openclaw:main
Recent Commits to openclaw:main
月光博客
月光博客
Apple Machine Learning Research
Apple Machine Learning Research

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
🧠 Building a semantic search with Pinecone and FastAPI — the right way
Python-T Poi · 2026-05-18 · via DEV Community

❓ Can you build a fast, scalable semantic search with Pinecone and FastAPI?

semantic search with pinecone and fastapi

Yes — and you don’t need a team of ML engineers. With semantic search using Pinecone and FastAPI , you can index unstructured text, serve low-latency queries, and deploy to production in hours. Most implementations treat embeddings as opaque vectors without considering performance trade-offs. This becomes a problem when recall drops at scale or latency spikes under load. Fix it by designing the system with data structure and query behavior in mind.

📑 Table of Contents

  • ❓ Can you build a fast, scalable semantic search with Pinecone and FastAPI?
  • 🧠 Embeddings — How Meaning Becomes Math
  • 📦 Pinecone — Why a Vector Database?
  • 🌱 Setup and Index Creation
  • 📤 Inserting Vectors in Bulk
  • ⚡ FastAPI — Designing a Low-Latency Search Endpoint
  • 🔌 Caching Repeated Queries
  • 🔍 Evaluation — Measuring Recall and Relevance
  • 🛠 Common Pitfalls
  • 🟩 Final Thoughts
  • ❓ Frequently Asked Questions
  • Can I use free-tier Pinecone for production?
  • Which embedding model should I pick for non-English content?
  • How do I update embeddings when content changes?
  • 📚 References & Further Reading

🧠 Embeddings — How Meaning Becomes Math

An embedding is a fixed-length vector that maps semantic meaning into a continuous space, enabling similarity search via geometric distance. The transformation is performed by a pre-trained transformer model like all-MiniLM-L6-v2 from Sentence Transformers, which maps variable-length text into a 384-dimensional vector space.

The model tokenizes input text, processes it through transformer layers, then applies mean pooling over the final hidden states to generate a single vector. Because the training objective includes contrastive learning on sentence pairs, semantically similar phrases — such as “How do I reset a password?” and “Forgot my login” — are embedded close together.

Distance in this space correlates with semantic similarity. Cosine similarity, which measures angular difference, is typically used instead of Euclidean distance because it’s invariant to vector magnitude.

from sentence_transformers import SentenceTransformer # Load a lightweight but effective model
model = SentenceTransformer('all-MiniLM-L6-v2') # Generate embedding for a query
sentence = "How to deploy FastAPI on Kubernetes"
embedding = model.encode(sentence) print(type(embedding), embedding.shape)



<class 'numpy.ndarray'> (384,)

Enter fullscreen mode Exit fullscreen mode

The output is a 384-dimensional numpy array. These embeddings must be computed once per document and stored for search. Query embeddings are generated on-demand and compared against indexed vectors.

"Semantic search isn't about keywords — it's about intent. The vector space learns what users mean, not just what they type."


📦 Pinecone — Why a Vector Database?

Traditional databases are not optimized for high-dimensional vector similarity search. A full scan over 1 million vectors at 384 floats per vector requires ~1.5 GB of data movement and O(n) comparisons — far too slow for interactive use.

Pinecone uses approximate nearest neighbor (ANN) algorithms like HNSW (Hierarchical Navigable Small World) to achieve search in roughly O(log n) time. HNSW builds a multi-layer graph structure that allows fast navigation to nearby vectors, trading a small reduction in recall for orders-of-magnitude lower latency.

Distances are computed using cosine similarity or Euclidean distance, depending on index configuration. The service exposes a simple API over gRPC via HTTPS, with each vector stored alongside metadata for retrieval.

🌱 Setup and Index Creation

Install the Pinecone client:

$ pip install pinecone-client


Collecting pinecone-client Downloading pinecone_client-3.1.0-py3-none-any.whl (48 kB)
...
Successfully installed pinecone-client-3.1.0

Enter fullscreen mode Exit fullscreen mode

Initialize and create an index:

import pinecone # Initialize connection
pinecone.init(api_key="your-api-key", environment="us-west1-gcp") # Create index if it doesn't exist
if 'semantic-search' not in pinecone.list_indexes(): pinecone.create_index( name='semantic-search', dimension=384, # Match embedding size metric='cosine' )

Enter fullscreen mode Exit fullscreen mode

The dimension must exactly match the embedding size (384 for all-MiniLM-L6-v2). The metric should be cosine for sentence embeddings, as angular similarity reflects semantic alignment better than magnitude-sensitive metrics.

📤 Inserting Vectors in Bulk

To index content, generate embeddings and upsert them as tuples of (id, vector, metadata):

index = pinecone.Index('semantic-search') documents = [ { "id": "doc_1", "text": "How to deploy FastAPI with Docker", "url": "/guides/fastapi-docker" }, { "id": "doc_2", "text": "Kubernetes secrets management best practices", "url": "/guides/k8s-secrets" }
] # Generate and upsert vectors
vectors = []
for doc in documents: vector = model.encode(doc["text"]).tolist() vectors.append((doc["id"], vector, {"text": doc["text"], "url": doc["url"]})) index.upsert(vectors=vectors)

Enter fullscreen mode Exit fullscreen mode

The upsert operation inserts new vectors or overwrites existing ones by ID. Pinecone batches writes internally and returns confirmation asynchronously.

print(index.describe_index_stats())



{'dimension': 384, 'index_fullness': 0.0, 'namespaces': {'': {'vector_count': 2}}, 'total_vector_count': 2}

Enter fullscreen mode Exit fullscreen mode

The index now contains two vectors. Metadata is stored alongside each vector and can be filtered on during queries. Avoid storing large fields in metadata — it increases transfer size and query latency. (More onPythonTPoint tutorials)


⚡ FastAPI — Designing a Low-Latency Search Endpoint

A production search endpoint must respond in under 200ms. This requires minimizing blocking operations, leveraging async I/O, and reusing embeddings where possible.

FastAPI supports this through Pydantic request validation and async route handlers. The endpoint accepts a query string, encodes it, searches Pinecone, and returns ranked results.

from fastapi import FastAPI
from pydantic import BaseModel
import uvicorn app = FastAPI() class SearchRequest(BaseModel): query: str top_k: int = 5 @app.post("/search")
async def semantic_search(request: SearchRequest): # Step 1: Encode the query query_vector = model.encode(request.query).tolist() # Step 2: Query Pinecone result = index.query( vector=query_vector, top_k=request.top_k, include_metadata=True ) # Step 3: Format response matches = [] for match in result['matches']: matches.append({ "id": match['id'], "score": match['score'], "text": match['metadata']['text'], "url": match['metadata']['url'] }) return {"results": matches} # Run with: uvicorn main:app -reload

Enter fullscreen mode Exit fullscreen mode

Start the server:

$ uvicorn main:app -reload


INFO: Uvicorn running on http://127.0.0.1:8000
INFO: Application startup complete.
INFO: reloading active

Enter fullscreen mode Exit fullscreen mode

Query the endpoint:

$ curl -X POST http://127.0.0.1:8000/search \ -H "Content-Type: application/json" \ -d '{"query": "how to deploy a Python API"}'


{ "results": [ { "id": "doc_1", "score": 0.876, "text": "How to deploy FastAPI with Docker", "url": "/guides/fastapi-docker" } ]
}

Enter fullscreen mode Exit fullscreen mode

The response includes cosine similarity scores. Higher values indicate greater relevance. Metadata filtering and namespace isolation can be added later for multi-tenancy or domain-specific routing.

🔌 Caching Repeated Queries

Approximately 20% of user queries repeat within short intervals. Cache results using Redis to avoid recomputing embeddings and reduce Pinecone call volume.

import redis r = redis.Redis(host='localhost', port=6379, db=0) @app.post("/search")
async def semantic_search(request: SearchRequest): cache_key = f"search:{request.query}:{request.top_k}" cached = r.get(cache_key) if cached: return json.loads(cached) # ... (compute result) # Cache for 10 minutes r.setex(cache_key, 600, json.dumps({"results": matches})) return {"results": matches}

Enter fullscreen mode Exit fullscreen mode

With caching, repeated queries drop from ~150ms to ~10ms. The embedding computation accounts for most of the saved latency, as the model inference is the slowest step in the chain.


🔍 Evaluation — Measuring Recall and Relevance

Correctness matters. Use recall@k to measure the percentage of queries where at least one relevant result appears in the top K results.

Construct a test set of query-ground truth pairs:

test_cases = [ { "query": "deploy FastAPI", "relevant_ids": ["doc_1"] }, { "query": "manage secrets in Kubernetes", "relevant_ids": ["doc_2"] }
]

Enter fullscreen mode Exit fullscreen mode

Compute recall@5:

def evaluate_recall(test_cases, top_k=5): hits = 0 for case in test_cases: result = index.query( vector=model.encode(case["query"]).tolist(), top_k=top_k ) returned_ids = {match['id'] for match in result['matches']} if any(rid in returned_ids for rid in case['relevant_ids']): hits += 1 return hits / len(test_cases) print(f"Recall@5: {evaluate_recall(test_cases):.2f}")



Recall@5: 1.00

Enter fullscreen mode Exit fullscreen mode

A score of 1.00 means all relevant items were retrieved in the top 5. Expand the test set to hundreds of labeled queries for meaningful benchmarking. For production systems, aim for recall@5 ≥ 0.90.

🛠 Common Pitfalls

  • Mismatched dimensions : Using a 768-dim embedding with a 384-dim index fails silently during upsert. Always validate model output shape matches index dimension.
  • Unnormalized vectors : Cosine similarity assumes unit-length vectors. If the model doesn’t normalize, apply L2 normalization before indexing.
  • Overloading metadata : Large metadata fields increase payload size and slow down queries. Store only IDs, titles, and URLs; fetch full content from a document store if needed.

🟩 Final Thoughts

Building semantic search with Pinecone and FastAPI is not integration work — it’s systems design. The performance and accuracy depend on understanding each component’s role: embedding models for semantic representation, vector databases for efficient similarity search, and API frameworks for low-latency delivery.

The stack is accessible, but success requires attention to detail. Model choice affects embedding quality and compute cost. Index parameters determine recall and speed. Caching reduces latency variance. These aren’t incidental — they define the user experience. Handle them deliberately, and you’ll ship a search system that works — not just one that runs.

❓ Frequently Asked Questions

Can I use free-tier Pinecone for production?

Yes, but only for low-traffic applications. The free tier supports up to 100MB of storage and limited queries per second. For higher load, upgrade to a paid plan with dedicated pods.

Which embedding model should I pick for non-English content?

For multilingual support, use paraphrase-multilingual-MiniLM-L12-v2 from Sentence Transformers. It supports 50+ languages and maintains strong cross-lingual similarity.

How do I update embeddings when content changes?

Re-encode the updated document and call upsert() with the same ID. Pinecone will overwrite the old vector. For bulk updates, batch the upserts to reduce latency.

📚 References & Further Reading