Pinecone Tutorial for RAG

Create a Pinecone index, upsert vectors with metadata, query with filters and use namespaces.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 6 · Lesson 3 of 13 · Intermediate

Pinecone Tutorial for RAG

Create a Pinecone index, upsert vectors with metadata, query with filters and use namespaces.

Pinecone is a fully managed vector database: you create an index through an API and Pinecone runs, scales and backs it up for you. Recent versions can also embed your text for you (integrated embedding) and combine semantic and keyword (BM25) search. This lesson builds a RAG retriever on Pinecone with the current Python SDK.

What you will learn

  • How to create a Pinecone index with integrated embedding
  • How to upsert text documents with metadata into namespaces
  • How to search with metadata filters and use the results in a RAG answer
  • How to delete documents and organise data with namespaces

Prerequisites

Version note

This lesson follows the Pinecone Python SDK version 10 documentation (checked November 2026), which introduced a schema-based index API and a documents API. Older tutorials use create_index(dimension=..., spec=ServerlessSpec(...)) with index.upsert/index.query; those calls still work but are deprecated. If you are on an older SDK, follow the documentation for your version.

Installation and setup

pip install "pinecone>=10.1.0" python-dotenv
.env
PINECONE_API_KEY=your-pinecone-key

Step 1: Create an index with integrated embedding

The schema declares one text field, chunk_text, that Pinecone embeds automatically (with its default hosted embedding model) and also indexes for full-text keyword search.

pinecone_setup.py
import time
from dotenv import load_dotenv
from pinecone import Pinecone, SchemaBuilder

load_dotenv()
pc = Pinecone()                                  # reads PINECONE_API_KEY
INDEX_NAME = "rag-tutorial"

if not pc.indexes.exists(name=INDEX_NAME):
    schema = (SchemaBuilder()
              .add_string_field("chunk_text", full_text_search={"language": "en"}, embed={})
              .build())
    pc.indexes.create(name=INDEX_NAME, schema=schema)
    while not pc.indexes.describe(name=INDEX_NAME).status.ready:
        time.sleep(2)
print("index ready")

Step 2: Upsert documents

Each document needs a unique _id, the text field, and any metadata fields you want to filter on. Namespaces partition an index, for example one namespace per customer or per environment.

index = pc.index(name=INDEX_NAME)
NAMESPACE = "zentrix"

documents = [
    {"_id": "leave-1", "chunk_text": "Employees get 18 days of paid leave in their first year.", "dept": "hr"},
    {"_id": "leave-2", "chunk_text": "Up to 5 unused leave days can be carried over.", "dept": "hr"},
    {"_id": "exp-1", "chunk_text": "Expense claims must be submitted within 30 days.", "dept": "finance"},
    {"_id": "it-1", "chunk_text": "Laptops must use full-disk encryption.", "dept": "it"},
]
for start in range(0, len(documents), 96):         # at most 96 documents per call when embedding
    index.documents.upsert(namespace=NAMESPACE, documents=documents[start:start + 96])
time.sleep(10)                                      # writes become searchable after a short delay

Step 3: Search with a filter

results = index.documents.search(
    namespace=NAMESPACE,
    top_k=3,
    score_by=[{"type": "embed", "fields": ["chunk_text"], "query": "How much holiday do new staff get?"}],
    filter={"dept": {"$eq": "hr"}},
    include_fields=["chunk_text", "dept"],
)
for m in results.matches:
    print(f"{m.score:.3f}  {m.id}  {m.chunk_text}")
0.512  leave-1  Employees get 18 days of paid leave in their first year.
0.341  leave-2  Up to 5 unused leave days can be carried over.

Change "type": "embed" to "type": "text" to run BM25 keyword search on the same field, which helps for codes and names (Hybrid Search). Scores are example values.

Step 4: Use Pinecone as the RAG retriever

from rag_helpers import ask

def answer(question: str, dept: str | None = None) -> str:
    kwargs = {"filter": {"dept": {"$eq": dept}}} if dept else {}
    hits = index.documents.search(
        namespace=NAMESPACE, top_k=4, include_fields=["chunk_text"],
        score_by=[{"type": "embed", "fields": ["chunk_text"], "query": question}], **kwargs,
    ).matches
    sources = "\n".join(f'<source id="{m.id}">{m.chunk_text}</source>' for m in hits)
    return ask(f"<sources>\n{sources}\n</sources>\n\nAnswer only from the sources and cite "
               f"source ids in brackets. Say so if they do not contain the answer.\n\nQuestion: {question}")

print(answer("Can I carry over unused leave?", dept="hr"))

Step 5: Delete documents

index.documents.delete(namespace=NAMESPACE, ids=["it-1"])                 # by id
index.documents.delete(namespace=NAMESPACE, filter={"dept": {"$eq": "finance"}})   # by filter

Use stable IDs such as doc_id:chunk_index so that re-indexing a changed document can delete its old chunks first (Updating and Re-Indexing).

Bring your own embeddings

If you want to use your own embedding model, define a dense vector field instead of an embedded text field, with the dimension and metric of your model, for example {"fields": {"embedding": {"type": "dense_vector", "dimension": 384, "metric": "cosine"}}}, and a managed deployment (cloud and region). Then you send vectors yourself. Check the SDK documentation for the exact upsert and query format for vector fields.

Common errors and troubleshooting

  • Unauthorized: PINECONE_API_KEY missing or for another project.
  • No results right after upsert: writes are eventually consistent; wait a few seconds.
  • Too many documents per request: batch upserts (96 per call for integrated embedding).
  • Filter matches nothing: field names and value types must match exactly what you upserted.
  • Code from older tutorials fails: check which SDK version they were written for; v10 changed index creation and targeting.

Best practices

  • Use namespaces for tenant isolation, and still enforce tenant filters in your own code.
  • Keep source URLs, titles and dates as fields so answers can cite them.
  • Monitor usage and cost in the console; serverless pricing depends on storage, reads and writes.

Key takeaways

  • Pinecone is a managed vector database; SDK v10 uses pc.indexes.create(schema=...) and pc.index(name=...).
  • With integrated embedding, you upsert and search plain text through index.documents.
  • Use metadata filters, namespaces and stable IDs; switch between embedding and BM25 scoring per query.

Frequently asked questions

Pinecone or a self-hosted database?

Pinecone removes operations work; self-hosted databases (Qdrant, Milvus, pgvector) give more control and can be cheaper at scale. See Choosing a Vector Database.

Can I use Pinecone with LangChain or LlamaIndex?

Yes, both have Pinecone integrations; make sure the integration version supports your SDK version.

Practice exercises

  1. Load the sample policy files, chunk them and upsert them with source and chunk fields.
  2. Compare embed and text scoring on ten questions, including some with product codes.

Related tutorials