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.
11 min readIntermediateCommon · estimateFacts checked 26 November 2026
Say it out loud
Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.
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.
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.
Key words
- 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
Clean, match, then index
Raw files
PDFs with broken characters and footers
Clean the text
fix text, drop headers, tidy spacing
Remove copies
Exact copies
same hash, same cleaned text
Near copies
similar text, checked by a person
Split into chunks
short pieces, each with its source
Search index
only the version in force is stored
- 1Messy files go into the cleaning step first.
- 2Cleaning comes first, so copies look the same.
- 3Exact copies go first, then near copies are checked.
- 4Only the kept files move on, cut into chunks.
- 5Chunks 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.
# 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
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.
Copies use up the search
Staff question
How long do refunds take?
Top 4 snippets
Policy copy 1
refunds within 7 working days
Policy copy 2
same text, another folder
Policy copy 3
same text again
Delivery terms
about parcels, not refunds
Model
answers from the four snippets
Other rules fall off
copies took the room they needed
- 1The staff member asks one question.
- 2The model reads four snippets, and three are copies.
- 3The 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."
BetterHash the cleaned text. Raw files with different spacing or footers hash differently, so copies slip through.
Trap"Use embeddings to remove every duplicate."
BetterMeaning 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."
BetterA 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?
Quick check
A near-copy check merges two contracts that differ only in a payment term. What is the first fix?
Can you answer these from memory?
Flash cards · tap a card to flip it
What will they ask next?
Last updated on 26 November 2026
Building a search over your own company documents?
I design and build AI products and agents (the UI and the system behind them), including the search behind the answer. Book a short call and tell me what your documents look like.