---
title: "Build Production Document RAG Pipelines with Pixeltable"
date: "2025-12-09"
dateModified: "2026-11-07"
author: "Pixeltable Team"
tags:
  - Document Processing
  - PDF
  - RAG
  - Retrieval
  - Pixeltable
  - LLM
  - Embeddings
  - OCR
  - Text Extraction
  - Knowledge Base
description: "Learn how to build end-to-end document processing pipelines that extract, chunk, embed, and search PDFs and documents using Pixeltable's declarative approach, with no external orchestration needed."
url: "https://www.pixeltable.com/blog/document-pdf-processing-rag-pixeltable"
---

# Build Production Document RAG Pipelines with Pixeltable

## The Document Processing Challenge

 
Building a document RAG (Retrieval-Augmented Generation) system sounds simple: extract text from PDFs, chunk it, embed it, and search. But production reality is messier:

 

 - PDFs have tables, images, headers, and footers that need special handling

 - Documents get updated and need re-processing

 - You need to track which chunks came from which documents

 - Embeddings need to stay in sync when documents change

 - The pipeline needs to scale to thousands of documents

 

 
Pixeltable solves all of this with a declarative approach that handles extraction, chunking, embedding, and search in a single unified system.

 
## Basic Document Pipeline

 
 
Let's start with a simple but complete document processing pipeline. The application file declares a table for the documents and a view that splits them into chunks:

 
```python

# app.py
import pixeltable as pxt
from pixeltable.functions.document import document_splitter
from pixeltable.functions.huggingface import sentence_transformer

TableModel = pxt.model_base()
embed_fn = sentence_transformer.using(model_id='sentence-transformers/all-MiniLM-L6-v2')

# A document library
class Library(TableModel, name='library'):
 document: pxt.Document # Native document type
 filename: pxt.String
 doc_type: pxt.String # 'report', 'general', 'faq', ...
 uploaded_at: pxt.Timestamp

# Step 1: Split each document into chunks of up to 512 tokens
class Chunks(
 TableModel,
 name='chunks',
 base=Library,
 iterator=document_splitter(Library.document, separators='token_limit', limit=512, overlap=50),
):
 # Step 2: An embedding index on the chunk text, updated on every insert
 __indexes__ = [pxt.EmbeddingIndex(text, embedding=embed_fn, name='chunk_idx')] # type: ignore[name-defined]
 
```

 
Create the tables:

 
```bash

pip install pixeltable sentence-transformers tiktoken
pxt init
pxt schema update app.py docs
 
```

 
Then insert documents and search them from Python:

 
```python

# search.py
import app

app.TableModel.bind_all('docs')

# Insert documents: chunking and embedding run during the insert
app.Library.insert([
 {'document': 'report_q1.pdf', 'filename': 'Q1 Report', 'doc_type': 'report', 'uploaded_at': '2025-01-15'},
 {'document': 'handbook.pdf', 'filename': 'Employee Handbook', 'doc_type': 'general', 'uploaded_at': '2025-01-10'},
])

# Search your documents
def search_docs(query: str, top_k: int = 5):
 chunks = app.Chunks
 sim = chunks.text.similarity(string=query)
 return chunks.order_by(sim, asc=False).limit(top_k).select(
 chunks.filename, # Inherited from the library row
 chunks.text,
 chunks.pos, # Chunk position in document
 score=sim,
 ).collect()

# Find relevant passages
results = search_docs('What is the vacation policy?')
 
```

 
## Advanced: Handling Complex PDFs

 
 
Real PDFs have tables, images, and complex layouts. Splitting a PDF by page keeps each page's extracted text next to an image of that page, and an LLM can clean up the text. The OpenAI columns from here on need `pip install openai` and `OPENAI_API_KEY` in the environment before the first `pxt` command, since the `pxt` daemon reads its environment once when it starts:

 
```python

# app.py: add this import at the top of the file
from pixeltable.functions import openai

# app.py (continued)
# One row per PDF page: the page's extracted text and an image of the page
class Pages(
 TableModel,
 name='pages',
 base=Library,
 iterator=document_splitter(Library.document, separators='page', elements=['text', 'image'], metadata='page'),
):
 # Use an LLM to clean and structure the extracted text
 cleaned_text = openai.chat_completions(
 model='gpt-4o-mini',
 messages=[{
 'role': 'system',
 'content': 'Clean and structure the following extracted document text. Fix extraction errors, remove headers/footers, and format properly.'
 }, {
 'role': 'user',
 'content': text # type: ignore[name-defined]
 }]
 ).choices[0].message.content
 
```

 
## Smart Chunking Strategies

 
 
Different documents need different chunking strategies. A view's base can be a filtered query, so each document type gets its own splitter:

 
```python

# app.py (continued)

# Strategy 1: Fixed-size chunks with overlap (good for general text)
class FixedChunks(
 TableModel,
 name='fixed_chunks',
 base=Library.where(Library.doc_type == 'general'),
 iterator=document_splitter(Library.document, separators='token_limit', limit=500, overlap=50),
):
 pass

# Strategy 2: One chunk per page, split further past 1,000 tokens (good for reports)
class PageChunks(
 TableModel,
 name='page_chunks',
 base=Library.where(Library.doc_type == 'report'),
 iterator=document_splitter(Library.document, separators='page,token_limit', limit=1000, metadata='page'),
):
 pass

# Strategy 3: Sentence-based chunks (good for FAQs; needs pip install spacy)
class SentenceChunks(
 TableModel,
 name='sentence_chunks',
 base=Library.where(Library.doc_type == 'faq'),
 iterator=document_splitter(Library.document, separators='sentence,token_limit', limit=200),
):
 pass
 
```

 
## Enriching Chunks with Metadata

 
 
Add useful metadata to each chunk for better retrieval. Replace the `Chunks` class in `app.py` with this version and run `pxt schema update app.py docs` again. The update adds the new columns and the summary index, and computes them for the chunks already stored:

 
```python

# app.py: the Chunks view, now with a summary and the key entities of each chunk
# (uses the openai import added at the top of the file)
class Chunks(
 TableModel,
 name='chunks',
 base=Library,
 iterator=document_splitter(Library.document, separators='token_limit', limit=512, overlap=50),
):
 # Each chunk also has its parent document's columns (filename, doc_type, uploaded_at)

 # Generate a summary for each chunk
 summary = openai.chat_completions(
 model='gpt-4o-mini',
 messages=[{'role': 'user', 'content': 'Summarize this text in 1-2 sentences: ' + text}], # type: ignore[name-defined]
 ).choices[0].message.content.astype(pxt.String)

 # Extract key entities from each chunk
 entities = openai.chat_completions(
 model='gpt-4o-mini',
 messages=[{
 'role': 'user',
 'content': 'Extract key entities (people, organizations, dates, numbers) from this text as JSON: ' + text, # type: ignore[name-defined]
 }],
 model_kwargs={'response_format': {'type': 'json_object'}},
 ).choices[0].message.content

 # Index both text and summary for different search strategies
 __indexes__ = [
 pxt.EmbeddingIndex(text, embedding=embed_fn, name='chunk_idx'), # type: ignore[name-defined]
 pxt.EmbeddingIndex(summary, embedding=embed_fn, name='summary_idx'),
 ]
 
```

 
Search the summaries with `app.Chunks.summary.similarity(string=query)`, or the text as before.

 
## Complete RAG Pipeline with LLM

 
 
Here's a full RAG system that retrieves relevant chunks and generates answers. Retrieval is a `@pxt.query` used as a computed column, so each question keeps the context its answer came from:

 
```python

# app.py (continued)

# Step 1: Retrieve the top-k chunks for a question
@pxt.query
def retrieve_context(question: str, top_k: int = 5):
 sim = Chunks.text.similarity(string=question, idx='chunk_idx')
 return Chunks.order_by(sim, asc=False).limit(top_k).select(Chunks.filename, Chunks.text)

@pxt.udf
def format_context(chunks: list[dict]) -> str:
 return '\n\n---\n\n'.join(f"[Source: {c['filename']}]\n{c['text']}" for c in chunks)

# A queries table to track all questions
class Queries(TableModel, name='queries'):
 question: pxt.String
 asked_at: pxt.Timestamp

 context = format_context(retrieve_context(question, top_k=5))

 # Step 2: Generate an answer using the retrieved context
 answer = openai.chat_completions(
 model='gpt-4o',
 messages=[{
 'role': 'system',
 'content': '''You are a helpful assistant that answers questions based on the provided context.
 Only use information from the context. If the answer isn't in the context, say so.
 Always cite your sources by mentioning the document name.'''
 }, {
 'role': 'user',
 'content': 'Context:\n' + context + '\n\nQuestion: ' + question
 }]
 ).choices[0].message.content
 
```

 
Run `pxt schema update app.py docs`, then ask questions. Retrieval and generation run on insert:

 
```python

# ask.py
import app

app.TableModel.bind_all('docs')

app.Queries.insert([
 {'question': 'What is the company vacation policy?', 'asked_at': '2025-01-15 10:00:00'},
 {'question': 'How do I submit an expense report?', 'asked_at': '2025-01-15 10:05:00'},
])

# View questions with their answers
app.Queries.select(app.Queries.question, app.Queries.answer).collect()
 
```

 
## Handling Document Updates

 
 
When a document changes, Pixeltable's [incremental processing](/blog/pixeltable-incremental-embedding-indexes) regenerates that document's chunks and recomputes their columns and index entries. Chunks of other documents stay as they are:

 
```python

# Update a document: only its chunks get regenerated and re-embedded
app.Library.update(
 {'document': 'handbook_v2.pdf'}, # New version
 where=app.Library.filename == 'Employee Handbook',
)

# Pixeltable then:
# 1. Splits the new version into chunks
# 2. Computes summaries, entities and embeddings for those chunks
# 3. Removes the old version's chunks from the views and the indexes
# 4. Records a new table version: pxt.get_table('docs/library:1') still reads version 1

# Delete a document: its chunks and embeddings are cleaned up
app.Library.delete(where=app.Library.filename == 'Q1 Report')
 
```

 
## Scaling to Large Document Libraries

 
 
Tips for handling thousands of documents:

 
```python

from datetime import datetime

import app

app.TableModel.bind_all('docs')

# 1. Use batch inserts: one insert call for many documents
app.Library.insert([
 {'document': f'doc_{i}.pdf', 'filename': f'Document {i}', 'doc_type': 'general', 'uploaded_at': '2025-02-01'}
 for i in range(1000)
])

# 2. Filter by document type or date in queries
docs_2025 = app.Library.where(app.Library.uploaded_at >= datetime(2025, 1, 1))

# 3. Pick the embedding model in app.py: a sentence-transformers model runs locally,
# openai.embeddings.using(model='text-embedding-3-small') calls the OpenAI API for each chunk

# 4. Check a view's columns and indexes
app.Chunks.describe()
 
```

 
## Why Pixeltable vs Traditional RAG Stacks

 
 
| Task | Traditional Stack | Pixeltable |
| --- | --- | --- |
| Text extraction | PyPDF2, pdfplumber, unstructured | document_splitter: text, page images, headings, page numbers |
| Chunking | LangChain, custom code | Built-in document_splitter iterator |
| Embeddings | Separate embedding service | Computed column, stored with each chunk |
| Vector store | Pinecone, Weaviate, pgvector | Built-in embedding index |
| Orchestration | Airflow, Prefect, custom | Automatic with dependencies |
| Updates | Manual re-indexing | New, updated and deleted documents update their chunks and index on write |
| Lineage | External tracking | Built-in versioning |

 
## Conclusion

 
 
Building production document RAG systems doesn't have to be complex. With Pixeltable's declarative approach:

 

 - Define your pipeline as computed columns

 - Let Pixeltable handle extraction, chunking, and embedding

 - Insert, update or delete a document, and its chunks, columns and index entries follow

 - Scale from prototypes to production without changing code

 

 
The best part? Your entire document pipeline (from raw PDFs to searchable embeddings) lives in one place, fully versioned and queryable.

 
The class-based `TableModel` receipt for the same job is [DocuVision](/blog/docuvision-pdf-chart-qa).

 
## Resources

 

 - [Pixeltable Documentation](https://docs.pixeltable.com)

 - [Production RAG: A Data-Centric Approach](/blog/production-rag-data-centric)

 - [Embedding Management Guide](/blog/embedding-management-guide)

 - [Incremental Embedding Indexes](/blog/pixeltable-incremental-embedding-indexes)

 - [Pixeltable on GitHub](https://github.com/pixeltable/pixeltable)