Data engineering for generative AI is the work of turning scattered company content (SharePoint files, PDFs, ERP and Tally exports, CRM notes) into clean, permission-tagged, current chunks that a RAG system or AI agent can search. It covers extraction, cleaning, PII masking, chunking, embedding, indexing and incremental refresh, backed by quality checks and lineage.
Summary: the short version
- An LLM answers from whatever chunks retrieval hands it, so stale, duplicated or garbled data becomes wrong answers.
- A RAG pipeline is a familiar ELT pipeline plus three stages: chunking, embedding and loading a vector index with access metadata.
- Mask personal data such as PAN, Aadhaar and phone numbers before embedding; the DPDP Act, 2023 applies to text in your index and logs.
- Refresh incrementally using content hashes or change feeds, and delete chunks for removed documents in the same transaction.
- Do not embed ledgers and Tally exports. Load numbers into tables and let the AI query them with SQL; embed the documents that explain them.
Why is generative AI a data engineering problem?
Because an LLM can only answer from what your pipeline puts in front of it, so stale, duplicated, garbled or wrongly permissioned data turns directly into wrong or leaked answers. In retrieval-augmented generation (RAG), described by Lewis and colleagues in 2020, the system searches your documents for relevant passages and places them in the prompt before the model answers. The model only knows whichever chunk retrieval returned (new to this? read RAG explained). When users complain, the cause usually sits upstream:
| What users report | Usual data cause |
|---|---|
| "It quoted the old policy" | Index not refreshed, or the old version never deleted |
| "It says it can't find something that exists" | Scanned PDF with no OCR, or a table flattened into word soup |
| "Different answers to the same question" | The same circular sits in three folders in three versions |
| "It showed me HR data I shouldn't see" | No access metadata on chunks, so no filter at query time |
When learners in the Advanced Generative AI Course at Ivy Professional School build their first RAG app, week one goes on prompts. By week two, nearly every bug they chase lives in parsing, chunking or refresh. That is why we push developers heading into GenAI to learn the data engineering side properly.
What does a data pipeline for RAG look like?
It is an ELT-style pipeline with three new stages at the end: chunking, embedding and loading a vector index with access metadata. Raw files land unchanged in a landing zone, parsed and cleaned text forms the next layer, and chunks with embeddings are the served layer. If you know the bronze, silver and gold layers of a lakehouse, this is the same pattern applied to documents, and the trade-offs from ETL vs ELT still apply.
Those first two stages are the core of a data engineering job, and they are what learners practise in Ivy's data engineering course in India: SQL and Python transformations, Spark and Kafka for volume and streams, and Azure Data Factory, Data Lake and Databricks for scheduled cloud pipelines, across 160 hours and 10+ industry projects. The chunk, embed and index stages belong to our Advanced Generative AI Course, which covers RAG pipelines with vector database retrieval.
How should you clean, deduplicate and mask personal data before embedding?
Normalise the text, strip boilerplate and duplicates, and mask personal data before anything reaches the embedding model or the vector store.
- Clean: fix encoding errors, collapse whitespace, remove repeated headers, footers and page numbers, and drop near-empty pages.
- Deduplicate: exact duplicates via a content hash; near-duplicates ("v2", "v2-final", "v2-final-signed") by keeping only the latest version per document and flagging high-similarity pairs for review.
- Mask PII: regular expressions catch structured identifiers such as PAN, Aadhaar, mobile numbers and emails. Names and addresses need an entity-recognition tool such as Microsoft Presidio, plus a sampled manual audit.
Embedding is not anonymisation. The original chunk text sits next to every vector and comes back in answers and logs. India's Digital Personal Data Protection Act, 2023 applies to that text like any other personal data; the DPDP Rules notified in November 2025 bring most data fiduciary obligations into force 18 months later, around May 2027 (see MeitY's data protection page). Index only what the assistant's purpose needs.
How do you chunk documents and choose embeddings?
Split along the document's own structure (sections, clauses, FAQ entries) into pieces of a few hundred tokens with a small overlap, and attach metadata to every chunk. Keep tables whole, and prefix each chunk with its title and heading ("Travel Policy > Hotel limits") so it makes sense on its own.
Every chunk should carry its source path, page, version date, access group and embedding model name. Vectors from different models are not comparable, so switching models means re-embedding everything; plan it as a migration. For the intuition behind vectors, read what an embedding actually is. For storage, the pgvector extension used in the example below is often enough if you already run PostgreSQL.
Pick a chunk size, then read twenty random chunks aloud. If a colleague could not answer a question from one chunk alone, your chunks are too small or cut in the wrong place.
How do you keep the vector index fresh without re-embedding everything?
Detect what changed at the source, re-process only those documents, and delete chunks for documents that were removed or replaced. Content hashes work for any file store. Delta queries suit SharePoint, last-modified watermarks suit CRMs, and change data capture suits databases. Replace each document's chunks inside one transaction so nobody retrieves a half-updated policy.
Deletions are the step teams most often forget. A withdrawn circular that stays in the index will keep being quoted, confidently, for months. The illustrative arithmetic below shows why incremental refresh matters:
What does an Airflow DAG for a RAG pipeline look like?
An hourly DAG that finds changed files, then parses, checks, embeds and upserts each one as a separate mapped task, plus a task that removes deleted documents. The example uses Airflow 3's TaskFlow API (see the official tutorial), PostgreSQL with pgvector and an open-source embedding model. PDFs are synced from SharePoint into one folder per access group. Create the tables once:
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE IF NOT EXISTS rag_documents (
source_path text PRIMARY KEY,
content_hash text NOT NULL,
refreshed_at timestamptz NOT NULL
);
CREATE TABLE IF NOT EXISTS rag_chunks (
id bigserial PRIMARY KEY,
source_path text NOT NULL,
access_group text NOT NULL,
page int NOT NULL,
chunk_no int NOT NULL,
body text NOT NULL,
embedding vector(384) NOT NULL,
embed_model text NOT NULL
);
CREATE INDEX IF NOT EXISTS rag_chunks_source_idx ON rag_chunks (source_path);
CREATE INDEX IF NOT EXISTS rag_chunks_group_idx ON rag_chunks (access_group);
CREATE INDEX IF NOT EXISTS rag_chunks_hnsw_idx ON rag_chunks USING hnsw (embedding vector_cosine_ops);"""Hourly refresh of a policy-assistant index (Airflow 3.x).
On Airflow 2.x, use: from airflow.decorators import dag, task
pip install apache-airflow pypdf sentence-transformers "psycopg[binary]" pgvector
"""
from __future__ import annotations
import hashlib
import json
import re
from datetime import datetime
from pathlib import Path
from airflow.sdk import dag, task
LANDING = Path("/data/landing") # synced from SharePoint: one folder per access group
STAGING = Path("/data/staging/chunks")
PG_DSN = "postgresql://rag:rag@pg:5432/knowledge" # use an Airflow Connection in production
MODEL_NAME = "sentence-transformers/all-MiniLM-L6-v2" # 384-dimensional vectors
PII = [
("[PAN]", re.compile(r"\b[A-Z]{5}[0-9]{4}[A-Z]\b")),
("[AADHAAR]", re.compile(r"\b\d{4}\s?\d{4}\s?\d{4}\b")),
("[EMAIL]", re.compile(r"\b[\w.+-]+@[\w-]+\.[\w.-]+\b")),
("[PHONE]", re.compile(r"(?<!\d)(?:\+91[\s-]?)?[6-9]\d{4}[\s-]?\d{5}(?!\d)")),
]
def sha256_of(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest()
def clean(text: str) -> str:
for token, pattern in PII:
text = pattern.sub(token, text)
text = re.sub(r"[ \t]+", " ", text)
return re.sub(r"\n{3,}", "\n\n", text).strip()
def split_text(text: str, size: int = 1200, overlap: int = 200) -> list[str]:
"""Character-based splitter that prefers to cut at the end of a sentence."""
chunks, start = [], 0
while start < len(text):
end = min(start + size, len(text))
if end < len(text):
cut = text.rfind(". ", start, end)
if cut > start + size // 2:
end = cut + 1
chunks.append(text[start:end].strip())
if end == len(text):
break
start = end - overlap
return [c for c in chunks if c]
def read_rows(chunk_file: str) -> list[dict]:
lines = Path(chunk_file).read_text(encoding="utf-8").splitlines()
return [json.loads(line) for line in lines if line.strip()]
@dag(schedule="@hourly", start_date=datetime(2026, 11, 1), catchup=False,
max_active_runs=1, tags=["genai", "rag"])
def rag_refresh():
@task
def find_changed_files() -> list[str]:
import psycopg
current = {str(p): sha256_of(p) for p in LANDING.glob("*/*.pdf")}
with psycopg.connect(PG_DSN) as conn:
known = dict(conn.execute("SELECT source_path, content_hash FROM rag_documents").fetchall())
return [path for path, digest in current.items() if known.get(path) != digest]
@task
def remove_deleted_files() -> int:
import psycopg
present = {str(p) for p in LANDING.glob("*/*.pdf")}
with psycopg.connect(PG_DSN) as conn:
known = [row[0] for row in conn.execute("SELECT source_path FROM rag_documents")]
gone = [path for path in known if path not in present]
for path in gone:
conn.execute("DELETE FROM rag_chunks WHERE source_path = %s", (path,))
conn.execute("DELETE FROM rag_documents WHERE source_path = %s", (path,))
return len(gone)
@task
def parse_clean_chunk(path: str) -> str:
from pypdf import PdfReader
source = Path(path)
digest, group = sha256_of(source), source.parent.name
rows, seen = [], set()
for page_no, page in enumerate(PdfReader(source).pages, start=1):
for chunk in split_text(clean(page.extract_text() or "")):
key = hashlib.sha1(chunk.lower().encode()).hexdigest()
if key in seen: # repeated boilerplate inside the file
continue
seen.add(key)
rows.append({"source_path": path, "content_hash": digest, "access_group": group,
"page": page_no, "chunk_no": len(rows), "body": chunk})
STAGING.mkdir(parents=True, exist_ok=True)
out = STAGING / f"{digest}.jsonl"
out.write_text("\n".join(json.dumps(r, ensure_ascii=False) for r in rows), encoding="utf-8")
return str(out)
@task
def quality_check(chunk_file: str) -> str:
rows = read_rows(chunk_file)
if not rows:
raise ValueError(f"{chunk_file}: no text extracted (scanned PDF? route it to OCR)")
text = " ".join(r["body"] for r in rows)
unreadable = text.count("�") / len(text)
if unreadable > 0.01:
raise ValueError(f"{chunk_file}: {unreadable:.1%} unreadable characters")
tiny = sum(len(r["body"]) < 50 for r in rows) / len(rows)
if tiny > 0.3:
raise ValueError(f"{chunk_file}: {tiny:.0%} of chunks are under 50 characters")
return chunk_file
@task
def embed_and_upsert(chunk_file: str) -> int:
import psycopg
from pgvector.psycopg import register_vector
from sentence_transformers import SentenceTransformer
rows = read_rows(chunk_file)
vectors = SentenceTransformer(MODEL_NAME).encode(
[r["body"] for r in rows], batch_size=64, normalize_embeddings=True)
doc = rows[0]
with psycopg.connect(PG_DSN) as conn:
register_vector(conn)
with conn.transaction(): # readers never see a half-replaced document
conn.execute("DELETE FROM rag_chunks WHERE source_path = %s", (doc["source_path"],))
with conn.cursor() as cur:
cur.executemany(
"INSERT INTO rag_chunks (source_path, access_group, page, chunk_no, body,"
" embedding, embed_model) VALUES (%s, %s, %s, %s, %s, %s, %s)",
[(r["source_path"], r["access_group"], r["page"], r["chunk_no"], r["body"],
vec, MODEL_NAME) for r, vec in zip(rows, vectors)])
conn.execute(
"INSERT INTO rag_documents (source_path, content_hash, refreshed_at)"
" VALUES (%s, %s, now()) ON CONFLICT (source_path)"
" DO UPDATE SET content_hash = EXCLUDED.content_hash, refreshed_at = now()",
(doc["source_path"], doc["content_hash"]))
return len(rows)
remove_deleted_files()
chunk_files = parse_clean_chunk.expand(path=find_changed_files())
checked = quality_check.expand(chunk_file=chunk_files)
embed_and_upsert.expand(chunk_file=checked)
rag_refresh()Three design choices matter more than the code. Dynamic task mapping (.expand) gives each file its own task, so one corrupt PDF fails alone. Tasks pass file paths, not document text, which assumes every worker mounts the same /data volume (use object storage such as S3 or Azure Blob otherwise). And the quality check runs before embedding, where failures are cheap. New to Airflow? See Airflow for Python data pipelines.
How do you enforce access control in a RAG pipeline?
Copy each document's permissions into chunk metadata at ingestion, then filter on the user's groups inside the database query, never in the prompt. Telling the model "do not reveal HR documents" is a request, not a control. A filter in the query is a control: chunks the user may not see never reach the model at all.
SELECT body, source_path, page
FROM rag_chunks
WHERE access_group = ANY(%(user_groups)s)
ORDER BY embedding <=> %(query_vector)s
LIMIT 5;One pgvector detail matters here: an HNSW index applies the WHERE filter after the approximate search, so a small access group can come back with fewer than five rows. From pgvector 0.8.0 you can run SET hnsw.iterative_scan = strict_order; so the index keeps scanning until enough rows pass the filter, as the pgvector README explains.
Treat a permission change as a content change, and add test personas to your eval set: a sales trainee asking about salary bands should get a polite refusal.
Which data quality checks and lineage do GenAI pipelines need?
Put a simple automated check at every hand-off, and record lineage so any answer can be traced back to a file, a version and a pipeline run.
| Stage | Check | Catches |
|---|---|---|
| Extraction | Characters per page above a floor | Scanned PDFs that skipped OCR |
| Cleaning | Share of unreadable characters below 1% | Encoding and font problems |
| PII masking | Masked-token counts per file, plus a sampled manual audit | Identifier formats the regex missed |
| Chunking | Length distribution; no empty or tiny chunks | Splitter bugs |
| Embedding | Vector count equals chunk count; dimensions match | Partial batches, API failures |
| Index | No source older than the refresh target; no deleted sources present | A silently broken refresh |
| Retrieval | Golden questions return the expected document in the top five | Any of the above |
For lineage, store the source path, content hash, run ID and embedding model with each chunk. OpenLineage, an open standard with an Airflow integration, can record which job read and wrote which dataset, so an auditor's "where did this answer come from?" takes minutes, not days.
What does this look like for a manufacturer in Kolkata?
For a typical mid-sized manufacturer, the right design embeds SOPs, policies and contracts, queries Tally data through SQL, and masks CRM notes before indexing them. Picture a 600-person engineering goods company that wants one internal assistant for HR policies, shop-floor SOPs, vendor contracts and sales questions. The volumes below are illustrative.
- SOPs and policies: synced hourly from SharePoint using delta queries; one access group per department plus "all staff".
- Vendor contracts: OCR first, then a weekly manual check of ten random pages, because a misread payment term is costly.
- CRM notes: only the last 24 months, phone numbers and emails masked, visible to the sales group only.
- Tally: nightly exports loaded into warehouse tables (a simple star schema of invoices, parties and dates); the assistant gets a read-only SQL tool for "outstanding from distributors above ₹5 lakh".
When we run this exercise with enterprise teams, the source inventory (what exists, who owns it, who may see it) usually takes longer than the first pipeline. Time well spent.
What should you build first?
Build the boring foundations before the clever retrieval tricks.
- List every source, its owner, its refresh frequency and who may see it.
- Route structured data (Tally, ERP, sales tables) to SQL; embed only documents.
- Mask PAN, Aadhaar, phone and email before embedding, and audit a sample by hand.
- Attach source, page, version, access group and model name to every chunk.
- Refresh incrementally and handle deletions in the same run.
- Add a quality check at every hand-off and alert on failures.
- Keep 30 golden questions that must retrieve the right document, and run them after every refresh (our guide to evaluating LLM applications shows how to grow them into a full eval set).
Frequently asked questions
What is data engineering for generative AI?
It is building the pipelines that collect company content, extract and clean the text, mask personal data, split it into chunks, embed the chunks and load them into a searchable index, then keep that index fresh and permission-aware so RAG systems and agents answer from current, allowed information.
Do I need a vector database for RAG?
You need somewhere to store and search embeddings, but it does not have to be a new product. If you already run PostgreSQL, the pgvector extension is often enough for small and mid-sized corpora. A few dozen documents may fit straight into the prompt with no retrieval layer at all.
How often should a RAG index be refreshed?
As often as the source changes in ways users care about. Policies and SOPs on SharePoint often justify hourly or daily incremental refresh, while archives can refresh weekly. Refresh only changed documents, handle deletions in the same run, and alert when any source is older than its agreed refresh target.
Should I embed Excel files and ERP data?
Usually not. Embeddings capture meaning, not arithmetic, so a vector search cannot total invoices or compare quarters reliably. Load spreadsheets and ERP exports into database tables and let the assistant query them with SQL. Embed the documents that explain the numbers, such as policies, contracts and process notes.
How does the DPDP Act affect RAG pipelines in India?
Personal data in documents, chunks, prompts and logs is still personal data under the Digital Personal Data Protection Act, 2023. Index only what the assistant's purpose needs, mask identifiers such as PAN and Aadhaar before embedding, control access with metadata filters, and set retention and deletion rules for both the index and logs.
Do I need a course to learn data engineering for generative AI?
No. If you already write SQL and Python, the Airflow and pgvector documentation plus one end-to-end project will teach you most of it. A course helps career switchers who want mentor feedback and deadlines. At Ivy Professional School the pipeline side sits in the Data Engineering Course and RAG with vector databases in the Advanced Generative AI Course. Compare any syllabus with real job descriptions first.
Sources
- Lewis, P. et al. "Retrieval-Augmented Generation for Knowledge-Intensive NLP Tasks." 2020. https://arxiv.org/abs/2005.11401
- Apache Airflow. "Pythonic DAGs with the TaskFlow API" tutorial. https://airflow.apache.org/docs/apache-airflow/stable/tutorial/taskflow.html
- Microsoft Learn. "Use delta query to track changes in Microsoft Graph data." https://learn.microsoft.com/en-us/graph/delta-query-overview
- Unstructured. Open-source library overview (partitioning and chunking). https://docs.unstructured.io/open-source/introduction/overview
- pgvector. Open-source vector similarity search for Postgres. https://github.com/pgvector/pgvector
- OpenLineage. "About OpenLineage." https://openlineage.io/docs/
- Ministry of Electronics and Information Technology, Government of India. Data protection framework (DPDP Act, 2023 and DPDP Rules, 2025). https://www.meity.gov.in/data-protection-framework

By