Query Databases for LlamaIndex
Query and load SQL database rows into LlamaIndex documents, streaming or async, with column mapping.
Why it matters
Integrate your SQL databases with LlamaIndex to extract and load data for AI applications. Efficiently query and ingest structured data from various database sources.
Outcomes
What it gets done
Connect to SQL databases using various credentials or URIs.
Execute custom SQL queries to select specific data.
Map database columns to metadata and exclude sensitive text.
Load data synchronously, asynchronously, or in a streaming fashion.
Install
Add it to your toolbox
Run in your project directory:
curl -fsSL https://spark.entire.vc/get/li-reader-readers-database | bash Overview
LlamaIndex Readers Integration: Database
A LlamaIndex reader that loads SQL query results as documents, with configurable metadata mapping, text exclusion, and streaming or async loading. Use to turn arbitrary SQL query results into documents with control over metadata versus text columns, not for writing to the database.
What it does
The Database Reader queries and loads data from databases efficiently into LlamaIndex documents. It accepts a connection in several forms - an existing SQLDatabase object, a SQLAlchemy Engine, a full connection URI, or discrete credentials (host, port, user, password, database name) - so it fits into a project regardless of how the database connection is already managed. An optional schema parameter scopes queries to a specific namespace, such as targeting a warehouse or media schema within the same database.
Column handling is configurable: metadata_cols maps specific columns into document metadata (optionally renaming a column via a tuple like mapping id to article_id), while excluded_text_cols removes named columns from the document's text body even if they were selected by the query - useful for a column like updated_at that should be tracked as metadata but not embedded in the searchable text. A custom document_id function can generate each document's ID dynamically from its row data, for example an f-string template combining a table name and row ID.
Beyond the standard load_data, the reader supports lazy_load_data for streaming results one document at a time rather than loading everything into memory, and an async aload_data for non-blocking use in async code.
When to use - and when NOT to
Use it when you need to turn the results of a SQL query into LlamaIndex documents - filtering with an arbitrary SELECT query, controlling which columns become metadata versus searchable text, and generating stable custom document IDs. Use lazy_load_data for large result sets where loading everything into memory at once would be wasteful, and aload_data when working inside an async application. Do not use it as a way to modify the database; it is a read-only loader built around SQL queries you supply.
Capabilities
load_data/lazy_load_data/aload_data run a SQL query and return matching rows as documents, with configurable connection method (SQLDatabase, Engine, URI, or discrete credentials), schema scoping, metadata column mapping, text-column exclusion, and custom document ID generation.
How to install
pip install llama-index-readers-database
from llama_index.readers.database import DatabaseReader
reader = DatabaseReader(
uri="postgresql+psycopg2://user:pass@localhost:5432/mydb",
schema="warehouse", # optional namespace
)
### Streaming variant, excluded id from text_resource
for doc in reader.lazy_load_data(
query="SELECT * FROM warehouse.big_table", excluded_text_cols={"id"}
):
process(doc)
Requires database connection details in one of the supported forms (SQLDatabase object, SQLAlchemy Engine, connection URI, or discrete host/port/user/password/dbname).
Who it's for
Developers who need SQL query results loaded into LlamaIndex with fine control over which columns become metadata, which are excluded from text, and how document IDs are generated - including at scale via streaming or async loading.
Source README
LlamaIndex Readers Integration: Database
Overview
Database Reader is a tool designed to query and load data from databases efficiently.
Key features
- Accepts connection via
SQLDatabase, SQLAlchemyEngine, full URI, or discrete credentials - Optional
schemaselection (namespace) - Column-level metadata mapping (
metadata_cols) and text exclusion (excluded_text_cols) - Custom
id_generation function (document_id) - Supports streaming (
lazy_load_data) and async (aload_data)
Installation
You can install Database Reader via pip:
pip install llama-index-readers-database
Usage
from llama_index.readers.database import DatabaseReader
### Initialize DatabaseReader with the SQL database connection details
reader = DatabaseReader(
sql_database="<SQLDatabase Object>", # Optional: SQLDatabase object
engine="<SQLAlchemy Engine Object>", # Optional: SQLAlchemy Engine object
uri="<Connection URI>", # Optional: Connection URI
scheme="<Scheme>", # Optional: Scheme
host="<Host>", # Optional: Host
port="<Port>", # Optional: Port
user="<Username>", # Optional: Username
[REDACTED], # Optional: Password
dbname="<Database Name>", # Optional: Database Name
)
### Load data from the database using a query
documents = reader.load_data(
query="<SQL Query>" # SQL query parameter to filter tables and rows
)
### Initialize DatabaseReader with the SQL connection string and custom database schema
from llama_index.readers.database import DatabaseReader
reader = DatabaseReader(
uri="postgresql+psycopg2://user:pass@localhost:5432/mydb",
schema="warehouse", # optional namespace
)
### Streaming variant, excluded id from text_resource
for doc in reader.lazy_load_data(
query="SELECT * FROM warehouse.big_table", excluded_text_cols={"id"}
):
process(doc)
### Async variant, added region to metadata
docs_async = await reader.aload_data(
query="SELECT * FROM warehouse.big_table", metadata_cols=["region"]
)
### Advanced usage with custom named metadata columns, columns excluded from the `Document.text_resource`, and a dynamic `Document.id_` generated from row data and a fstring template
from llama_index.readers.database import DatabaseReader
reader_media = DatabaseReader(
uri="postgresql+psycopg2://user:pass@localhost:5432/mydb",
schema="media", # optional namespace
)
docs = reader_media.load_data(
query="SELECT id, title, body, updated_at FROM media.articles",
metadata_cols=[
("id", "article_id"),
"updated_at",
], # map / include in metadata
excluded_text_cols=["updated_at"], # omit from text
document_id=lambda row: f"media-articles-{row['id']}", # custom document id
)
This loader is designed to be used as a way to load data into
LlamaIndex.
FAQ
Common questions
Discussion
Questions & comments · 0
Sign In Sign in to leave a comment.