DuckDB Extension
Redis
Read Redis values from DuckDB SQL and join them with local data. The extension also supports writes, hashes, lists, and key discovery.
On this page
Use values from Redis alongside analytical data
Redis stores values under keys and supports structures such as hashes and lists. This extension accesses those values from DuckDB, so a SQL query can look up operational data and combine it with local tables.
Use it for inspecting a Redis instance or enriching rows with values already held there. You need a reachable Redis server and the appropriate credentials. Reads observe that server’s current data; save the results locally when you need a repeatable analytical snapshot.
Example
Read an existing Redis string
Connect to a local Redis server and look up one string key. This example does not write to Redis.
Before you run it: Run a Redis server on localhost:6379, or change the connection settings. Use an existing string key.
Run this example in the DuckDB CLI or a native client.
SET allow_extension_repositories = 'allowed';
CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
WITH PREFIX 'https://duckdb-extensions.query.farm';
INSTALL redis FROM query_farm;
LOAD redis FROM query_farm;
CREATE OR REPLACE SECRET qf_redis_demo (
TYPE redis, PROVIDER config,
host 'localhost', port '6379'
);
SELECT redis_get('user:1', 'qf_redis_demo') AS value;
DROP SECRET qf_redis_demo;
SET allow_extension_repositories = 'allowed';
CREATE EXTENSION REPOSITORY IF NOT EXISTS query_farm
WITH PREFIX 'https://haybarn-extensions.query.farm';
INSTALL redis FROM query_farm;
LOAD redis FROM query_farm;
CREATE OR REPLACE SECRET qf_redis_demo (
TYPE redis, PROVIDER config,
host 'localhost', port '6379'
);
SELECT redis_get('user:1', 'qf_redis_demo') AS value;
DROP SECRET qf_redis_demo;
INSTALL redis FROM community;
LOAD redis;
CREATE OR REPLACE SECRET qf_redis_demo (
TYPE redis, PROVIDER config,
host 'localhost', port '6379'
);
SELECT redis_get('user:1', 'qf_redis_demo') AS value;
DROP SECRET qf_redis_demo;
Replace user:1 with a string key in your instance. The result depends on the stored value. Use the authentication guidance for servers that require credentials.
Common tasks
Deep Dive
Technical Details
What you can do with one query
The single most useful pattern: drain an entire Redis keyspace into a DuckDB table without writing a script:
CREATE TABLE redis_users_dump ASSELECT key, field, valueFROM redis_hscan_over_scan( /* scan_pattern */ 'user:*', /* hscan_pattern */ '*', /* count */ 100, /* secret */ 'redis');redis_hscan_over_scan chains the upstream SCAN and HSCAN cursor commands into one streaming (key, field, value) row source. Server-friendly cursor pagination throughout — no KEYS blocking, no Python in the middle.
This extension is for SQL-side workflows where data integration matters more than every Redis feature. It has dedicated functions for strings, hashes, and lists; sets, sorted sets, streams and other commands go through redis_command (DuckDB 2.0 build). There is no PUB-SUB or MULTI/EXEC transaction support. Connections are single-node (no Redis Cluster). Auth is currently plaintext — TLS isn’t wired up yet. The status is experimental; the function surface may change.
For application-grade Redis access, keep a real client. For one-off migrations, hot-cold joins, and operational queries from SQL, this is the right tool.
Authentication
Every redis_* function takes a trailing secret argument naming a DuckDB secret of TYPE redis. This keeps credentials out of query text and lets multiple environments (dev/staging/prod) live as separate secrets — pick the right one per query:
CREATE SECRET prod_redis ( TYPE redis, PROVIDER config, host 'cache.prod.internal', port '6379', password :prod_password);
SELECT redis_get('counter', 'prod_redis');See CREATE SECRET and the DuckDB Secrets Manager for the secrets infrastructure, and the Secrets section below for the parameter table the redis secret type accepts.
SCAN, never KEYS
The KEYS command blocks the Redis server for the duration of the scan, which can stall traffic on a large production instance. No function in this extension issues it. Every key-listing function is built on cursor-paginated, non-blocking SCAN:
redis_keysis the convenience function: it follows theSCANcursor page by page until iteration completes and returns every matching key as a table, each key once.redis_scanis the manual primitive: oneSCANpage per call. You re-pass the returned cursor to fetch the next page; cursor0means iteration is complete:
SELECT redis_scan('0', 'user:*', 100, 'redis');-- "1024:user:1,user:2,...,user:50"redis_hscan_over_scan (used in the lead snippet above) chains both into one streaming pipeline: for every key matching scan_pattern, run HSCAN hscan_pattern and emit (key, field, value) rows, following both cursors to the end. Matching keys that aren’t hashes are skipped. The fastest way to drain a Redis hash dataset into DuckDB.
Because redis_keys and redis_hscan_over_scan walk the whole matching keyspace in one query, keep their patterns narrow on large instances.
Return values and NULLs
redis_getandredis_hgetreturnNULLfor a missing key or field, socoalesce(redis_get(k, 'redis'), 'default')andIS NULLchecks work as expected.redis_hsetreturns aBIGINTcount of fields added (1for a new field,0when an existing one is overwritten);redis_lpushreturns the list length after the push as aBIGINT.redis_mgetreturns values comma-joined in request order, with an empty entry for each missing key so positions line up with the keys you asked for. Empty key names (for example, from a trailing comma) are ignored. A value containing a comma, or an empty value, can’t be told apart from that, so in the DuckDB 2.0 build preferredis_mget_list, which takes aVARCHAR[]and returns aVARCHAR[]withNULLfor missing keys.- The DuckDB 2.0 build adds typed variants of the other comma-joined functions:
redis_lrange_list(VARCHAR[]),redis_scan_page(STRUCT(cursor VARCHAR, keys VARCHAR[])),redis_hscan_page(STRUCT(cursor VARCHAR, entries MAP(VARCHAR, VARCHAR))) andredis_hgetall_map(MAP(VARCHAR, VARCHAR)). The original functions keep their string results. - A
NULLin any argument, including the secret name, gives aNULLresult.
Every argument is read per row, so the key, value, and even the secret can come from columns. The scalar functions are registered as volatile: DuckDB runs them for every row and never constant-folds or deduplicates a call, which matters because most of them change server state.
In the DuckDB 2.0 build the commands for a vector of rows (up to 2,048) are pipelined: they are sent in one write and the replies read back in order, so a bulk redis_set or redis_get over a table costs one round trip per vector instead of one per row. If one row’s command fails (for example, WRONGTYPE), the error is raised for the first failing row, but the other commands of that vector have already run on the server.
Timeouts, cancellation and sandboxing
These apply to the DuckDB 2.0 build.
- Timeouts. Connecting and every wait for reply data are bounded by the
redis_timeout_mssetting (default30000); a secret’stimeout_msoverrides it, and0waits forever. A server that stops answering fails the query withtimed out waiting for a reply after N msinstead of hanging it. The timeout applies to each wait, not to the whole reply, so a large reply that keeps arriving is never cut off. - Cancellation. A query waiting on Redis can be interrupted (Ctrl-C in the CLI,
interrupt()from a client API) at any time, including while connecting. - Sandboxing. Every
redis_*function refuses with a Permission Error whenenable_external_accessisfalse, so a locked-down DuckDB can’t be used to reach Redis servers. - Connection isolation. Connections are pooled per database instance and keyed by host, port, user name, password and database index; a secret is never handed a connection that was authenticated (or
SELECTed) for another. Idle connections close after two minutes, and a pooled connection that the server closed in the meantime is replaced transparently.redis_commandcloses its connection afterwards rather than returning it to the pool. - Malformed replies. Replies are parsed with bounded sizes, element counts and nesting depth, so a misbehaving server produces an error, not a crash or runaway memory use.
SET redis_timeout_ms = 2000; -- fail fast against an unresponsive serverChanges in the DuckDB 2.0 build
- Security: connections are no longer shared between secrets that point at the same host and port with different credentials or databases, nor between database instances in one process.
- Every function refuses when
enable_external_accessisfalse. - New:
redis_timeout_mssetting; secret optionsusername,dbandtimeout_ms; functionsredis_lrange_list,redis_mget_list,redis_scan_page,redis_hscan_page,redis_hgetall_mapandredis_command. redis_lrange_table’sindexcolumn is the element’s position in the list; it used to start at 0 whateverstartwas.- Commands are pipelined per vector of rows (see above).
What’s in the box
| Group | Functions | Redis commands |
|---|---|---|
| Strings | redis_get, redis_set, redis_mget, redis_mget_list |
GET, SET, MGET |
| Hashes | redis_hget, redis_hset, redis_hgetall, redis_hgetall_map, redis_hscan, redis_hscan_page |
HGET, HSET, HGETALL, HSCAN |
| Lists | redis_lpush, redis_lrange, redis_lrange_list, redis_lrange_table |
LPUSH, LRANGE, LLEN |
| Discovery | redis_keys, redis_scan, redis_scan_page, redis_hscan_over_scan |
SCAN, HSCAN |
| Key management | redis_type, redis_exists, redis_del |
TYPE, EXISTS, DEL |
| Expiry | redis_expire, redis_expireat, redis_ttl |
EXPIRE, EXPIREAT, TTL |
| Anything else | redis_command |
any command |
The extension speaks the Redis Serialization Protocol over plain TCP. Recipes for each group live in the Cookbook.
Reference
Extension Contents
Quick reference to all available functions and settings organized by category.
| Name | Type | Description |
|---|---|---|
|
Cache / In-memory store
|
||
| redis | Object type: Secret | Redis connection details. |
|
Commands
|
||
| redis_command() | Object type: Scalar function | Run any Redis command, given as a VARCHAR[] of the command name and its arguments — sets, sorted sets, counters, streams and anything else without a dedicated function. |
|
Configuration
|
||
| redis_timeout_ms | Object type: Setting | Timeout in milliseconds for connecting to Redis and for each wait for reply data (0 waits forever; queries can still be interrupted). |
|
Expiry
EXPIRE / EXPIREAT / TTL — set and inspect key time-to-live. |
||
| redis_expire() | Object type: Scalar function | Set a key's time-to-live in seconds. |
| redis_expireat() | Object type: Scalar function | Expire a key at an absolute Unix timestamp (seconds). |
| redis_ttl() | Object type: Scalar function | Remaining time-to-live in seconds. |
|
Hashes
HGET / HSET / HGETALL / HSCAN — for field-keyed records stored under one Redis key. The |
||
| redis_hget() | Object type: Scalar function | Get the value of a hash field. |
| redis_hgetall() | Object type: Table function | List all (field, value) pairs of a hash as a table. |
| redis_hgetall_map() | Object type: Scalar function | All fields and values of a hash as a MAP(VARCHAR, VARCHAR) — one value per row, so it works per row in a SELECT (redis_hgetall is a table function). |
| redis_hscan() | Object type: Scalar function | Cursor-paginated scan of a hash's fields. |
| redis_hscan_over_scan() | Object type: Table function | For every key matching a SCAN pattern, run HSCAN and emit (key, field, value) rows, following both cursors to the end. |
| redis_hscan_page() | Object type: Scalar function | One HSCAN step over a hash's fields, typed: returns STRUCT(cursor VARCHAR, entries MAP(VARCHAR, VARCHAR)). |
| redis_hset() | Object type: Scalar function | Set the value of a hash field. |
|
Keys
DEL / EXISTS / TYPE / SCAN — keyspace introspection and management. Key listing is built on cursor-paginated SCAN, never the server-blocking KEYS command. |
||
| redis_del() | Object type: Scalar function | Delete a key. |
| redis_exists() | Object type: Scalar function | Check whether a key exists. |
| redis_keys() | Object type: Table function | List all keys matching a pattern as a table, one row per key. |
| redis_scan() | Object type: Scalar function | Cursor-paginated SCAN of the keyspace, one page per call. |
| redis_scan_page() | Object type: Scalar function | One SCAN step over the keys matching a pattern, typed: returns STRUCT(cursor VARCHAR, keys VARCHAR[]). |
| redis_type() | Object type: Scalar function | Get the Redis type of a key (string / list / hash / set / zset / stream / none). |
|
Lists
LPUSH / LRANGE — interact with Redis lists. Use |
||
| redis_lpush() | Object type: Scalar function | Push a value onto the head of a list. |
| redis_lrange() | Object type: Scalar function | Get a range from a list as a comma-separated string. |
| redis_lrange_list() | Object type: Scalar function | Get a range from a list as a VARCHAR[]. |
| redis_lrange_table() | Object type: Table function |
Get a range from a list as a table — one row per element, with index (the element's position in the list) and value.
|
|
Strings
GET / SET / MGET against Redis string keys. The simplest key-value layer — read and write opaque values. |
||
| redis_get() | Object type: Scalar function | Get the value of a string key. |
| redis_mget() | Object type: Scalar function | Get multiple values in one round-trip. |
| redis_mget_list() | Object type: Scalar function | Get multiple values in one round-trip, typed: takes the keys as a VARCHAR[] and returns a VARCHAR[] of the same length, with NULL for each missing key. |
| redis_set() | Object type: Scalar function | Set the value of a string key. |
No extension contents match that search.
API Reference
Function Reference
Configuration
Settings
Configure the redis extension behavior using these settings.
redis_timeout_ms
Timeout in milliseconds for connecting to Redis and for each wait for reply data (0 waits forever; queries can still be interrupted). A redis secret's timeout_ms overrides it
30000
Security
Secrets
DuckDB secrets for storing the credentials and keys used by the redis extension.
redis
Description
Redis connection details. All redis_* functions take a final secret argument naming a secret of this type.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| Parameter host | Type VARCHAR | Required Required | Description Redis server hostname or IP. |
| Parameter port | Type VARCHAR | Required Required | Description Redis server port (typically '6379'). |
| Parameter password | Type VARCHAR | Required Optional | Description Authentication password if the server requires AUTH. Optional: leave it out to connect without AUTH. |
| Parameter username | Type VARCHAR | Required Optional | Description Redis 6+ ACL user name, sent as AUTH username password. Requires password. DuckDB 2.0 build. |
| Parameter db | Type BIGINT | Required Optional | Description Database index to SELECT after connecting (default 0). DuckDB 2.0 build. |
| Parameter timeout_ms | Type BIGINT | Required Optional | Description Timeout in milliseconds for connecting and for each wait for reply data; overrides the redis_timeout_ms setting. 0 waits forever (the query can still be interrupted). DuckDB 2.0 build. |
Examples
Local Redis without auth
CREATE SECRET IF NOT EXISTS redis (
TYPE redis,
PROVIDER config,
host 'localhost',
port '6379'
);
Redis Cloud endpoint with a password
CREATE SECRET IF NOT EXISTS redis (
TYPE redis,
PROVIDER config,
host 'redis-1234.ec2.redns.redis-cloud.com',
port '16959',
password 'xxxxxx'
);
ACL user, database 2 and a 5 second timeout (DuckDB 2.0 build)
CREATE SECRET IF NOT EXISTS redis_reports (
TYPE redis,
PROVIDER config,
host 'cache.internal',
port '6379',
username 'reporting',
password 'xxxxxx',
db 2,
timeout_ms 5000
);
Practical Examples
Cookbook
Real-world recipes and patterns for common use cases.
Connect
Redis credentials live in a DuckDB secret. Every redis_* function takes a final secret argument naming this secret:
CREATE SECRET IF NOT EXISTS redis ( TYPE redis, PROVIDER config, host 'localhost', port '6379');Add password when the server requires AUTH; without it the extension connects without AUTH. host and port are required, and a secret missing either fails with a “missing required key” error. The secret argument is the secret’s exact name: earlier releases matched any unscoped redis secret, while the current release looks the secret up by name only.
For production, parameterize the password from the environment so it doesn’t appear in cached query plans:
SET VARIABLE redis_password = getenv('REDIS_PASSWORD');
CREATE SECRET prod_redis ( TYPE redis, PROVIDER config, host 'cache.prod.internal', port '6379', password :redis_password);In the DuckDB 2.0 build a secret can also name a Redis 6+ ACL user, a database index and a timeout:
CREATE SECRET reports_redis ( TYPE redis, PROVIDER config, host 'cache.prod.internal', port '6379', username 'reporting', password :redis_password, db 2, timeout_ms 5000);See CREATE SECRET for the full secrets DSL and the Secrets section on this page for the redis parameter table.
String operations
-- Set a value (Redis SET)SELECT redis_set('user:1', 'John Doe', 'redis') AS ok;-- Get a value (Redis GET) — NULL if the key does not existSELECT redis_get('user:1', 'redis') AS user_name;-- Fall back to a default for missing keysSELECT coalesce(redis_get('user:999', 'redis'), 'unknown') AS user_name;-- Bulk write from a columnINSERT INTO users (id, name)SELECT id, redis_set('user:' || id::VARCHAR, name, 'redis')FROM new_users;-- Multi-get in one round-trip (Redis MGET)SELECT redis_mget('user:1,user:2,user:3', 'redis');-- → "John Doe,,Jane Roe" when user:2 is missingredis_mget returns the values comma-joined in the order the keys were requested, with an empty entry for each missing key, so positions always line up with the key list. In the DuckDB 2.0 build, redis_mget_list takes and returns lists instead, so values with commas and missing keys (NULL) stay unambiguous:
-- Typed multi-get (DuckDB 2.0 build)SELECT redis_mget_list(['user:1', 'user:2', 'user:3'], 'redis');-- → ['John Doe', NULL, 'Jane Roe']Maps to GET, SET, MGET. See redis_get / redis_set / redis_mget for the function signatures.
Hash operations
-- Set fields (Redis HSET) — returns the number of fields added (BIGINT)-- Get one field (Redis HGET) — NULL if the key or field does not existSELECT redis_hget('profile:1', 'email', 'redis') AS email;-- All fields and values as a table (Redis HGETALL)SELECT * FROM redis_hgetall('profile:1', 'redis');-- Or as a MAP, one per row (DuckDB 2.0 build)SELECT id, redis_hgetall_map('profile:' || id, 'redis')['email'] AS emailFROM users;Maps to HGET, HSET, HGETALL. See redis_hget / redis_hset / redis_hgetall.
List operations
-- Push values (Redis LPUSH) — returns the list length after the push (BIGINT)SELECT redis_lpush('queue:jobs', 'job-1', 'redis'); -- 1SELECT redis_lpush('queue:jobs', 'job-2', 'redis'); -- 2-- Read as a comma-joined stringSELECT redis_lrange('queue:jobs', 0, -1, 'redis');-- As a VARCHAR[] (DuckDB 2.0 build)SELECT redis_lrange_list('queue:jobs', 0, -1, 'redis');-- Or as a table — one row per element, index = position in the listSELECT * FROM redis_lrange_table('queue:jobs', 0, -1, 'redis');Maps to LPUSH and LRANGE. redis_lrange_table is the table-shaped variant — pick it when you want one DuckDB row per list element instead of a single comma-joined string from redis_lrange.
Discovery (SCAN)
Both discovery functions use cursor-paginated SCAN, never the server-blocking KEYS command:
-- Every matching key as a table — follows the SCAN cursor to the end for youSELECT * FROM redis_keys('user:*', 'redis');-- One SCAN page per call, when you want to control pagination yourselfSELECT redis_scan('0', 'user:*', 100, 'redis');-- → "1024:user:1,user:2,...,user:50"-- Pass the returned cursor (1024) back in to fetch the next page; cursor "0" means done.-- The same page as a STRUCT(cursor, keys) (DuckDB 2.0 build)SELECT page.cursor, unnest(page.keys) AS keyFROM (SELECT redis_scan_page('0', 'user:*', 100, 'redis') AS page);redis_keys walks the whole keyspace in one query, so keep the pattern narrow on large instances.
See redis_keys and redis_scan.
Bulk hash discovery (redis_hscan_over_scan)
The killer feature for migration and bulk analysis — combines SCAN with HSCAN to emit (key, field, value) rows for every hash matching a key pattern, in one query. Both cursors are followed to the end, and matching keys that aren’t hashes are skipped:
-- Every field of every user:* hash, as rowsSELECT key, field, valueFROM redis_hscan_over_scan( /* scan_pattern */ 'user:*', /* hscan_pattern */ '*', /* count */ 100, /* secret */ 'redis')ORDER BY key, field;Pipe directly into a CREATE TABLE AS for offline analysis or migration:
CREATE TABLE redis_users_dump ASSELECT key, field, valueFROM redis_hscan_over_scan('user:*', '*', 100, 'redis');See redis_hscan_over_scan for the full signature.
Key management
-- Type, existence, deletionSELECT redis_type('profile:1', 'redis'); -- 'hash'SELECT redis_exists('user:1', 'redis'); -- TRUESELECT redis_del('user:1', 'redis'); -- TRUE if existed and removedMaps to TYPE, EXISTS, DEL. See redis_type / redis_exists / redis_del.
Expiry (TTL)
-- Expire a key in one hourSELECT redis_expire('session:123', 3600, 'redis'); -- TRUE if the key exists-- Expire at an absolute time (Unix seconds)SELECT redis_expireat('cache:item', EXTRACT(EPOCH FROM TIMESTAMP '2027-01-01')::BIGINT, 'redis');-- Remaining seconds: -1 = no expiry, -2 = key does not existSELECT redis_ttl('session:123', 'redis');Combine with redis_keys to audit or apply expiry across a keyspace:
-- Find session keys that never expire, then give them a 5 minute TTLSELECT key, redis_expire(key, 300, 'redis') AS expiredFROM redis_keys('session:*', 'redis')WHERE redis_ttl(key, 'redis') = -1;Maps to EXPIRE, EXPIREAT, TTL. See redis_expire / redis_expireat / redis_ttl.
Any other command (redis_command)
In the DuckDB 2.0 build, redis_command runs any Redis command given as a VARCHAR[]. Strings and integers come back as text, nil as NULL, and array replies as JSON:
-- SetsSELECT redis_command(['SADD', 'tags', 'duckdb', 'redis'], 'redis'); -- '2'SELECT redis_command(['SMEMBERS', 'tags'], 'redis'); -- '["duckdb","redis"]'-- Counters, cast to the type you needSELECT redis_command(['INCRBY', 'page:views', '5'], 'redis')::BIGINT AS views;-- Sorted set leaderboard, unpacked with the json extensionSELECT unnest(json_transform( redis_command(['ZREVRANGE', 'leaderboard', '0', '9'], 'redis'), '["VARCHAR"]')) AS player;The connection used by redis_command is closed afterwards instead of being pooled, so commands that change connection state (SELECT, CLIENT, …) don’t leak into other queries.
Timeouts
Each connect and each wait for reply data is bounded by redis_timeout_ms (default 30 seconds) in the DuckDB 2.0 build. Lower it to fail fast, or set timeout_ms on a secret:
SET redis_timeout_ms = 2000;A query waiting on Redis can always be interrupted, and every redis_* function refuses when enable_external_access is false.
Platform Support
Compatibility
Extension availability may vary by platform and DuckDB version. Check below to ensure this extension supports your environment before installation.
Quick Facts
Platforms
DuckDB 2.0.0
- Linux x86_64aarch64
- Linux (musl) Not available
- macOS Apple Silicon
- Windows x86_64x86_64 (MinGW)
- WASM Not available
Compiled binary sizes
| Platform | Architecture | Size |
|---|---|---|
| Linux | x86_64 | 4.16 MB |
| Linux | aarch64 | 3.51 MB |
| macOS | Apple Silicon | 2.96 MB |
| Windows | x86_64 | 10.26 MB |
| Windows | x86_64 (MinGW) | 17.90 MB |
Compressed download sizes for the release shown above.
DuckDB & Haybarn
Release calendar- DuckDB v2.0.0 Query.Farm repository Supported
- Haybarn v1.5.6 Built-in community repository Supported
Browser examples use Haybarn-Wasm 2.0.0-rc12.
Checked .
Learn and explore
Tutorials and articles
Writing about Redis: how it works, what changed, and why.
-
Redis for DuckDB 2.0: typed replies, pooled connections and timeouts
Redis for DuckDB 2.0 adds lists and maps, cursor-based scans, pipelined commands, credential-scoped connection reuse, and interruptible network waits.