### Set and Get Data in Valkey Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Basic example demonstrating how to set a key-value pair and retrieve its value using the Valkey client. Ensure the Valkey client is imported and initialized. ```python import valkey r = valkey.Valkey(decode_responses=True) r.set('mykey', 'thevalueofmykey') r.get('mykey') ``` -------------------------------- ### Run Development Environment Setup Source: https://github.com/valkey-io/valkey-py/blob/main/CONTRIBUTING.md Command to set up the full development environment using Docker Compose. Assumes Docker and Docker Compose with profiles support are installed. ```bash make devenv ``` -------------------------------- ### Install Valkey-Py Source: https://github.com/valkey-io/valkey-py/blob/main/README.md Install the valkey-py library using pip. ```bash $ pip install valkey ``` -------------------------------- ### Install Valkey-Py Package Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/opentelemetry/README.md Install the valkey-py package from the local source. ```shell pip install . ``` -------------------------------- ### Run Valkey Client Example Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/opentelemetry/README.md Execute the main client example script to generate traces and view them via the provided link. ```shell python3 main.py ``` -------------------------------- ### Start Valkey via Docker Source: https://github.com/valkey-io/valkey-py/blob/main/README.md Use this command to start a Valkey instance using Docker for local development or testing. ```bash docker run -p 6379:6379 -it valkey/valkey:latest ``` -------------------------------- ### Clone Example Repository Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/opentelemetry/README.md Download the example code for OpenTelemetry instrumentation using Git. ```shell git clone https://github.com/valkey-io/valkey-py.git cd example/opentelemetry ``` -------------------------------- ### Start Services with Docker Compose Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/opentelemetry/README.md Start Valkey Server and Uptrace services using Docker Compose and view Uptrace logs. ```shell docker compose up -d docker compose logs uptrace ``` -------------------------------- ### Migration from redis-py Source: https://github.com/valkey-io/valkey-py/blob/main/README.md Use the valkey alias for smooth transition from redis-py. This example demonstrates setting and getting a value. ```python import valkey as redis r = redis.Redis(host='localhost', port=6379, db=0) r.set('foo', 'bar') # True r.get('foo') # b'bar' ``` -------------------------------- ### Install Valkey-Py with libvalkey support Source: https://github.com/valkey-io/valkey-py/blob/main/README.md Install valkey-py with optional libvalkey support for faster performance. This requires libvalkey version 2.3.2 or newer. ```bash $ pip install "valkey[libvalkey]" ``` -------------------------------- ### Install Cohere Package Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/search_vector_similarity_examples.ipynb Installs the Cohere Python client library. ```python %pip install cohere ``` -------------------------------- ### Install OpenAI Package Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/search_vector_similarity_examples.ipynb Installs the OpenAI Python client library. ```python %pip install openai ``` -------------------------------- ### Create Virtual Environment and Install Dev Dependencies Source: https://github.com/valkey-io/valkey-py/blob/main/CONTRIBUTING.md Steps to create a Python virtual environment and install development dependencies using pip. ```bash python -m venv .venv source .venv/bin/activate pip install --group dev ``` -------------------------------- ### Install OpenTelemetry Libraries Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/opentelemetry_api_examples.ipynb Install the necessary OpenTelemetry API and SDK packages using pip. This is a prerequisite for using the tracing functionalities. ```bash pip install opentelemetry-api opentelemetry-sdk ``` -------------------------------- ### Valkey Connection URL Examples Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Examples of supported URL formats for connecting to Valkey, including TCP, SSL-wrapped TCP, and Unix Domain Socket connections. These URLs can specify username, password, host, port, and database. ```text valkey://[[username]:[password]]@localhost:6379/0 valkeys://[[username]:[password]]@localhost:6379/0 unix://[username@]/path/to/socket.sock?db=0[&password=password] ``` -------------------------------- ### Sentinel Client Connection Example Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Demonstrates how to connect to Valkey Sentinel instances and discover master and slave nodes. ```APIDOC ## Sentinel Client Valkey Sentinel provides high availability for Valkey. There are commands that can only be executed against a Valkey node running in sentinel mode. Connecting to those nodes, and executing commands against them requires a Sentinel connection. ### Connection Example: ```pycon >>> from valkey import Sentinel >>> sentinel = Sentinel([('localhost', 26379)], socket_timeout=0.1) >>> sentinel.discover_master('mymaster') ('127.0.0.1', 6379) >>> sentinel.discover_slaves('mymaster') [('127.0.0.1', 6380)] ``` ``` -------------------------------- ### Connect to a Sentinel Instance Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/connection_examples.ipynb Connect to a Valkey Sentinel instance to discover master nodes. This example shows how to initialize Sentinel with a list of addresses and a timeout. ```python from valkey.sentinel import Sentinel sentinel = Sentinel([("localhost", 26379)], socket_timeout=0.1) sentinel.discover_master("valkey-py-test") ``` -------------------------------- ### Valkey Client Initialization Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Demonstrates how to initialize a Valkey client, including options for standalone replica redirect and URL-based connection. ```APIDOC ## valkey.Valkey ### Description Implementation of the Valkey protocol. This abstract class provides a Python interface to all Valkey commands and an implementation of the Valkey protocol. ### Parameters * **host** (str) - Default: 'localhost' * **port** (int) - Default: 6379 * **db** (int) - Default: 0 * **password** (str | None) * **socket_timeout** (int | None) * **socket_connect_timeout** (int | None) * **socket_keepalive** (bool | None) * **socket_keepalive_options** (dict | None) * **connection_pool** (ConnectionPool | None) * **unix_socket_path** (str | None) * **encoding** (str) - Default: 'utf-8' * **encoding_errors** (str) - Default: 'strict' * **charset** (str | None) * **errors** (str | None) * **decode_responses** (bool) - Default: False * **retry_on_timeout** (bool) - Default: False * **retry_on_error** (list[Exception] | None) * **ssl** (bool) - Default: False * **ssl_keyfile** (str | None) * **ssl_certfile** (str | None) * **ssl_cert_reqs** (str) - Default: 'required' * **ssl_ca_certs** (str | None) * **ssl_ca_path** (str | None) * **ssl_ca_data** (str | None) * **ssl_check_hostname** (bool) - Default: False * **ssl_password** (str | None) * **ssl_validate_ocsp** (bool) - Default: False * **ssl_validate_ocsp_stapled** (bool) - Default: False * **ssl_ocsp_context** (ssl.SSLContext | None) * **ssl_ocsp_expected_cert** (str | None) * **ssl_min_version** (int | None) * **ssl_ciphers** (str | None) * **max_connections** (int | None) * **single_connection_client** (bool) - Default: False * **health_check_interval** (int) - Default: 0 * **client_name** (str | None) * **lib_name** (str | None) - Default: 'valkey-py' * **lib_version** (str | None) - Default: '6.2.0rc2' * **username** (str | None) * **retry** (Retry | None) * **valkey_connect_func** (Callable | None) * **credential_provider** (CredentialProvider | None) * **protocol** (int | None) - Default: 2 * **client_capa_redirect** (bool) - Default: False * **cache_enabled** (bool) - Default: False * **client_cache** (AbstractCache | None) * **cache_max_size** (int) - Default: 10000 * **cache_ttl** (int) - Default: 0 * **cache_policy** (EvictionPolicy) - Default: EvictionPolicy.LRU * **cache_deny_list** (List[str]) * **cache_allow_list** (List[str]) ### Method ```python valkey.Valkey( host='localhost', port=6379, db=0, password=None, socket_timeout=None, socket_connect_timeout=None, socket_keepalive=None, socket_keepalive_options=None, connection_pool=None, unix_socket_path=None, encoding='utf-8', encoding_errors='strict', charset=None, errors=None, decode_responses=False, retry_on_timeout=False, retry_on_error=None, ssl=False, ssl_keyfile=None, ssl_certfile=None, ssl_cert_reqs='required', ssl_ca_certs=None, ssl_ca_path=None, ssl_ca_data=None, ssl_check_hostname=False, ssl_password=None, ssl_validate_ocsp=False, ssl_validate_ocsp_stapled=False, ssl_ocsp_context=None, ssl_ocsp_expected_cert=None, ssl_min_version=None, ssl_ciphers=None, max_connections=None, single_connection_client=False, health_check_interval=0, client_name=None, lib_name='valkey-py', lib_version='6.2.0rc2', username=None, retry=None, valkey_connect_func=None, credential_provider=None, protocol=2, client_capa_redirect=False, cache_enabled=False, client_cache=None, cache_max_size=10000, cache_ttl=0, cache_policy=EvictionPolicy.LRU, cache_deny_list=[ 'BF.CARD', 'BF.DEBUG', 'BF.EXISTS', 'BF.INFO', 'BF.MEXISTS', 'BF.SCANDUMP', 'CF.COMPACT', 'CF.COUNT', 'CF.DEBUG', 'CF.EXISTS', 'CF.INFO', 'CF.MEXISTS', 'CF.SCANDUMP', 'CMS.INFO', 'CMS.QUERY', 'DUMP', 'EXPIRETIME', 'FT.AGGREGATE', 'FT.ALIASADD', 'FT.ALIASDEL', 'FT.ALIASUPDATE', 'FT.CURSOR', 'FT.EXPLAIN', 'FT.EXPLAINCLI', 'FT.GET', 'FT.INFO', 'FT.MGET', 'FT.PROFILE', 'FT.SEARCH', 'FT.SPELLCHECK', 'FT.SUGGET', 'FT.SUGLEN', 'FT.SYNDUMP', 'FT.TAGVALS', 'FT._ALIASADDIFNX', 'FT._ALIASDELIFX', 'HRANDFIELD', 'JSON.DEBUG', 'PEXPIRETIME', 'PFCOUNT', 'PTTL', 'SRANDMEMBER', 'TDIGEST.BYRANK', 'TDIGEST.BYREVRANK', 'TDIGEST.CDF', 'TDIGEST.INFO', 'TDIGEST.MAX', 'TDIGEST.MIN', 'TDIGEST.QUANTILE', 'TDIGEST.RANK', 'TDIGEST.REVRANK', 'TDIGEST.TRIMMED_MEAN', 'TOPK.INFO', 'TOPK.LIST', 'TOPK.QUERY', 'TOUCH', 'TTL', ], cache_allow_list=[ 'BITCOUNT', 'BITFIELD_RO', 'BITPOS', 'EXISTS', 'GEODIST', 'GEOHASH', 'GEOPOS', 'GEORADIUSBYMEMBER_RO', 'GEORADIUS_RO', 'GEOSEARCH', 'GET', 'GETBIT', 'GETRANGE', 'HEXISTS', 'HGET', 'HGETALL', 'HKEYS', 'HLEN', 'HMGET', 'HSTRLEN', 'HVALS', 'JSON.ARRINDEX', 'JSON.ARRLEN', 'JSON.GET', 'JSON.MGET', 'JSON.OBJKEYS', 'JSON.OBJLEN', 'JSON.RESP', 'JSON.STRLEN', 'JSON.TYPE', 'LCS', 'LINDEX', 'LLEN', 'LPOS', 'LRANGE', 'MGET', 'SCARD', 'SDIFF', 'SINTER', 'SINTERCARD', 'SISMEMBER', 'SMEMBERS', 'SMISMEMBER', 'SORT_RO', 'STRLEN', 'SUBSTR', 'SUNION', 'TS.GET', 'TS.INFO', 'TS.RANGE', 'TS.REVRANGE', 'TYPE', 'XLEN', 'XPENDING', 'XRANGE', 'XREVRANGE', 'ZCARD', 'ZCOUNT', 'ZDIFF', 'ZINTER', 'ZINTERCARD', 'ZLEXCOUNT', 'ZMSCORE', 'ZRANGE', 'ZRANGEBYLEX', 'ZRANGEBYSCORE', 'ZRANK', 'ZREVRANGE', 'ZREVRANGEBYLEX', 'ZREVRANGEBYSCORE', 'ZREVRANK', 'ZSCORE', 'ZUNION', ]) # Example with client_capa_redirect enabled valkey.Valkey(host="localhost", port=6380, client_capa_redirect=True) # Example using from_url valkey.from_url("valkey://localhost:6380?client_capa_redirect=true") ``` -------------------------------- ### Build Documentation Locally Source: https://github.com/valkey-io/valkey-py/blob/main/CONTRIBUTING.md Build the project documentation locally to preview changes before deployment. ```bash make build-docs ``` -------------------------------- ### slowlog_get Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Get the entries from the slowlog. If `num` is specified, get the most recent `num` items. ```APIDOC ## slowlog_get(num=None, **kwargs) ### Description Get the entries from the slowlog. If `num` is specified, get the most recent `num` items. ### Parameters: * **num** (int | None) ### Return type: list[dict[str, int | bytes]] | Awaitable[list[dict[str, int | bytes]]] ### See Also: [https://valkey.io/commands/slowlog-get](https://valkey.io/commands/slowlog-get) ``` -------------------------------- ### Get Valkey ACL Help Information Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Fetches and returns helpful text describing the different ACL subcommands available on the Valkey server. ```python r.acl_help() ``` -------------------------------- ### DCO Signed-off-by Example Source: https://github.com/valkey-io/valkey-py/blob/main/CONTRIBUTING.md An example of the 'Signed-off-by' line required in commit messages to comply with the DCO. ```text Signed-off-by: Jane Smith ``` -------------------------------- ### Install OpenTelemetry Redis Instrumentation Source: https://github.com/valkey-io/valkey-py/blob/main/docs/opentelemetry.md Install the necessary package for OpenTelemetry Redis instrumentation using pip. ```shell pip install opentelemetry-instrumentation-redis ``` -------------------------------- ### Initialize Valkey and Timeseries Client Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/timeseries_examples.ipynb Establishes a connection to Valkey and initializes the timeseries client. Ensure Valkey is running and accessible. ```python import valkey r = valkey.Valkey(decode_responses=True) ts = r.ts() r.ping() ``` -------------------------------- ### Install Packages Inside a Container Source: https://github.com/valkey-io/valkey-py/blob/main/CONTRIBUTING.md Update package lists and install new packages within a container's bash session. ```bash $ apt update && apt install ``` -------------------------------- ### Initialize Valkey Connection Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/valkey-stream-example.ipynb Establishes a connection to the Valkey server and pings it to verify connectivity. Ensure Valkey is running and accessible. ```python import valkey from time import time from valkey.exceptions import ( ConnectionError, DataError, NoScriptError, ValkeyError, ResponseError, ) valkey_host = "valkey" stream_key = "skey" stream2_key = "s2key" group1 = "grp1" group2 = "grp2" r = valkey.Valkey(valkey_host) r.ping() ``` -------------------------------- ### Connect, Ping, and Disconnect with Asyncio Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/asyncio_examples.ipynb Demonstrates basic connection, ping, and disconnection using Valkey's asyncio interface. Ensure to explicitly disconnect the client when using asyncio. ```python import valkey.asyncio as valkey client = valkey.Valkey() print(f"Ping successful: {await client.ping()}") await client.aclose() ``` -------------------------------- ### Create a PubSub Instance Source: https://github.com/valkey-io/valkey-py/blob/main/docs/advanced_features.md Instantiate a PubSub object to subscribe to channels and listen for messages. This is the first step in setting up a publish/subscribe communication channel. ```python >>> r = valkey.Valkey(...) >>> p = r.pubsub() ``` -------------------------------- ### Valkey Pipelining Example Source: https://github.com/valkey-io/valkey-py/blob/main/README.md Demonstrates how to use Valkey pipelines to batch commands and optimize round-trip calls. The execute() method returns a list of results corresponding to the commands. ```python pipe = r.pipeline() pipe.set('foo', 5) pipe.set('bar', 18.5) pipe.set('blee', "hello world!") pipe.execute() # [True, True, True] ``` -------------------------------- ### Initialize Sentinel and Connect to Master/Slave Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Instantiate a Sentinel client and obtain master and slave connections for a given service name. Useful for managing high-availability Valkey setups. ```python >>> from valkey.sentinel import Sentinel >>> sentinel = Sentinel([('localhost', 26379)], socket_timeout=0.1) >>> master = sentinel.master_for('mymaster', socket_timeout=0.1) >>> master.set('foo', 'bar') >>> slave = sentinel.slave_for('mymaster', socket_timeout=0.1) >>> slave.get('foo') ``` -------------------------------- ### ltrim(name, start, end) Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Trims a list in Valkey, keeping only the elements within the specified start and end indices. Supports negative indexing similar to Python slicing. ```APIDOC ## ltrim(name, start, end) ### Description Trim the list `name`, removing all values not within the slice between `start` and `end`. `start` and `end` can be negative numbers just like Python slicing notation. ### Parameters * **name** (bytes | str | memoryview) * **start** (int) * **end** (int) ### Return type Literal[True] | Awaitable[Literal[True]] ``` -------------------------------- ### getex Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Get the value of a key and optionally set its expiration. This command is similar to GET but is a write command with additional options for setting expiration times in seconds, milliseconds, or Unix timestamps, or for persisting the key. ```APIDOC ## getex(name, ex=None, px=None, exat=None, pxat=None, persist=False) ### Description Get the value of key and optionally set its expiration. GETEX is similar to GET, but is a write command with additional options. All time parameters can be given as datetime.timedelta or integers. `ex` sets an expire flag on key `name` for `ex` seconds. `px` sets an expire flag on key `name` for `px` milliseconds. `exat` sets an expire flag on key `name` for `ex` seconds, specified in unix time. `pxat` sets an expire flag on key `name` for `ex` milliseconds, specified in unix time. `persist` remove the time to live associated with `name`. For more information see [https://valkey.io/commands/getex](https://valkey.io/commands/getex) ### Parameters * **name** (bytes | str | memoryview) * **ex** (int | timedelta | None) * **px** (int | timedelta | None) * **exat** (int | datetime | None) * **pxat** (int | datetime | None) * **persist** (bool) ### Return type str | bytes | None | Awaitable[str | bytes | None] ``` -------------------------------- ### Create a Pub/Sub Client Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Instantiate a Publish/Subscribe client to subscribe to channels and listen for messages. ```python pubsub = client.pubsub() ``` -------------------------------- ### getex Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Get the value of a key and optionally set its expiration time. This command is similar to GET but is a write command with additional options for setting expiration in seconds, milliseconds, or Unix timestamps, or for persisting the key. ```APIDOC ## getex(name, ex=None, px=None, exat=None, pxat=None, persist=False) ### Description Get the value of key and optionally set its expiration. GETEX is similar to GET, but is a write command with additional options. All time parameters can be given as datetime.timedelta or integers. `ex` sets an expire flag on key `name` for `ex` seconds. `px` sets an expire flag on key `name` for `px` milliseconds. `exat` sets an expire flag on key `name` for `ex` seconds, specified in unix time. `pxat` sets an expire flag on key `name` for `ex` milliseconds, specified in unix time. `persist` remove the time to live associated with `name`. For more information see [https://valkey.io/commands/getex](https://valkey.io/commands/getex) ### Parameters: * **name** (*bytes* *|* *str* *|* *memoryview*) * **ex** (*int* *|* *timedelta* *|* *None*) * **px** (*int* *|* *timedelta* *|* *None*) * **exat** (*int* *|* *datetime* *|* *None*) * **pxat** (*int* *|* *datetime* *|* *None*) * **persist** (*bool*) ### Return type: str | bytes | None | *Awaitable*[str | bytes | None] ``` -------------------------------- ### ValkeyCluster.initialize Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Asynchronously retrieves all nodes from startup nodes and establishes connections if they have not been initialized yet. ```APIDOC ## async initialize() ### Description Get all nodes from startup nodes & creates connections if not initialized. ### Return type [ValkeyCluster](#valkey.asyncio.cluster.ValkeyCluster) ``` -------------------------------- ### slowlog_len Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Get the number of items in the slowlog. ```APIDOC ## slowlog_len(**kwargs) ### Description Get the number of items in the slowlog. ### Return type: int | Awaitable[int] ### See Also: [https://valkey.io/commands/slowlog-len](https://valkey.io/commands/slowlog-len) ``` -------------------------------- ### Get Replica Nodes Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Retrieves only the replica nodes from the cluster. ```python valkey_client.get_replicas() ``` -------------------------------- ### Initialize Cluster Connections Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Asynchronously fetches all nodes from startup nodes and establishes connections if the cluster has not been initialized. ```python await valkey_client.initialize() ``` -------------------------------- ### Monitor Valkey Server Commands Source: https://github.com/valkey-io/valkey-py/blob/main/docs/advanced_features.md Demonstrates how to use the Monitor object to stream and print every command processed by the Valkey server in real-time. ```python >>> r = valkey.Valkey(...) >>> with r.monitor() as m: >>> for command in m.listen(): >>> print(command) ``` -------------------------------- ### Get Primary Nodes Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Retrieves only the primary nodes from the cluster. ```python valkey_client.get_primaries() ``` -------------------------------- ### Connect with Custom Connection Pool (Asyncio) Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/asyncio_examples.ipynb Shows how to create a Valkey client from a custom ConnectionPool. The Valkey client takes ownership of the pool, and closing the client also disconnects the pool. ```python import valkey.asyncio as valkey pool = valkey.ConnectionPool.from_url("valkey://localhost") client = valkey.Valkey.from_pool(pool) await client.aclose() ``` -------------------------------- ### Get Cluster Nodes Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Retrieves all nodes participating in the cluster. ```python valkey_client.get_nodes() ``` -------------------------------- ### Get Connection from Pool Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Retrieve a connection from the pool for a specific command. ```python connection = pool.get_connection('SET') ``` -------------------------------- ### Valkey Pub/Sub Subscription Example Source: https://github.com/valkey-io/valkey-py/blob/main/README.md Shows how to utilize Valkey Pub/Sub to subscribe to channels and receive messages. The get_message() method retrieves the next message from the subscription. ```python r = valkey.Valkey(...) p = r.pubsub() p.subscribe('my-first-channel', 'my-second-channel', ...) p.get_message() # {'pattern': None, 'type': 'subscribe', 'channel': b'my-second-channel', 'data': 1} ``` -------------------------------- ### Get Random Node Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Selects and returns a random node from the cluster. ```python valkey_client.get_random_node() ``` -------------------------------- ### cluster_nodes Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Gets the Cluster config for the node. Sends to a random node in the cluster. ```APIDOC ## cluster_nodes() ### Description Gets the Cluster config for the node. Sends to a random node in the cluster. ### Method Not specified (assumed to be a client library method) ### Endpoint Not specified ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ``` -------------------------------- ### Paginating and Ordering Search Results Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/search_json_examples.ipynb This example shows how to paginate and order search results. It retrieves users, returning two at a time, sorted by age in descending order. ```python # Search for all users, returning 2 users at a time and sorting by age in descending order offset = 0 num = 2 q = ( Query("*" ).paging(offset, num).sort_by("age", asc=False) # pass asc=True to sort in ascending order ) r.ft().search(q) ``` ```text Result: Result{4 total, docs: [Document {'id': 'user:1', 'payload': None, 'age': '42', 'json': '{"user":{"name":"Paul John","email":"paul.john@example.com","age":42,"city":"London"}}'}, Document {'id': 'user:3', 'payload': None, 'age': '35', 'json': '{"user":{"name":"Paul Zamir","email":"paul.zamir@example.com","age":35,"city":"Tel Aviv"}}'}]} ``` -------------------------------- ### Get Encoder Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Retrieves the encoder object used by the client for data serialization. ```python valkey_client.get_encoder() ``` -------------------------------- ### Loading External Valkey Modules Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Demonstrates how to load external Valkey modules and their commands into the Valkey client. This allows for extending the client with custom functionalities defined in external modules. ```python from valkey import Valkey from foomodule import F r = Valkey() r.load_external_module("foo", F) r.foo().do_thing(‘your’, ‘arguments’) ``` -------------------------------- ### Get Default Node Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Retrieves the currently configured default node for the client. ```python valkey_client.get_default_node() ``` -------------------------------- ### Asyncio Connect via URL (TCP with RESP 3) Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/asyncio_examples.ipynb Connect to a Valkey instance using a URL and enable the RESP 3 protocol by appending 'protocol=3'. This example also includes 'decode_responses=True'. ```python import valkey.asyncio as valkey url_connection = valkey.from_url( "valkey://localhost:6379?decode_responses=True&protocol=3" ) url_connection.ping() ``` -------------------------------- ### get Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Retrieves the value associated with a given key. Returns None if the key does not exist. ```APIDOC ## get ### Description Return the value at key `name`, or None if the key doesn’t exist. ### Method Not applicable (Python method) ### Parameters #### Path Parameters Not applicable #### Query Parameters Not applicable #### Request Body Not applicable ### Parameters * **name** (*bytes* *|* *str* *|* *memoryview*) - Required ### Return type str | bytes | None | *Awaitable*[str | bytes | None] ``` -------------------------------- ### Connect to Valkey Server Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/set_and_get_examples.ipynb Establishes a connection to the Valkey server. Ensure decode_responses is set appropriately for your needs. ```python import valkey r = valkey.Valkey(decode_responses=True) r.ping() ``` -------------------------------- ### get Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Retrieves the value associated with a given key. Returns None if the key does not exist. ```APIDOC ## get(name) ### Description Return the value at key `name`, or None if the key doesn’t exist. ### Parameters: * **name** (*bytes* *|* *str* *|* *memoryview*) ### Return type: str | bytes | None | *Awaitable*[str | bytes | None] ``` -------------------------------- ### on_connect Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Initializes the connection, authenticates, selects a database, and sends READONLY if set during initialization. ```APIDOC ## on_connect(connection) ### Description Initialize the connection, authenticate and select a database and send : READONLY if it is set during object initialization. ### Parameters #### Path Parameters - **connection** (object) - Required - The connection object. ``` -------------------------------- ### acl_getuser Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Get the ACL details for the specified username. If `username` does not exist, return None. ```APIDOC ## acl_getuser ### Description Get the ACL details for the specified `username`. If `username` does not exist, return None. ### Method APIDOC ### Endpoint APIDOC ### Parameters #### Path Parameters - **username** (str) - Required - The username to retrieve ACL details for. #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **dict[str, bool | list[str] | list[list[str]] | list[dict[str, str]]] | None** - The ACL details for the user, or None if the user does not exist. #### Response Example N/A ``` -------------------------------- ### Get Pub/Sub Channels Source: https://github.com/valkey-io/valkey-py/blob/main/docs/advanced_features.md Demonstrates how to retrieve a list of all currently active Pub/Sub channels. ```python >>> r.pubsub_channels() [b'foo', b'bar'] ``` -------------------------------- ### from_url() Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Creates a Valkey client configured from a given URL, supporting valkey, valkeys, and unix schemes. ```APIDOC ## from_url() ### Description Returns a Valkey client object configured from the given URL. Supports `valkey://`, `valkeys://`, and `unix://` URL schemes. ### Method Class Method ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **url** (*str*) – The connection URL. * **single_connection_client** (*bool*) – If True, creates a client with a single connection. * **auto_close_connection_pool** (*bool* | *None*) – Whether to automatically close the connection pool. * **kwargs** (*Any*) – Additional keyword arguments passed to the ConnectionPool initializer. ### Response #### Success Response * **Valkey** ([*Valkey*](#valkey.asyncio.client.Valkey)) – A new Valkey client instance configured from the URL. ### Response Example None ### Example URL Formats: ```default valkey://[[username]:[password]]@localhost:6379/0 valkeys://[[username]:[password]]@localhost:6379/0 unix://[username@]/path/to/socket.sock?db=0[&password=password] ``` ``` -------------------------------- ### setrange Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Overwrites bytes in a string value starting at a specified offset with new value. ```APIDOC ## setrange ### Description Overwrite bytes in the value of `name` starting at `offset` with `value`. If `offset` plus the length of `value` exceeds the length of the original value, the new value will be larger than before. If `offset` exceeds the length of the original value, null bytes will be used to pad between the end of the previous value and the start of what’s being injected. Returns the length of the new string. ### Method Not specified (assumed to be a client method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **name** (bytes | str | memoryview) * **offset** (int) * **value** (bytes | memoryview | str | int | float) ### Return type int | Awaitable[int] ``` -------------------------------- ### Create Valkey Client from URL Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Configure a Valkey client object by providing a connection URL. Supports 'valkey://' for TCP and 'valkeys://' for SSL connections. URL components like username, password, and query parameters are parsed and applied. ```python valkey://[[username]:[password]]@localhost:6379/0 valkeys://[[username]:[password]]@localhost:6379/0 ``` -------------------------------- ### cluster_slots Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Get array of Cluster slot to node mappings. For more information see https://valkey.io/commands/cluster-slots ```APIDOC ## cluster_slots ### Description Get array of Cluster slot to node mappings. ### Parameters * **target_nodes** (TargetNodesT | None) - Optional - The target nodes for the cluster slots. ### Return type Any | Awaitable[Any] ``` -------------------------------- ### acl_whoami Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Gets the username for the current connection. This command is useful for identifying the currently authenticated user. ```APIDOC ## acl_whoami(**kwargs) ### Description Get the username for the current connection ### Return type str | bytes | *Awaitable*[str | bytes] ``` -------------------------------- ### Execute multi-key commands on Valkey Cluster Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/timeseries_examples.ipynb Demonstrates how to execute multi-key commands on a Valkey cluster using `ValkeyCluster`. It includes refreshing cluster state and performing Time Series operations. ```python import valkey r = valkey.ValkeyCluster(host="localhost", port=46379) # This command should be executed on all cluster nodes after creation and any re-sharding # Please note that this command is internal and will be deprecated in the future r.execute_command("timeseries.REFRESHCLUSTER", target_nodes="primaries") # Now multi-key commands can be executed ts = r.ts() ts.add("ts_key1", "*", 2, labels={"label1": 1, "label2": 2}) ts.add("ts_key2", "*", 10, labels={"label1": 1, "label2": 2}) ts.mget(["label1=1"]) ``` -------------------------------- ### acl_whoami Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Gets the username for the current connection. This is useful for identifying the authenticated user making the request. ```APIDOC ## acl_whoami(**kwargs) ### Description Get the username for the current connection. ### Return type str | bytes | *Awaitable*[str | bytes] ``` -------------------------------- ### Get Connection Arguments Source: https://github.com/valkey-io/valkey-py/blob/main/docs/connections.md Retrieves the keyword arguments that were passed to the underlying Connection object during initialization. ```python valkey_client.get_connection_kwargs() ``` -------------------------------- ### Connect with Async Client (RESP 3) Source: https://github.com/valkey-io/valkey-py/blob/main/docs/resp3_features.md Establishes an asynchronous connection to Valkey with RESP 3 protocol. ```python import valkey.asyncio as valkey r = valkey.Valkey(host='localhost', port=6379, protocol=3) await r.ping() ``` -------------------------------- ### Connect with Initial Credentials and Credential Provider Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/connection_examples.ipynb Connects to a Valkey instance using an initial set of credentials, and then switches to an external credential supplier on subsequent calls. This is useful for scenarios where initial credentials are known but might change or need to be fetched dynamically. ```python from typing import Union import valkey class InitCredsSetCredentialProvider(valkey.CredentialProvider): def __init__(self, username, password): self.username = username self.password = password self.call_supplier = False def call_external_supplier(self) -> Union[Tuple[str], Tuple[str, str]]: # Call to an external credential supplier raise NotImplementedError def get_credentials(self) -> Union[Tuple[str], Tuple[str, str]]: if self.call_supplier: return self.call_external_supplier() # Use the init set only for the first time self.call_supplier = True return self.username, self.password cred_provider = InitCredsSetCredentialProvider( username="init_user", password="init_pass" ) ``` -------------------------------- ### Get Number of Pattern Subscriptions Source: https://github.com/valkey-io/valkey-py/blob/main/docs/advanced_features.md Demonstrates how to retrieve the total count of active pattern subscriptions. ```python >>> r.pubsub_numpat() 1204 ``` -------------------------------- ### Get Number of Subscribers for Channels Source: https://github.com/valkey-io/valkey-py/blob/main/docs/advanced_features.md Shows how to query the number of subscribers for specific Pub/Sub channels. ```python >>> r.pubsub_numsub('foo', 'bar') [(b'foo', 9001), (b'bar', 42)] >>> r.pubsub_numsub('baz') [(b'baz', 0)] ``` -------------------------------- ### Connect with Host, Port, Username, and Password Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/connection_examples.ipynb Connects to a Valkey instance on a specified host and port, using username and password for authentication. Decodes responses to strings. ```python import valkey user_connection = valkey.Valkey( host="localhost", port=6380, username="dvora", password="valkey", decode_responses=True, ) user_connection.ping() ``` -------------------------------- ### Configure Valkey Standalone Client with Retries Source: https://github.com/valkey-io/valkey-py/blob/main/docs/retry.md Set up a Valkey client with a Retry instance for exponential backoff and specify custom errors to retry on. Also shows how to configure retries for timeout errors only. ```python from valkey.backoff import ExponentialBackoff from valkey.retry import Retry from valkey.client import Valkey from valkey.exceptions import ( BusyLoadingError, ConnectionError, TimeoutError ) # Run 3 retries with exponential backoff strategy retry = Retry(ExponentialBackoff(), 3) # Valkey client with retries on custom errors r = Valkey(host='localhost', port=6379, retry=retry, retry_on_error=[BusyLoadingError, ConnectionError, TimeoutError]) # Valkey client with retries on TimeoutError only r_only_timeout = Valkey(host='localhost', port=6379, retry=retry, retry_on_timeout=True) ``` -------------------------------- ### Get a specific node connection Source: https://github.com/valkey-io/valkey-py/blob/main/docs/clustering.md Obtains a connection object for a specific node in the cluster by its address. ```python >>> p2 = rc.pubsub(rc.get_node('localhost', 6379)) ``` -------------------------------- ### Creating and Executing a Basic Pipeline Source: https://github.com/valkey-io/valkey-py/blob/main/docs/advanced_features.md Use the pipeline() method to buffer commands and execute them in a single request. Responses are returned as a list. ```python >>> r = valkey.Valkey(...) >>> r.set('bing', 'baz') >>> # Use the pipeline() method to create a pipeline instance >>> pipe = r.pipeline() >>> # The following SET commands are buffered >>> pipe.set('foo', 'bar') >>> pipe.get('bing') >>> # the EXECUTE call sends all buffered commands to the server, returning >>> # a list of responses, one for each command. >>> pipe.execute() [True, b'baz'] ``` -------------------------------- ### Clean Up Docker Resources Source: https://github.com/valkey-io/valkey-py/blob/main/CONTRIBUTING.md Command to remove Docker resources created by the development environment setup. ```bash make clean ``` -------------------------------- ### Get the Last Sample from Timeseries Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/timeseries_examples.ipynb Retrieves the most recent data point added to a specified timeseries key. ```python ts.get("ts_key") ``` -------------------------------- ### Execute Valkey commands via Cluster Client Source: https://github.com/valkey-io/valkey-py/blob/main/docs/clustering.md Demonstrates setting and getting keys, and executing cluster-wide commands like keys() and ping() using the ValkeyCluster client. The client automatically routes key-based commands to the correct node. ```python # target-nodes: the node that holds 'foo1's key slot rc.set('foo1', 'bar1') # target-nodes: the node that holds 'foo2's key slot rc.set('foo2', 'bar2') # target-nodes: the node that holds 'foo1's key slot print(rc.get('foo1')) # target-node: default-node print(rc.keys()) # target-node: default-node rc.ping() ``` -------------------------------- ### Subscribe to Sharded Channels Source: https://github.com/valkey-io/valkey-py/blob/main/docs/advanced_features.md Example of subscribing to a sharded channel using ValkeyCluster and retrieving sharded messages. ```python >>> from valkey.cluster import ValkeyCluster, ClusterNode >>> r = ValkeyCluster(startup_nodes=[ClusterNode('localhost', 6379), ClusterNode('localhost', 6380)]) >>> p = r.pubsub() >>> p.ssubscribe('foo') >>> # assume someone sends a message along the channel via a publish >>> message = p.get_sharded_message() ``` -------------------------------- ### module_loadex Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Loads a module from a dynamic library at runtime with configuration directives. This command allows for dynamic loading of Valkey modules, providing flexibility in extending Valkey's functionality. ```APIDOC ## module_loadex(path, options=None, args=None) ### Description Loads a module from a dynamic library at runtime with configuration directives. ### Parameters * **path** (str) - The path to the dynamic library of the module. * **options** (list[str] | None) - Optional list of configuration options. * **args** (list[str] | None) - Optional list of arguments for the module. ### Return type str | bytes | Awaitable[str | bytes] ``` -------------------------------- ### Initialize Cohere Client Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/search_vector_similarity_examples.ipynb Initializes the Cohere client with your API key. Replace 'YOUR COHERE API KEY' with your actual key. ```python import cohere co = cohere.Client("YOUR COHERE API KEY") ``` -------------------------------- ### zrevrangebylex Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Return the reversed lexicographical range of values from a sorted set. Supports slicing with start and num. ```APIDOC ## zrevrangebylex ### Description Return the reversed lexicographical range of values from sorted set `name` between `max` and `min`. If `start` and `num` are specified, then return a slice of the range. ### Method `zrevrangebylex` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters * **name** (*bytes* *|* *str* *|* *memoryview*) * **max** (*bytes* *|* *memoryview* *|* *str* *|* *int* *|* *float*) * **min** (*bytes* *|* *memoryview* *|* *str* *|* *int* *|* *float*) * **start** (*int* *|* *None*) - Optional * **num** (*int* *|* *None*) - Optional ### Return type: list[str | bytes] | *Awaitable*[list[str | bytes]] ``` -------------------------------- ### zrevrangebylex Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Return the reversed lexicographical range of values from a sorted set. Supports slicing with start and num. ```APIDOC ## zrevrangebylex ### Description Return the reversed lexicographical range of values from sorted set `name` between `max` and `min`. If `start` and `num` are specified, then return a slice of the range. ### Method N/A (Python method) ### Endpoint N/A (Python method) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters * **name** (*bytes* *|* *str* *|* *memoryview*) * **max** (*bytes* *|* *memoryview* *|* *str* *|* *int* *|* *float*) * **min** (*bytes* *|* *memoryview* *|* *str* *|* *int* *|* *float*) * **start** (*int* *|* *None*) * **num** (*int* *|* *None*) ### Return type: list[str | bytes] | *Awaitable*[list[str | bytes]] ``` -------------------------------- ### Connect to Valkey via SSL Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/ssl_connection_examples.ipynb Use this snippet to establish a basic SSL connection to a Valkey instance. Ensure SSL is enabled and certificate requirements are set appropriately. ```python import valkey r = valkey.Valkey( host="localhost", port=6666, ssl=True, ssl_cert_reqs="none", ) r.ping() ``` -------------------------------- ### Create and Activate Virtual Environment Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/opentelemetry/README.md Optionally, create and activate a Python virtual environment for project dependencies. ```shell python3 -m venv .venv source .venv/bin/active ``` -------------------------------- ### sync Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Initiates a replication stream from the master. This command is used to start the synchronization process with a primary server. ```APIDOC ## sync() ### Description Initiates a replication stream from the master. ### Return type: bytes | Awaitable[bytes] ``` -------------------------------- ### Connect to Default Valkey Instance Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/connection_examples.ipynb Connects to a Valkey instance using default settings, typically running on localhost:6379. Pings the server to verify the connection. ```python import valkey connection = valkey.Valkey() connection.ping() ``` -------------------------------- ### substr Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Retrieves a portion of a string value from a specified key. The substring is defined by start and end indices. ```APIDOC ## substr(name, start, end=-1) ### Description Return a substring of the string at key `name`. `start` and `end` are 0-based integers specifying the portion of the string to return. ### Parameters * **name** (bytes | str | memoryview) * **start** (int) * **end** (int) ### Return type str | bytes | *Awaitable*[str | bytes] ``` -------------------------------- ### Enable RESP3 Protocol Source: https://github.com/valkey-io/valkey-py/blob/main/README.md Connect to Valkey using the RESP3 protocol by setting protocol=3 during client initialization. ```python import valkey r = valkey.Valkey(host='localhost', port=6379, db=0, protocol=3) ``` -------------------------------- ### acl_log Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Get ACL logs as a list. Optionally specify a count to retrieve a specific number of recent logs. ```APIDOC ## acl_log ### Description Get ACL logs as a list. Optionally specify a count to retrieve a specific number of recent logs. ### Method APIDOC ### Endpoint APIDOC ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Parameters #### Path Parameters - **count** (int | None) - Optional - The number of logs to retrieve. ### Request Example N/A ### Response #### Success Response (200) - **list[dict[str, str | float | dict[str, str | int]]]** - A list of ACL log entries. #### Response Example N/A ``` -------------------------------- ### Connect to Valkey on Custom Host and Port Source: https://github.com/valkey-io/valkey-py/blob/main/docs/index.md Connect to a Valkey server running on a specified host and port. Pings the server to verify the connection. ```python import valkey r = valkey.Valkey(host='foo.bar.com', port=12345) r.ping() ``` -------------------------------- ### getrange Source: https://github.com/valkey-io/valkey-py/blob/main/docs/commands.md Returns the substring of the string value stored at a given key, determined by the inclusive start and end offsets. ```APIDOC ## getrange(key, start, end) ### Description Returns the substring of the string value stored at `key`, determined by the offsets `start` and `end` (both are inclusive) For more information see [https://valkey.io/commands/getrange](https://valkey.io/commands/getrange) ### Parameters * **key** (bytes | str | memoryview) * **start** (int) * **end** (int) ### Return type str | bytes | Awaitable[str | bytes] ``` -------------------------------- ### Initialize Vector Dimensions and Create Index Source: https://github.com/valkey-io/valkey-py/blob/main/docs/examples/search_vector_similarity_examples.ipynb Sets the vector dimensions and calls the function to create the Valkey index. This example assumes a vector dimension of 1536. ```python # define vector dimensions VECTOR_DIMENSIONS = 1536 # create the index create_index(vector_dimensions=VECTOR_DIMENSIONS) ```