StackPractices
intermediate By Mathias Paulenko

Store and Query Embeddings in Pinecone Vector Database

Use Pinecone to store, query, and filter vector embeddings for semantic search with metadata filtering and namespace isolation

Topics: ai

Pinecone is a managed vector database built for semantic search and RAG: you hand it embeddings, it hands back the closest matches in milliseconds. This recipe covers index creation, upserts with metadata, filtered queries, and namespace isolation for multi-tenant apps.

When to Use This

  • Semantic search over documents, products, or knowledge bases
  • RAG (Retrieval-Augmented Generation) pipelines that need fast vector retrieval
  • Recommendation systems based on embedding similarity
  • Deduplication of semantically similar content

Skip Pinecone when the corpus is small or fully local. For a dataset you can fit on one machine, a local ChromaDB store avoids per-query network latency and per-vector costs — Pinecone pays off when you need managed scaling, multi-tenant namespaces, or serverless indexes that stay warm for many clients.

Prerequisites

  • Python 3.10+
  • pinecone package (pip install pinecone)
  • openai package for embeddings (pip install openai)
  • A Pinecone API key

Solution

1. Install Dependencies

pip install pinecone openai

2. Initialize Pinecone and Create an Index

from pinecone import Pinecone, ServerSpec
from openai import OpenAI

pc = Pinecone(api_key="your-pinecone-api-key")
openai_client = OpenAI()

# Create a serverless index (free tier)
index_name = "knowledge-base"

if index_name not in [idx.name for idx in pc.list_indexes()]:
    pc.create_index(
        name=index_name,
        dimension=1536,  # OpenAI text-embedding-3-small dimension
        metric="cosine",
        spec=ServerSpec(
            cloud="aws",
            region="us-east-1",
        ),
    )

index = pc.Index(index_name)

3. Generate Embeddings and Upsert

import uuid

def generate_embedding(text: str) -> list[float]:
    """Generate embedding using OpenAI."""
    response = openai_client.embeddings.create(
        model="text-embedding-3-small",
        input=text,
    )
    return response.data[0].embedding

def upsert_documents(documents: list[dict]) -> dict:
    """Upsert documents with embeddings and metadata.

    Args:
        documents: List of {text, metadata} dicts.

    Returns:
        Upsert response from Pinecone.
    """
    vectors = []
    for doc in documents:
        embedding = generate_embedding(doc["text"])
        vectors.append({
            "id": doc.get("id", str(uuid.uuid4())),
            "values": embedding,
            "metadata": {
                **doc.get("metadata", {}),
                "text": doc["text"][:500],  # Store truncated text for retrieval
            },
        })

    return index.upsert(vectors=vectors)

# Upsert sample documents
upsert_documents([
    {
        "id": "doc1",
        "text": "Redis is an in-memory data structure store used as a cache and database.",
        "metadata": {"category": "database", "source": "docs"},
    },
    {
        "id": "doc2",
        "text": "PostgreSQL is a capable open-source relational database system.",
        "metadata": {"category": "database", "source": "docs"},
    },
    {
        "id": "doc3",
        "text": "Docker containers package applications with their dependencies.",
        "metadata": {"category": "devops", "source": "tutorial"},
    },
])

4. Query for Similar Vectors

def search_similar(
    query: str,
    top_k: int = 5,
    metadata_filter: dict | None = None,
) -> list[dict]:
    """Search for similar documents.

    Args:
        query: Query text.
        top_k: Number of results to return.
        metadata_filter: Metadata filter dict.

    Returns:
        List of {id, score, metadata} dicts.
    """
    query_embedding = generate_embedding(query)

    results = index.query(
        vector=query_embedding,
        top_k=top_k,
        include_metadata=True,
        filter=metadata_filter,
    )

    return [
        {
            "id": match["id"],
            "score": match["score"],
            "metadata": match["metadata"],
        }
        for match in results["matches"]
    ]

# Semantic search
results = search_similar("in-memory cache for fast lookups", top_k=3)
for r in results:
    print(f"Score: {r['score']:.3f} | {r['metadata']['text'][:80]}")

5. Metadata Filtering

# Filter by category
results = search_similar(
    "database for web applications",
    top_k=5,
    metadata_filter={"category": {"$eq": "database"}},
)

# Filter by source and category
results = search_similar(
    "container deployment",
    top_k=5,
    metadata_filter={
        "source": {"$eq": "tutorial"},
        "category": {"$eq": "devops"},
    },
)

# Range filter
results = search_similar(
    "recent articles",
    top_k=10,
    metadata_filter={"timestamp": {"$gte": 1700000000}},
)

6. Namespaces for Multi-Tenant Isolation

def upsert_to_namespace(documents: list[dict], namespace: str) -> dict:
    """Upsert documents to a specific namespace."""
    vectors = []
    for doc in documents:
        embedding = generate_embedding(doc["text"])
        vectors.append({
            "id": doc["id"],
            "values": embedding,
            "metadata": doc.get("metadata", {}),
        })
    return index.upsert(vectors=vectors, namespace=namespace)

def search_namespace(query: str, namespace: str, top_k: int = 5) -> list[dict]:
    """Search within a specific namespace."""
    query_embedding = generate_embedding(query)
    results = index.query(
        vector=query_embedding,
        top_k=top_k,
        include_metadata=True,
        namespace=namespace,
    )
    return results["matches"]

# Each tenant gets isolated search
tenant_a_docs = [{"id": "a1", "text": "Tenant A pricing docs", "metadata": {"plan": "pro"}}]
tenant_b_docs = [{"id": "b1", "text": "Tenant B internal wiki", "metadata": {"plan": "free"}}]

upsert_to_namespace(tenant_a_docs, namespace="tenant-a")
upsert_to_namespace(tenant_b_docs, namespace="tenant-b")

results = search_namespace("caching strategies", namespace="tenant-a")

7. Batch Upsert for Large Datasets

def batch_upsert(documents: list[dict], batch_size: int = 100) -> int:
    """Upsert documents in batches to avoid rate limits.

    Args:
        documents: List of documents to upsert.
        batch_size: Number of vectors per batch.

    Returns:
        Total number of vectors upserted.
    """
    total = 0
    for i in range(0, len(documents), batch_size):
        batch = documents[i:i + batch_size]

        # Generate embeddings in batch
        texts = [doc["text"] for doc in batch]
        response = openai_client.embeddings.create(
            model="text-embedding-3-small",
            input=texts,
        )
        embeddings = [item.embedding for item in response.data]

        vectors = [
            {
                "id": doc.get("id", str(uuid.uuid4())),
                "values": emb,
                "metadata": doc.get("metadata", {}),
            }
            for doc, emb in zip(batch, embeddings)
        ]

        index.upsert(vectors=vectors)
        total += len(vectors)
        print(f"Upserted batch {i // batch_size + 1}: {total} total")

    return total

8. Retries and Index Health Checks

Pinecone calls are network I/O — wrap them with a short retry so a transient timeout or 429 doesn’t kill an ingestion job:

import time

def upsert_with_retry(vectors: list[dict], attempts: int = 3) -> dict:
    """Upsert with exponential backoff on transient failures."""
    for attempt in range(1, attempts + 1):
        try:
            return index.upsert(vectors=vectors)
        except Exception as exc:
            if attempt == attempts:
                raise
            wait = 2 ** attempt
            print(f"Upsert failed ({exc}), retrying in {wait}s")
            time.sleep(wait)

# Inspect the index before and after large loads
stats = index.describe_index_stats()
print(f"Total vectors: {stats['total_vector_count']}")
print(f"Per-namespace: {stats['namespaces']}")

describe_index_stats() is the fastest way to confirm an upsert actually landed. Note that fresh writes can take a few seconds to become queryable, so don’t assert on the count immediately after a bulk load.

A runnable single-file version of this pipeline lives in the companion repo.

How It Works

flowchart diagram: Documents
  1. Index creation specifies the vector dimension (must match the embedding model) and similarity metric (cosine, euclidean, or dotproduct).
  2. Upsert stores vectors with optional metadata. Each vector has a unique ID, values (the embedding), and metadata (key-value pairs for filtering).
  3. Query converts the query text to an embedding, searches for the nearest vectors by cosine similarity, and returns the top K matches with scores.
  4. Metadata filtering uses MongoDB-like operators ($eq, $ne, $in, $gte, $lte) to narrow results before vector similarity search — see the Pinecone metadata filtering docs for the full operator list.
  5. Namespaces partition the index into isolated subsets. Queries in one namespace don’t see vectors from another, enabling multi-tenant setups.

Two trade-offs worth knowing before you commit: serverless indexes bill per storage and per read/write unit, so a small high-traffic workload can cost more than a pod-based index; and freshly upserted vectors aren’t instantly queryable — there’s a short propagation delay that breaks naive “upsert then immediately count” tests.

Variants

# Pinecone supports hybrid search with sparse vectors
from pinecone import SparseValues

def upsert_hybrid(doc_id: str, text: str, dense_values: list[float], sparse_values: dict):
    """Upsert one document with dense and sparse vectors."""
    index.upsert(vectors=[{
        "id": doc_id,
        "values": dense_values,
        "sparse_values": SparseValues(
            indices=sparse_values["indices"],
            values=sparse_values["values"],
        ),
        "metadata": {"text": text},
    }])

# Query with both dense and sparse vectors
dense_query = generate_embedding("semantic search over my docs")
sparse_query = {"indices": [12, 450, 1024], "values": [0.8, 0.6, 0.4]}  # from a BM25/SPLADE encoder

results = index.query(
    vector=dense_query,
    sparse_vector=SparseValues(
        indices=sparse_query["indices"],
        values=sparse_query["values"],
    ),
    top_k=10,
    include_metadata=True,
)

Hybrid search blends exact keyword matching (sparse) with semantic similarity (dense). It follows the RAG hybrid search pattern and usually beats pure dense retrieval on names, error codes, and other exact terms embeddings handle poorly.

Delete by Metadata Filter

def delete_by_filter(metadata_filter: dict) -> dict:
    """Delete all vectors matching a metadata filter."""
    return index.delete(filter=metadata_filter)

# Delete all documents from a specific source
delete_by_filter({"source": {"$eq": "deprecated"}})

Fetch by ID

def fetch_vectors(ids: list[str]) -> dict:
    """Fetch vectors by their IDs."""
    return index.fetch(ids=ids)

result = fetch_vectors(["doc1", "doc2"])
for vid, vector in result["vectors"].items():
    print(f"ID: {vid}, Values: {vector['values'][:5]}...")

Best Practices

  • For a deeper guide, see Compare Text Semantic Similarity with OpenAI Embeddings.

  • Use batch embeddings API — generating embeddings one at a time is 10x slower than batching

  • Store truncated text in metadata — Pinecone doesn’t store full documents; keep text in metadata for retrieval

  • Use namespaces for tenants — cheaper and faster than separate indexes for each tenant

  • Monitor index size — Pinecone has storage limits per plan; delete old vectors with delete(filter=...) and check usage with describe_index_stats()

Common Mistakes

  • Mismatched dimensions — the index dimension must match the embedding model’s output dimension exactly; switching from text-embedding-3-small to 3-large requires a new index
  • Not using metadata filtering — retrieving all vectors and filtering client-side is slow and expensive
  • Upserting one vector at a time — batch upserts are considerably faster and avoid rate limits
  • Using the wrong metric — cosine is best for normalized text embeddings; dotproduct for unnormalized
  • Expecting instant read-after-write — a query fired immediately after a bulk upsert can miss fresh vectors; poll describe_index_stats() instead of asserting on query results

Frequently Asked Questions

What embedding model should I use?

text-embedding-3-small (1536 dimensions) is a good default. Move to text-embedding-3-large (3072 dimensions) only if your recall tests show the extra cost is worth it.

How much does Pinecone cost?

The free tier includes one serverless index with 100K vectors. Paid plans start at $70/month with higher storage and query limits — check Pinecone's pricing page for current numbers.

Can I use Pinecone with local embeddings?

Yes. Generate embeddings with any model (HuggingFace, Ollama) and upsert them to Pinecone — just make sure the index dimension matches whatever the model outputs.

How do I update an existing vector?

Upsert with the same ID. Pinecone overwrites the existing vector and metadata.

How long until an upsert is queryable?

Usually a few seconds — bigger bulk loads take longer to propagate across the index. Verify with describe_index_stats() rather than querying immediately.

Pinecone vs pgvector for a small project?

If you already run PostgreSQL and the corpus fits in it, pgvector avoids a second service. Pinecone wins when you need managed scale, namespaces, or hybrid search without operating the index yourself.

Can I back up a Pinecone index?

There's no native snapshot restore for serverless indexes. Keep the source documents and embedding pipeline so you can rebuild, or export vectors with list() + fetch() for critical data.