High severity beginner · Fix: 2-5 min

KeyError

builtins.KeyError

What this error means
This error occurs when LlamaIndex tries to access a document store key that does not exist in the index or storage backend.

Stack trace

traceback
Traceback (most recent call last):
  File "app.py", line 42, in <module>
    document = index.docstore['nonexistent_key']  # KeyError raised here
KeyError: 'nonexistent_key'
QUICK FIX
Check if the key exists in index.docstore before accessing it or catch KeyError exceptions to handle missing keys gracefully.

Why it happens

LlamaIndex maintains a document store mapping keys to documents. When code attempts to retrieve a document by a key that was never added or has been deleted, Python raises a KeyError. This usually means the key is misspelled, the document was never indexed, or the index was not properly saved and loaded.

Detection

Add checks using 'key in index.docstore' before access or wrap access in try/except KeyError to log missing keys and avoid crashes.

Causes & fixes

1

Attempting to access a document key that was never added to the index.

✓ Fix

Verify the key exists in the document store before access or ensure the document was indexed properly.

2

The document store was not saved or loaded correctly, causing missing keys.

✓ Fix

Ensure the index is saved and loaded using LlamaIndex's save_to_disk and load_from_disk methods properly.

3

Typo or mismatch in the document key string used for retrieval.

✓ Fix

Double-check the key string for exact spelling and case sensitivity matching the stored keys.

Code: broken vs fixed

Broken - triggers the error
python
from llama_index import GPTSimpleVectorIndex

index = GPTSimpleVectorIndex.load_from_disk('index.json')
doc = index.docstore['missing_key']  # KeyError here
Fixed - works correctly
python
import os
from llama_index import GPTSimpleVectorIndex

index = GPTSimpleVectorIndex.load_from_disk('index.json')
key = 'missing_key'
if key in index.docstore:
    doc = index.docstore[key]
    print('Document found:', doc)
else:
    print(f'Key "{key}" not found in document store.')  # Fixed: check key existence before access
Added a key existence check before accessing the document store to prevent KeyError when the key is missing.

Workaround

Wrap document store access in try/except KeyError, then log the missing key and optionally return a default value or trigger re-indexing.

Prevention

Always validate keys before access and ensure documents are indexed and persisted correctly using LlamaIndex's save/load methods to keep the document store consistent.

Python 3.9+ · llama-index >=0.5.0 · tested on 0.6.x
Verified 2026-04
Verify ↗

Community Notes

No notes yetBe the first to share a version-specific fix or tip.