How to beginner · 3 min read

How to use KeywordTableIndex in LlamaIndex

Quick answer
Use KeywordTableIndex in LlamaIndex to create a keyword-based index for efficient document retrieval. Build the index from documents, then query it with natural language prompts to get keyword-focused results.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install llama-index openai

Setup

Install the llama-index and openai Python packages and set your OpenAI API key as an environment variable.

bash
pip install llama-index openai

Step by step

This example shows how to create a KeywordTableIndex from a list of documents and query it using the OpenAI GPT-4o model.

python
import os
from llama_index import SimpleDirectoryReader, KeywordTableIndex, ServiceContext, LLMPredictor
from openai import OpenAI

# Set up OpenAI client
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

# Define LLM predictor using OpenAI GPT-4o
llm_predictor = LLMPredictor(client=client, model_name="gpt-4o")

# Create service context with the LLM predictor
service_context = ServiceContext.from_defaults(llm_predictor=llm_predictor)

# Load documents (example: from local directory or list)
docs = [
    "LlamaIndex is a powerful tool for building indices over documents.",
    "KeywordTableIndex allows fast keyword-based retrieval.",
    "You can query the index with natural language prompts."
]

# Build KeywordTableIndex from documents
index = KeywordTableIndex.from_documents(docs, service_context=service_context)

# Query the index
query_str = "What is KeywordTableIndex used for?"
response = index.query(query_str)

print("Query:", query_str)
print("Response:", response.response)
output
Query: What is KeywordTableIndex used for?
Response: KeywordTableIndex is used for fast keyword-based retrieval of information from documents.

Common variations

You can use KeywordTableIndex with asynchronous calls by integrating with async LLM clients. Also, you can swap the OpenAI GPT-4o model with other supported models like gpt-4o-mini or use Anthropic Claude models by adapting the LLM predictor accordingly.

Troubleshooting

If you get errors about missing API keys, ensure OPENAI_API_KEY is set in your environment. If queries return irrelevant results, verify your documents are properly loaded and the index is rebuilt after document changes.

Key Takeaways

  • Use KeywordTableIndex to build keyword-focused indices for fast retrieval.
  • Always set your OpenAI API key in os.environ to authenticate requests.
  • You can query the index with natural language prompts for relevant keyword-based answers.
Verified 2026-04 · gpt-4o
Verify ↗