# How Do You Clean and Deduplicate Documents Before RAG?

> Why cleaning comes before removing copies, how exact and near copies are found, and what to keep, explained simply for your AI interview.

**In short:** Clean the text first, so copies look the same, then remove exact copies by hash and near copies by similarity check. Keep each file's source and version, because copies waste the few slots a search returns.

AI and LLM interview question Q149, Retrieval-augmented generation (RAG). Intermediate, common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/how-do-you-clean-and-deduplicate-documents-first

## Say it in 30 seconds

Before I index anything, I clean the text: fix broken characters, strip repeated headers and footers, and tidy the spacing. Then I remove exact copies by comparing hashes, which are short fingerprints of the text, and near copies with a similarity check that a person reviews. Duplicates matter because a search returns only a few pieces of text, and three copies of one policy push out the answer I need. I keep the source, date and version of every file, so I can take an old rule out of the index.

## Say it in 2 minutes

The order matters. If I remove duplicates before cleaning, two copies of the same policy can look different just because one has a broken apostrophe or an extra footer. So I clean first: fix the way characters are stored, remove repeated headers and footers, and collapse extra spaces. After that, identical wording gives identical fingerprints.

Next I remove exact copies. Each file gets a hash, and any file whose hash I have already seen is dropped. That is fast and safe. For near copies, such as the same contract with one clause edited, I use a similarity check like MinHash, which estimates how much two documents overlap. Meaning-based checks come later, because they are slower, and a loose setting can merge two rules that differ on one number.

The step most people forget is versions. A hash says two files match, but it cannot say which one is newer. So every file keeps its source, date and version, and the old copies leave the search index as well as the duplicate list. Otherwise an out-of-date rule can win the search.

Deduplication runs again on every update, because documents change. I also check a sample of the matches by hand, because a rule that is too loose can drop a real but similar document.

## What does cleaning and deduplicating mean, in plain words?

Cleaning means fixing the text before it is searched: broken characters, repeated page headers, stray links and messy spacing. Deduplicating means removing the copies, so the same content is not stored and searched again and again. The search index is the store that the search looks in.

A team with 40,000 policy files often has the same wording in three folders. Picture a bank branch with three printed copies of the same fee sheet. Before anyone searches the shelf, you pull out the extra copies and keep the newest one, with a note of where it came from.

Retrieval-augmented generation, or RAG, is a way to build AI apps that look up your own documents and hand the best pieces to the model before it answers. The lookup returns only a few pieces, so copies waste the room.

- **Cleaning:** Fixing the text so it reads right and matches its copies.
- **Hash:** A short fingerprint of a file's text. Same text, same fingerprint.
- **Exact copy:** Two files with identical text after simple tidying.
- **Near copy:** Two files with small edits, such as one changed date or clause.
- **Chunk:** A short piece of a document that the search stores and returns.

## Why clean before you remove copies?

Copies only match when their text is the same. Two versions of one refund rule can differ by a smart quote, a stray space or a footer that says Page 3 of 9. A hash of the raw files sees two different files, so the copy survives.

So the order is fixed: clean first, then match. Cleaning means three small jobs: repair broken characters, remove repeated headers and footers, and collapse extra spaces. NVIDIA's documentation for NeMo Curator names the same kind of problem:

> "Remove undesirable text such as improperly decoded Unicode characters, inconsistent line spacing, or excessive URLs from documents being pre-processed for your dataset" (NVIDIA, NeMo Curator text cleaning)

*Diagram, Clean, match, then index: Copies are matched only after cleaning, so the match is fair. Exact copies go first, then near copies are checked, and only the kept files are split into chunks and indexed.*
1. Messy files go into the cleaning step first.
2. Cleaning comes first, so copies look the same.
3. Exact copies go first, then near copies are checked.
4. Only the kept files move on, cut into chunks.
5. Chunks go into the search index. Old copies stay out.

Worked example, with made-up numbers: an insurer loads 40,000 policy PDFs. A hash check on the raw files finds 2,100 exact copies. After the team strips repeated page footers and fixes broken characters, the count rises to 6,800, because the footers were making identical wording look different. Cleaning found copies that hashing had missed.

## How do you remove exact and near copies?

- **Exact: Same hash.** Each cleaned file gets a hash. Matching hashes mean the same text, so one copy goes. It is fast and safe.
- **Near: Similar, not identical.** A small edit changes the hash, so a similarity check such as MinHash estimates the overlap. Set the threshold (the match score that counts as a copy) too low and real differences get dropped.
- **Meaning: Same idea, other words.** Semantic checks compare embeddings, which are numbers that stand for meaning. They catch rewrites, but are slower, because they need an embedding step. A loose threshold can also treat two rules that differ on one figure as the same.

> "Find and remove near-duplicate documents with small edits or reformatting using MinHash and Locality Sensitive Hashing (LSH)." (NVIDIA, NeMo Curator fuzzy deduplication)
>
> "We find that existing language modeling datasets contain many near-duplicate examples and long repetitive substrings." (Lee and co-authors, 2021 paper)

Why bother with near copies? That 2021 paper found that over 1% of the unprompted output of language models trained on these datasets is copied verbatim from the training data. As an example, the authors removed one 61 word sentence that is repeated over 60,000 times from C4. Models trained on the deduplicated data emitted memorised text ten times less often.

Worked example, with made-up numbers: two contracts differ only in a payment term, 30 days against 60 days. The similarity check scores them 0.97 out of 1, so the system merges them into one. The threshold was too loose. The fix is a stricter threshold, then a human check on a sample of merged pairs.

Here is a small Python check with the standard library only. The hash is the exact-copy test.

```python
# A made-up policy folder: four files, two of them copies of the same refund rule.
import hashlib
import re

docs = {
    "refund-policy-v3.txt": "Refunds are paid within 7 working days.",
    "refund-policy-copy.txt": "Refunds are paid within 7  working days. ",
    "refund-policy-v2.txt": "Refunds are paid within 14 working days.",
    "warranty.txt": "Hardware is covered for 12 months.",
}

def normalise(text):
    # Collapse extra spaces and case, so small formatting changes do not hide a copy.
    return re.sub(r"\s+", " ", text).strip().lower()

seen = {}
kept = []
for name, text in docs.items():
    digest = hashlib.sha256(normalise(text).encode("utf-8")).hexdigest()
    if digest in seen:
        print("DROP " + name + " (same as " + seen[digest] + ")")
    else:
        seen[digest] = name
        kept.append(name)
        print("KEEP " + name)
print(str(len(kept)) + " of " + str(len(docs)) + " documents kept")
```

Output:

```text
KEEP refund-policy-v3.txt
DROP refund-policy-copy.txt (same as refund-policy-v3.txt)
KEEP refund-policy-v2.txt
KEEP warranty.txt
3 of 4 documents kept
```

The last lines show the limit. Version 2 of the refund rule stays, because its text differs. A hash cannot say which version is newer, so the team keeps metadata with each file: the labels for its source, date and version number.

## Which copy do you keep, and what can go wrong?

Copies cost more than disk space. A search returns a small number of pieces, so copies push out rules that the answer might need.

*Diagram, Copies use up the search: Three of the four snippets say the same thing, so the search has little room left for other rules. Remove the copies first and the same four slots carry more.*
1. The staff member asks one question.
2. The model reads four snippets, and three are copies.
3. The model answers from what it was given, with less room left.

1. **Clean the text:** Fix broken characters, repeated headers and footers, and extra spaces, so copies match.
2. **Remove exact copies:** Compare hashes of the cleaned text. Keep one copy and record where the others were.
3. **Flag near copies:** Run a similarity check, then review a sample of matches before you drop anything.
4. **Keep the version in force:** Use the date and version labels to pick the version that applies today. Take the others out of the search index as well as the duplicate list.
5. **Split and index:** Cut the kept files into chunks, each with its source, and store them.

- **Loose rules:** A rule that is too loose merges two different clauses, such as 30 and 60 days.
- **Over-cleaning:** Cleaning can remove real content, such as a table that looked like a footer.
- **Lost sources:** A copy removed without its labels leaves no source, so nobody can check the answer.

> **Tip:** Asked what to do first? Say cleaning. A hash only works on text that was cleaned the same way.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] Clean first, so copies look the same: fix text, drop repeated headers and footers.
- [ ] Exact copies by hash, near copies by similarity, with a human check on a sample.
- [ ] Keep source, date and version, and take old copies out of the index.
- [ ] Why it matters: copies use up the few slots a search returns.
- [ ] Dedup runs again whenever documents change.

**Common traps**

- Trap: "Just hash the raw files and delete the matches." Better: Hash the cleaned text. Raw files with different spacing or footers hash differently, so copies slip through.
- Trap: "Use embeddings to remove every duplicate." Better: Meaning checks can merge rules that differ on one figure. Use hashes first, then review the near matches.
- Trap: "The newest file wins, so keep only one file." Better: A hash cannot say which version is newer. Keep the date and version with every file.

## Can you spot the problem?

**Spot the problem:** Your team hashes the raw PDF files to find copies before indexing. Two copies of one policy are still both indexed. Why?

A. The hash function is too weak for text.
B. The raw files differ in spacing and footers, so their hashes differ.
C. The search returns too few slots.
D. Embeddings were switched off.

**Answer:** B. Cleaning comes first. Footers and spacing change the bytes, so the hashes differ even when the policy text is the same. Clean the text, then hash it.

**Quick check:** A near-copy check merges two contracts that differ only in a payment term. What is the first fix?

A. Delete all near matches without looking at them.
B. Raise the similarity threshold, then review a sample of the merged pairs.
C. Switch to a bigger embedding model.
D. Hash the raw files again, because hashing ignores spacing.

**Answer:** B. A stricter threshold merges fewer pairs, and a human sample shows whether the rule is right. Deleting blind, or changing the model, does not fix a rule that is too loose.

## Can you answer these from memory?

**Flash cards**

- **What is cleaning?** Fixing broken characters, repeated headers and footers, and extra spaces before matching.
- **What is an exact copy?** Same cleaned text. A matching hash shows it.
- **What is a near copy?** Small edits, such as one changed date. Found by a similarity check, then reviewed.
- **Why clean first?** Footers and spacing change the bytes, so copies would hash differently.
- **Why keep versions?** A hash says two files match, not which one is newer.
- **Why does this matter for RAG?** A search returns only a few chunks, so copies waste room the model needs.

## Likely follow-up questions

- Q113 What is chunking, and why does size matter? https://designervenkat.online/interview/ai/what-is-chunking-in-rag
- Q114 Fixed vs recursive vs semantic chunking? https://designervenkat.online/interview/ai/fixed-vs-recursive-vs-semantic-chunking
- Q147 When must you re-embed everything? (full answer coming)
- Q150 How would you design RAG for 10 million documents? https://designervenkat.online/interview/ai/how-would-you-design-rag-for-10-million-documents
- Q151 "The answer was in the docs, but the bot missed it." How do you debug? https://designervenkat.online/interview/ai/debug-a-rag-bot-that-missed-the-answer
