Skip to content

Binary keys and values

Store and read byte-exact keys and values through RESP and redis.command_bin.

PostgreSQL text values cannot contain NUL (\x00) bytes or invalid UTF-8 sequences, whereas Redis keys and values are arbitrary byte strings. Use redis.command_bin(bytea[], integer) from SQL (or raw binary arguments over RESP) to store and read arbitrary bytes without text conversion.

Send and read raw bytes

Connect to pgredis_demo as pgredis_app (psql -h 127.0.0.1 -p 5432 -U pgredis_app -d pgredis_demo) and pass bytea[] arguments containing \x00 and \xff bytes:

BEGIN;
SELECT redis.command_bin(ARRAY[
  'SET'::bytea, decode('006bff', 'hex'), decode('00ff', 'hex')
]);
SELECT encode(redis.command_bin(ARRAY[
  'GET'::bytea, decode('006bff', 'hex')
]), 'hex');
ROLLBACK;

The GET query returns 24320d0a00ff0d0a:

  • 24320d0a is the RESP bulk string header $2\r\n (2 bytes).
  • 00ff is the exact two-byte payload.
  • 0d0a is the trailing \r\n.

Keep the interface binary

Always use redis.command_bin(bytea[], integer) when keys, values, hash fields, set members, sorted-set members or Pub/Sub channel names can contain NUL bytes or non-UTF-8 payloads. Parse the outer RESP frame in bytea before interpreting the payload bytes, and do not pass binary payloads through PostgreSQL text or JSON string conversions.

Scan to open this page
https://mimus.pgsty.com/docs/redis/tutorial/binary-data/