### Connect to a Redis Cluster Source: https://github.com/alisaifee/coredis/blob/master/docs/source/index.rst Initialize a RedisCluster client by providing a list of startup nodes. This example shows the basic setup for connecting to a cluster. ```python import anyio import coredis async def main() -> None: client = coredis.RedisCluster( startup_nodes=[ ``` -------------------------------- ### Install Coredis with Recipes Source: https://github.com/alisaifee/coredis/blob/master/README.md Install coredis with dependencies required for recipes. ```console pip install "coredis[recipes]" ``` -------------------------------- ### Install Coredis with Recipe Dependencies Source: https://github.com/alisaifee/coredis/blob/master/docs/source/recipes/index.rst Use this command to install coredis along with all optional dependencies required by the recipes. ```bash pip install coredis[recipes] ``` -------------------------------- ### Install Coredis Source: https://github.com/alisaifee/coredis/blob/master/README.md Install the coredis library using pip. ```console pip install coredis ``` -------------------------------- ### RediSearch Create Index Example Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/modules.rst Provides an example of how to create a RediSearch index using the `coredis.modules.search.Field` class. This is a foundational step for using RediSearch's search and aggregation capabilities. ```python from coredis.modules.search import Field # Example schema definition (actual index creation not shown) # schema = [ # Field("title", as_name="title"), # Field("body", as_name="body"), # Field("tags", as_name="tags",) # ] # await client.search.create("my_index", schema) ``` -------------------------------- ### Install Coredis with OpenTelemetry Source: https://github.com/alisaifee/coredis/blob/master/README.md Install coredis with optional OpenTelemetry support. ```console pip install "coredis[otel]" ``` -------------------------------- ### Initialize Redis Client with LRUCache Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/caching.rst Demonstrates how to initialize a Redis client with an LRUCache instance for caching responses. This example also shows how to use it in a cluster mode. ```python import asyncio import coredis from coredis.patterns.cache import LRUCache cached_client = coredis.Redis(cache=LRUCache()) regular_client = coredis.Redis() # or in cluster mode # cached_client = coredis.RedisCluster("localhost", 7000, cache=LRUCache()) # regular_client = coredis.RedisCluster("localhost", 7000) ``` -------------------------------- ### Configure and Execute Coredis with OpenTelemetry Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/observability.rst Example demonstrating how to enable OpenTelemetry instrumentation, configure in-memory exporters for traces and metrics, and execute Redis commands to inspect emitted telemetry. ```python import anyio import coredis from opentelemetry import metrics, trace from opentelemetry.sdk.metrics import MeterProvider from opentelemetry.sdk.metrics.export import InMemoryMetricReader from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import SimpleSpanProcessor from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter async def main() -> None: coredis.Config.otel_enabled = True coredis.Config.otel_capture_command_args = True span_exporter = InMemorySpanExporter() tracer_provider = TracerProvider() tracer_provider.add_span_processor(SimpleSpanProcessor(span_exporter)) trace.set_tracer_provider(tracer_provider) metric_reader = InMemoryMetricReader() metrics.set_meter_provider(MeterProvider(metric_readers=[metric_reader])) client = coredis.Redis(host="127.0.0.1", port=6379) async with client: await client.set("example:key", "value") await client.get("example:key") spans = span_exporter.get_finished_spans() metric_data = metric_reader.get_metrics_data() print(f"spans={len(spans)} metric_resources={len(metric_data.resource_metrics)}") anyio.run(main) ``` -------------------------------- ### Create a Simple Stream Consumer Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/streams.rst Instantiate a simple consumer to read from one or more streams. It defaults to starting from the latest entry. ```python consumer = client.xconsumer(streams=["one", "two", "three"]) # or directly # import coredis.patterns.streams # consumer = coredis.patterns.streams.Consumer(client, streams=["one", "two", "three"]) ``` -------------------------------- ### Coredis Pub/Sub Subscription (5.x) Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/migration_guide.rst Example of subscribing to a channel using Coredis Pub/Sub in version 5.x. PubSub classes must be used as async context managers. ```python import asyncio import coredis async def main(): client = coredis.Redis() pubsub = client.pubsub() await pubsub.subscribe("channel") async for message in pubsub: print(message) asyncio.run(main()) ``` -------------------------------- ### Enable Coredis Runtime Type Checks with Beartype Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/typing.rst Shows how to enable runtime type checking in Coredis by setting the COREDIS_RUNTIME_CHECKS environment variable to 1 and installing beartype. This example demonstrates a type violation when passing an integer to the 'set' command's key parameter. ```bash $ COREDIS_RUNTIME_CHECKS=1 python -c " import coredis import asyncio async def test(): async with coredis.Redis() as client: await client.set(1,1) asyncio.run(test()) " Traceback (most recent call last): File "<@beartype(coredis.commands.core.CoreCommands.set) at 0x10c403130>", line 33, in set beartype.roar.BeartypeCallHintParamViolation: @beartyped coroutine CoreCommands.set() parameter key=1 violates type hint typing.Union[str, bytes], as 1 not str or bytes. ``` -------------------------------- ### Consume from Backlog with Coredis Consumer Group Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/streams.rst Use `start_from_backlog=True` to process old entries before new ones. This example simulates processing with a 50% failure rate and then restarts without the bug. ```python import random async with client: async with client.xconsumer( streams=["one"], group = "group-a", consumer = "consumer-1", start_from_backlog = True ) as consumer: [await client.xadd("one", {"id": i}) for i in range(10)] # fetch all ten entries and simulate a bug occurring 50% of the time # when processing the entry async for stream, entry in consumer: if random.random() > 0.5: print("success", await client.xack(stream, consumer.group, [entry.identifier])) else: print("oh nos!") pending = await client.xpending("one", "group-a") assert pending.consumers[b"consumer-1"] > 0 print("round two") # Let's pretend the consumer crashed and started again # and now doesn't have a bug that fails 50% of the time async with client.xconsumer( streams=["one"], group = "group-a", consumer = "consumer-1", start_from_backlog = True ) as consumer: async for stream, entry in consumer: await client.xack(stream, consumer.group, [entry.identifier]) pending = await client.xpending("one", "group-a") assert pending.consumers.get(b"consumer-1") is None ``` -------------------------------- ### Coredis Scripting with Wraps (5.x) Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/migration_guide.rst Example of registering and using a Lua script with the 'wraps' decorator in Coredis version 5.x. Key arguments must be annotated with KeyT. ```python import asyncio import coredis async def main(): client = coredis.Redis() @client.register_script("return {KEYS[1], ARGV[1]}").wraps(key_spec=["key"]) async def echo_key_value(key: str, value: str) -> list[bytes]: ... k, v = await echo_key_value("co", "redis") print(f"{k!r}={v!r}") asyncio.run(main()) ``` -------------------------------- ### Pub/Sub Channel and Subscription Info Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/pubsub.rst Get information about subscribed channels and the number of subscribers for specific channels or all patterns. ```python await client.pubsub_channels() # ['foo', 'bar'] ``` ```python await client.pubsub_numsub('foo', 'bar') # [('foo', 9001), ('bar', 42)] ``` ```python await client.pubsub_numsub('baz') # [('baz', 0)] ``` ```python await client.pubsub_numpat() # 1204 ``` -------------------------------- ### Use a Python-Wrapped Library Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/scripting.rst Instantiate a Python class that wraps a Lua library and use its methods. This example demonstrates using the library with a client and includes setting data and calling a complex function. ```python client = coredis.Redis() async with client: lib = await MyLib(client, replace=True) await lib.ping() # b"pong" await lib.echo("hello world") # b"hello world" await client.hset("k1", {"a": 10, "b": 20}) await client.hset("k2", {"c": 30, "d": 40}) await lib.hmmget("k1", "k2", a=1, b=2, c=3, d=4, e=5, f=6) # [b"10", b"20", b"30", b"40", b"5", b"6"] ``` -------------------------------- ### Add Entries to Streams Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/streams.rst Add multiple entries to specified streams using `xadd`. This example adds 10 entries to each of the 'one', 'two', and 'three' streams. ```python async with client: [await client.xadd("one", {"id": i}) for i in range(10)] [await client.xadd("two", {"id": i}) for i in range(10)] [await client.xadd("three", {"id": i}) for i in range(10)] ``` -------------------------------- ### Coredis Sentinel Usage (6.0) Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/migration_guide.rst Example of using Coredis Sentinel in version 6.0. Sentinel instances must be used as async context managers. ```python import anyio import coredis async def main(): sentinel = coredis.Sentinel(sentinels=[("localhost", 26379)]) async with sentinel: primary = sentinel.primary_for("svc") replica = sentinel.replica_for("svc") async with primary, replica: await primary.set("fubar", 1) await replica.get("fubar") anyio.run(main) ``` -------------------------------- ### Coredis Pub/Sub Subscription (6.0) Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/migration_guide.rst Example of subscribing to a channel using Coredis Pub/Sub in version 6.0. PubSub classes must be used as async context managers and the client must be used as an async context manager. ```python import anyio import coredis async def main(): client = coredis.Redis() async with client: async with client.pubsub() as pubsub: await pubsub.subscribe("channel") async for message in pubsub: print(message) anyio.run(main) ``` -------------------------------- ### Coredis Stream Consumer (5.x) Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/migration_guide.rst Example of using a stream consumer in Coredis version 5.x. Stream consumer instances must be async context managers. ```python import asyncio import coredis from coredis.stream import Consumer async def main(): client = coredis.Redis() consumer = await Consumer(client, streams=["one", "two"]) stream, entry = await consumer.get_entry() asyncio.run(main()) ``` -------------------------------- ### Client-Side Caching with TrackingCache (5.x) Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/migration_guide.rst Demonstrates using `TrackingCache` for client-side caching with a specified maximum size in bytes. It shows setting, getting, and retrieving cached values, and printing cache statistics. ```python import asyncio import coredis from coredis.cache import TrackingCache async def main(): cache=TrackingCache(max_size_bytes=128 * 1024 * 1024) client = coredis.Redis(cache=cache) await client.set("fubar", 1) await client.get("fubar") await client.get("fubar") print(cache.stats) asyncio.run(main()) ``` -------------------------------- ### Coredis Scripting with Wraps (6.0) Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/migration_guide.rst Example of registering and using a Lua script with the 'wraps' decorator in Coredis version 6.0. Key arguments must be annotated with KeyT and the client must be used as an async context manager. ```python import asyncio import coredis from coredis.typing import KeyT from coredis.commands import CommandRequest async def main(): client = coredis.Redis() @client.register_script("return {KEYS[1], ARGV[1]}").wraps() def echo_key_value(key: KeyT, value: str) -> CommandRequest[list[bytes]]: ... async with client: k, v = await echo_key_value("co", "redis") print(f"{k!r}={v!r}") asyncio.run(main()) ``` -------------------------------- ### Client-Side Caching with LRUCache (6.0) Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/migration_guide.rst Demonstrates using `LRUCache` for client-side caching with a specified maximum number of keys. It shows setting, getting, and retrieving cached values within an async context manager, and printing cache statistics. ```python import anyio import coredis from coredis.patterns.cache import LRUCache async def main(): cache=LRUCache(max_keys=10000) client = coredis.Redis(cache=cache) async with client: await client.set("fubar", 1) await client.get("fubar") await client.get("fubar") print(cache.stats) anyio.run(main) ``` -------------------------------- ### Create and Use Bloom Filter Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/modules.rst Demonstrates creating a Bloom filter, adding items individually and in batches, and checking for their existence. Also shows how to use the BloomFilter class directly. ```python import coredis client = coredis.Redis() async with client: # create filter await client.bf.reserve("filter", 0.1, 1000) # add items await client.bf.add("filter", 1) await client.bf.madd("filter", [2,3,4]) # test for inclusion assert await client.bf.exists("filter", 1) assert (True, False) == await client.bf.mexists("filter", [2,5]) # or assert await coredis.modules.BloomFilter(client).exists("filter", 1) ``` -------------------------------- ### Coredis Sentinel Usage Source: https://github.com/alisaifee/coredis/blob/master/README.md Connect to Redis via Sentinel to get primary and replica clients for a given service. Requires `anyio` and `coredis` to be installed. ```python import anyio import coredis async def main() -> None: sentinel = coredis.Sentinel(sentinels=[("localhost", 26379)]) async with sentinel: primary: coredis.Redis = sentinel.primary_for("myservice") replica: coredis.Redis = sentinel.replica_for("myservice") async with primary, replica: assert await primary.set("fubar", 1) assert int(await replica.get("fubar")) == 1 anyio.run(main, backend="asyncio") # or trio ``` -------------------------------- ### RedisJSON Set and Get Operations Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/modules.rst Illustrates basic RedisJSON operations for setting and retrieving JSON documents. Uses the standard Python json module for serialization by default, or orjson if installed. ```python import coredis client = coredis.Redis() async with client: await client.json.set( "key1", ".", {"a": 1, "b": [1, 2, 3], "c": "str"} ) assert 1 == await client.json.get("key1", ".a") assert [1,2,3] == await client.json.get("key1", ".b") assert "str" == await client.json.get("key1", ".c") await client.json.set("key2", ".", {"a": 2, "b": [4,5,6], "c": ["str"]}) # multi get assert ["str", ["str"]] == await client.json.mget(["key1", "key2"], ".c") ``` -------------------------------- ### Coredis Basic Usage (Single Node/Cluster) Source: https://github.com/alisaifee/coredis/blob/master/README.md Connect to a single Redis node or cluster, perform basic operations like SET, GET, INCR, EXPIRE, and use pipelines. Requires `anyio` and `coredis` to be installed. ```python import anyio import coredis async def main() -> None: client = coredis.Redis(host='127.0.0.1', port=6379, db=0, decode_responses=True) # or cluster # client = coredis.RedisCluster(startup_nodes=[coredis.connection.TCPLocation("127.0.0.1", 6379)], decode_responses=True) async with client: await client.flushdb() await client.set("foo", 1) assert await client.exists(["foo"]) == 1 assert await client.incr("foo") == 2 assert await client.expire("foo", 1) await anyio.sleep(0.1) assert await client.ttl("foo") == 1 await anyio.sleep(1) assert not await client.exists(["foo"]) async with client.pipeline() as pipeline: pipeline.incr("foo") value = pipeline.get("foo") pipeline.delete(["foo"]) assert await value == "1" anyio.run(main, backend="asyncio") # or trio ``` -------------------------------- ### Instantiating Module Command Groups Directly Source: https://github.com/alisaifee/coredis/blob/master/docs/source/api/modules.rst Shows how to instantiate module command group classes directly and bind them to a client. ```APIDOC ## Instantiating Module Command Groups Directly ### Description Module command groups can also be instantiated directly by passing a client instance to their constructor. This provides an alternative way to access module commands. ### Example ```python import coredis import coredis.modules client = coredis.Redis() # Instantiating Json command group directly json_module = coredis.modules.Json(client) await json_module.get("mykey", "$") # Instantiating BloomFilter command group directly bloom_filter = coredis.modules.BloomFilter(client) await bloom_filter.add("mybloom", "item") ``` ``` -------------------------------- ### Configure Consumer with Internal Buffer Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/streams.rst Set up a consumer with a buffer size to pre-fetch entries and a timeout for blocking operations. ```python consumer = client.xconsumer( client, streams=["one", "two", "three"], # Will fetch upto 10 extra entries per stream # on every request to redis buffer_size=10, timeout=30*1000 # 30 seconds ) ``` -------------------------------- ### Subscribe to Channels and Patterns on Instantiation Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/pubsub.rst Instantiate a Pub/Sub consumer and subscribe to specific channels and patterns simultaneously. The async context manager handles subscription and cleanup. ```python async with client.pubsub( channels=["my-first-channel", "my-second-channel"], patterns=["my-*"] ) as consumer: ... ``` -------------------------------- ### Coredis Span Examples Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/observability.rst Examples of span names emitted by Coredis for different operations. These are used for tracing command executions, pipelines, and transactions. ```text SET GET ``` ```text SET key1 ? GET key1 ``` -------------------------------- ### Initialize and Use Count-Min Sketch Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/modules.rst Illustrates initializing a Count-Min Sketch with dimensions, incrementing counts for multiple entries, and querying counts for entries. ```python # create a sketch await client.cms.initbydim("sketch", 2, 50) # increment the counts for multiple entries assert (1, 2) == await client.cms.incrby("sketch", {"a": 1, "b": 2}) # query the count for multiple entries assert (1, 2, 0) == await client.cms.query("sketch", ["a", "b", "c"]) ``` -------------------------------- ### Initialize Coredis Client Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/streams.rst Import and initialize a Coredis client for regular or cluster connections. ```python import coredis client = coredis.Redis() # or cluster # client = coredis.RedisCluster("localhost", 7000) ``` -------------------------------- ### GET Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Returns the string value of a key. ```APIDOC ## GET ### Description Returns the string value of a key. ### Method Coredis implementation: :meth:`~coredis.Redis.get` ### Documentation `GET `_ ### Client Caching Supports client caching: yes ``` -------------------------------- ### SLOWLOG GET Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Returns the slow log's entries. ```APIDOC ## SLOWLOG GET ### Description Returns the slow log's entries. ### Method [Method not specified in source] ### Endpoint [Endpoint not specified in source] ### Implementation [Implementation not specified in source] ``` -------------------------------- ### Get Message with Handler Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/pubsub.rst Retrieve a message and process it with a handler. The message variable will be None if a handler successfully processed it. ```python await message = consumer.get_message() # 'MY HANDLER: awesome data' # note here that the my_handler callback printed the string above. # `message` is None because the message was handled by our handler. print(message) # None ``` -------------------------------- ### Manage Connections with Blocking Pool (5.x) Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/migration_guide.rst Demonstrates creating a blocking connection pool with a maximum of 2 connections and executing commands that might block. ```python import coredis import asyncio from coredis import ConnectionPool, BlockingConnectionPool async def main(): # Blocking pool client = coredis.Redis(connection_pool=BlockingConnectionPool(max_connections=2)) await asyncio.gather(*(client.blpop(["fubar"], timeout=1) for _ in range(3))) ``` -------------------------------- ### Query Latest Temperature in Each Room with Coredis TimeSeries Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/modules.rst Retrieves the most recent temperature reading for each specified room using the 'get' method. ```python for room in rooms: print(await client.timeseries.get(f"temp:{room}")) ``` -------------------------------- ### Implementing a Custom Cache Source: https://github.com/alisaifee/coredis/blob/master/docs/source/api/caching.rst Guidelines for creating your own cache implementations. ```APIDOC ## Implementing a Custom Cache ### Description To create a custom cache compatible with `coredis.Redis` or `coredis.RedisCluster`, you must implement the `AbstractCache` interface. ### Abstract Cache Interface `coredis.patterns.cache.AbstractCache` ### Cache Statistics `coredis.patterns.cache.CacheStats` ``` -------------------------------- ### Manage Connections with Blocking Pool and Timeout (6.0) Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/migration_guide.rst Demonstrates creating a connection pool with a maximum of 2 connections and a timeout, using async context managers, and handling `TimeoutError` when the timeout is exceeded. ```python import coredis import asyncio async def main(): async with coredis.Redis( connection_pool=coredis.pool.ConnectionPool(max_connections=2, timeout=1) ) as client: try: print(await asyncio.gather(*(client.blpop(["fubar"], timeout=5) for _ in range(3)))) except TimeoutError: # Note that a `TimeoutError` is raised instead of `ConnectionError` print("Failed with timeout") asyncio.run(main()) ``` -------------------------------- ### VRANGE Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Return elements in a lexicographical range. This command is available starting from Redis version 8.4.0 and was added in Coredis version 6.0.0. ```APIDOC ## VRANGE ### Description Returns elements that fall within a specified lexicographical range. ### Method Not specified (assumed to be a method call in the Coredis library). ### Endpoint Not applicable (this is a library method). ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### VGETATTR Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Retrieve the JSON attributes of elements. This command is available starting from Redis version 8.0.0 and was added in Coredis version 5.0.0. ```APIDOC ## VGETATTR ### Description Retrieves the JSON attributes associated with elements. ### Method Not specified (assumed to be a method call in the Coredis library). ### Endpoint Not applicable (this is a library method). ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### VINFO Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Return information about a vector set. This command is available starting from Redis version 8.0.0 and was added in Coredis version 5.0.0. ```APIDOC ## VINFO ### Description Retrieves detailed information about a specified vector set. ### Method Not specified (assumed to be a method call in the Coredis library). ### Endpoint Not applicable (this is a library method). ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### Create and Use TopK Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/modules.rst Demonstrates reserving space for a TopK structure, adding a large number of entries, and retrieving the top 3 most frequent items. ```python import string import itertools import random # create a top-3 await client.topk.reserve("top3", 3) # add entries letters = list(itertools.chain(*[k[0]*k[1] for k in list(enumerate(string.ascii_lowercase))])) random.shuffle(letters) await client.topk.add("top3", letters) # get top 3 letters assert (b'z', b'y', b'x') == await client.topk.list("top3") ``` -------------------------------- ### VEMB Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Return the vector associated with an element. This command is available starting from Redis version 8.0.0 and was added in Coredis version 5.0.0. ```APIDOC ## VEMB ### Description Retrieves the vector data associated with a specific element. ### Method Not specified (assumed to be a method call in the Coredis library). ### Endpoint Not applicable (this is a library method). ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### VSIM Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Return elements by vector similarity. This command is available starting from Redis version 8.0.0 and was added in Coredis version 5.0.0. ```APIDOC ## VSIM ### Description Returns elements based on vector similarity. ### Method Not specified (assumed to be a method call in the Coredis library). ### Endpoint Not applicable (this is a library method). ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### Create and Use Cuckoo Filter Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/modules.rst Shows how to create a Cuckoo filter, add items, check for existence, count items, and delete items. Demonstrates the addnx command for adding only if not present. ```python # create filter await client.cf.reserve("filter", 1000) # add items assert await client.cf.add("filter", 1) assert not await client.cf.addnx("filter", 1) # test for inclusion assert await client.cf.exists("filter", 1) assert 1 == await client.cf.count("filter", 1) # delete an item assert await client.cf.delete("filter", 1) # test for inclusion assert not await client.cf.exists("filter", 1) assert 0 == await client.cf.count("filter", 1) ``` -------------------------------- ### Perform Geo Filtered Search Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/modules.rst Conduct a search with geographical filtering. This example finds documents within a specified radius of a given coordinate. ```python results = await client.search.search( "json_index", "*", geo_filters={"location": ((67.0011, 24.8607), 1, coredis.PureToken.KM)}, returns={"name": None}, ) assert results.total == 1 assert results.documents[0].properties["name"] == "karachi" ``` -------------------------------- ### ACL GETUSER Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Lists the ACL rules of a user. This command is available starting from Redis version 6.0.0 and was added in Coredis version 3.0.0. ```APIDOC ## ACL GETUSER ### Description Retrieves and lists the Access Control List (ACL) rules associated with a specific user. ### Method Not specified (assumed to be a method call in the Coredis library). ### Endpoint Not applicable (this is a library method). ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### Initialize and Cleanup Redis Client (6.0) Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/migration_guide.rst Version 6.0 mandates the use of async context managers for Redis clients, ensuring proper initialization and automatic cleanup of resources. ```python import anyio import coredis async def main(): client = coredis.Redis(host="127.0.0.1", port=6379) async with client: await client.set("key", "1") # Client and connection pool are automatically cleaned up anyio.run(main, backend="asyncio") # or "trio" ``` -------------------------------- ### VISMEMBER Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Check if an element exists in a vector set. This command is available starting from Redis version 8.2.0 and was added in Coredis version 5.2.0. ```APIDOC ## ISMEMB ### Description Checks for the existence of an element within a vector set. ### Method Not specified (assumed to be a method call in the Coredis library). ### Endpoint Not applicable (this is a library method). ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### Create Redis Client with Max Connections Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/connections.rst Demonstrates creating a Redis client with a specified maximum number of connections and handling concurrent blocking requests that exceed this limit. The command will block until a connection is available. ```python import asyncio import coredis async def test(): client = coredis.Redis(max_connections=8) # or with cluster # client = coredis.RedisCluster( # "localhost", 7000, # max_connections=8, max_connections_per_node=True # ) async with client: results = await asyncio.gather( *[client.blpop(["fubar"], 3) for _ in range(10)], ) asyncio.run(test()) ``` -------------------------------- ### VSETATTR Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Associate or remove the JSON attributes of elements. This command is available starting from Redis version 8.0.0 and was added in Coredis version 5.0.0. ```APIDOC ## VSETATTR ### Description Associates or removes JSON attributes for elements within a vector set. ### Method Not specified (assumed to be a method call in the Coredis library). ### Endpoint Not applicable (this is a library method). ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### VCARD Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Return the number of elements in a vector set. This command is available starting from Redis version 8.0.0 and was added in Coredis version 5.0.0. ```APIDOC ## VCARD ### Description Returns the count of elements present in a vector set. ### Method Not specified (assumed to be a method call in the Coredis library). ### Endpoint Not applicable (this is a library method). ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### Manage Connections with Blocking Pool and Timeout (5.x) Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/migration_guide.rst Demonstrates creating a blocking connection pool with a maximum of 2 connections and a timeout, and handling connection errors when the timeout is exceeded. ```python import coredis import asyncio from coredis import ConnectionPool, BlockingConnectionPool async def main(): # Blocking pool with timeout client = coredis.Redis(connection_pool=BlockingConnectionPool(max_connections=2, timeout=1)) try: await asyncio.gather(*(client.blpop(["fubar"], timeout=5) for _ in range(3))) except coredis.exceptions.ConnectionError as err: print("Failed with timeout") asyncio.run(main()) ``` -------------------------------- ### VDIM Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Return the dimension of vectors in the vector set. This command is available starting from Redis version 8.0.0 and was added in Coredis version 5.0.0. ```APIDOC ## VDIM ### Description Returns the dimension of vectors within a vector set. ### Method Not specified (assumed to be a method call in the Coredis library). ### Endpoint Not applicable (this is a library method). ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### Create TimeSeries Compaction Rules Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/modules.rst Shows how to create compaction rules for hourly and daily averages for time series, specifying the aggregation type and time interval. ```python for room in rooms: assert await client.timeseries.create( f"temp:{room}:hourly:avg", labels={"room": room, "compaction": "hourly"} ) assert await client.timeseries.create( f"temp:{room}:daily:avg", labels={"room": room, "compaction": "daily"} ) assert await client.timeseries.createrule( f"temp:{room}", f"temp:{room}:hourly:avg", coredis.PureToken.AVG, timedelta(hours=1) ) assert await client.timeseries.createrule( f"temp:{room}", f"temp:{room}:daily:avg", coredis.PureToken.AVG, timedelta(days=1) ) ``` -------------------------------- ### ACL LOAD Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Reloads the rules from the configured ACL file. This command is available starting from Redis version 6.0.0 and was added in Coredis version 3.0.0. ```APIDOC ## ACL LOAD ### Description Reloads the Access Control List (ACL) rules from the designated configuration file. ### Method Not specified (assumed to be a method call in the Coredis library). ### Endpoint Not applicable (this is a library method). ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### Create TimeSeries with Labels Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/modules.rst Demonstrates creating multiple time series, each with a unique label indicating the room, using the coredis client. ```python import coredis from datetime import datetime, timedelta rooms = {"bedroom", "lounge", "bathroom"} client = coredis.Redis(port=9379) async with client: for room in rooms: assert await client.timeseries.create(f"temp:{room}", labels={"room": room}) ``` -------------------------------- ### SELECT Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Changes the selected database on the Redis server. It's recommended to use the `db` argument during client initialization for managing database selection consistently. ```APIDOC ## SELECT ### Description Changes the selected database. ### Method POST ### Endpoint /select ### Documentation https://redis.io/commands/select ### Implementation coredis.Redis.select ### Warning Using :meth:`~coredis.Redis.select` directly is not recommended. Use the `db` argument when initializing the client to ensure that all connections originating from this client use the desired database number. ``` -------------------------------- ### ACL DELUSER Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Deletes ACL users, and terminates their connections. This command is available starting from Redis version 6.0.0 and was added in Coredis version 3.0.0. ```APIDOC ## ACL DELUSER ### Description Deletes specified Access Control List (ACL) users and terminates their active connections. ### Method Not specified (assumed to be a method call in the Coredis library). ### Endpoint Not applicable (this is a library method). ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### VLINKS Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Return the neighbors of an element at each layer in the HNSW graph. This command is available starting from Redis version 8.0.0 and was added in Coredis version 5.0.0. ```APIDOC ## VLINKS ### Description Returns the neighboring elements for a given element at each layer of the HNSW graph. ### Method Not specified (assumed to be a method call in the Coredis library). ### Endpoint Not applicable (this is a library method). ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### Basic Redis Operations with Coredis Source: https://github.com/alisaifee/coredis/blob/master/docs/source/index.rst Demonstrates setting, checking existence, incrementing, expiring, and deleting keys in Redis using Coredis. Includes pipeline usage for atomic operations. ```python import anyio from coredis.connection import TCPLocation from coredis import Redis async def main() -> None: client = Redis( locations=[ coredis.connection.TCPLocation("127.0.0.1", 7000) ], db=0, decode_responses=True ) async with client: await client.flushdb() await client.set("foo", 1) assert await client.exists(["foo"]) == 1 assert await client.incr("foo") == 2 assert await client.expire("foo", 1) await anyio.sleep(0.1) assert await client.ttl("foo") == 1 await anyio.sleep(1) assert not await client.exists(["foo"]) async with client.pipeline() as pipeline: pipeline.incr("foo") value = pipeline.get("foo") pipeline.delete(["foo"]) assert await value == "1" anyio.run(main, backend="asyncio") ``` -------------------------------- ### Manage Connections with Non-blocking Pool (5.x) Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/migration_guide.rst Demonstrates creating a non-blocking connection pool with a maximum of 2 connections and handling potential connection errors when attempting to exceed this limit. ```python import coredis import asyncio from coredis import ConnectionPool, BlockingConnectionPool async def main(): # Non-blocking pool client = coredis.Redis(connection_pool=ConnectionPool(max_connections=2)) try: await asyncio.gather(*(client.blpop(["fubar"], timeout=1) for _ in range(3))) except coredis.exceptions.ConnectionError as err: print("Failed with too many connections attempted") ``` -------------------------------- ### Create and Use T-Digest Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/modules.rst Shows how to create a T-Digest, add values, and retrieve data by rank, reverse rank, and quantile. ```python # create a digest await client.tdigest.create("digest") # add some values await client.tdigest.add("digest", 1, [1, 2, 3, 4]) # add some more values await client.tdigest.add("digest", 1, [1, 2, 3, 4]) # get the rank & reverse ranks assert (1.0, 1.0, 2.0) == await client.tdigest.byrank("digest", [0, 1, 2]) assert (6.0, 5.0, 4.0) == await client.tdigest.byrevrank("digest", [0, 1, 2]) # get the quantiles assert (1.0, 3.0, 6.0) == await client.tdigest.quantile("digest", [0, 0.5, 1]) ``` -------------------------------- ### Manage Connections with Non-blocking Pool (6.0) Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/migration_guide.rst Demonstrates creating a non-blocking connection pool with a maximum of 2 connections using async context managers. ```python import coredis import asyncio async def main(): async with coredis.Redis( connection_pool=coredis.pool.ConnectionPool(max_connections=2) ) as client: print(await asyncio.gather(*(client.blpop(["fubar"], timeout=1) for _ in range(3)))) asyncio.run(main()) ``` -------------------------------- ### ACL LIST Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Dumps the effective rules in ACL file format. This command is available starting from Redis version 6.0.0 and was added in Coredis version 3.0.0. ```APIDOC ## ACL LIST ### Description Dumps the currently effective Access Control List (ACL) rules in a file-compatible format. ### Method Not specified (assumed to be a method call in the Coredis library). ### Endpoint Not applicable (this is a library method). ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### Explicitly Subscribe to Channels and Patterns Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/pubsub.rst Create a Pub/Sub consumer and then explicitly subscribe to channels and patterns using the subscribe and psubscribe methods. The async context manager ensures proper cleanup. ```python async with client.pubsub() as consumer: await consumer.subscribe("my-first-channel", "my-second-channel", ...) await consumer.psubscribe("my-*") ``` -------------------------------- ### ACL CAT Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Lists the ACL categories, or the commands inside a category. This command is available starting from Redis version 6.0.0 and was added in Coredis version 3.0.0. ```APIDOC ## ACL CAT ### Description Lists Access Control List (ACL) categories or commands within a category. ### Method Not specified (assumed to be a method call in the Coredis library). ### Endpoint Not applicable (this is a library method). ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### Register and Load a Lua Library Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/scripting.rst Register a Lua script with a given name and then load it. If a library with the same name exists, this will raise an exception unless 'replace' is set to True. ```python client = coredis.Redis() library = await client.register_library("mylib", open("/var/tmp/library.lua").read()) ``` ```python library = await client.load_library("mylib") ``` -------------------------------- ### VRANDMEMBER Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Return one or multiple random members from a vector set. This command is available starting from Redis version 8.0.0 and was added in Coredis version 5.0.0. ```APIDOC ## VRANDMEMBER ### Description Returns one or multiple random members from a specified vector set. ### Method Not specified (assumed to be a method call in the Coredis library). ### Endpoint Not applicable (this is a library method). ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### Lua Library Definition Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/scripting.rst Defines a Lua library named 'mylib' with several functions: 'echo', 'ping', 'get', and 'hmmget'. This library can be registered with coredis for server-side execution. ```lua #!lua name=mylib redis.register_function('echo', function(k, a) return a[1] end) redis.register_function('ping', function() return "PONG" end) redis.register_function('get', function(k, a) return redis.call("GET", k[1]) end) redis.register_function('hmmget', function(k, a) local values = {} local fields = {} local response = {} local i = 1 local j = 1 while a[i] do fields[j] = a[i] i = i + 2 j = j + 1 end for idx, key in ipairs(k) do values = redis.call("HMGET", key, unpack(fields)) for idx, value in ipairs(values) do if not response[idx] and value then response[idx] = value end end end for idx, value in ipairs(fields) do if not response[idx] then response[idx] = a[idx*2] end end return response end) ``` -------------------------------- ### ACL SAVE Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Saves the effective ACL rules in the configured ACL file. This command is available starting from Redis version 6.0.0 and was added in Coredis version 3.0.0. ```APIDOC ## ACL SAVE ### Description Saves the currently effective Access Control List (ACL) rules to the designated configuration file. ### Method Not specified (assumed to be a method call in the Coredis library). ### Endpoint Not applicable (this is a library method). ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ``` -------------------------------- ### Initialize Pipeline with Transaction Enabled Source: https://github.com/alisaifee/coredis/blob/master/docs/source/handbook/pipelines.rst Create a pipeline instance with `transaction=True` to enable atomic execution of buffered commands. ```python pipe = r.pipeline(transaction=True) ``` -------------------------------- ### ACL DRYRUN Source: https://github.com/alisaifee/coredis/blob/master/docs/source/compatibility.rst Simulates the execution of a command by a user, without executing the command. This command is available starting from Redis version 7.0.0 and was added in Coredis version 3.0.0. ```APIDOC ## ACL DRYRUN ### Description Simulates the execution of a command by a user without actually performing the command. ### Method Not specified (assumed to be a method call in the Coredis library). ### Endpoint Not applicable (this is a library method). ### Parameters Not specified in the source text. ### Request Example Not specified in the source text. ### Response Not specified in the source text. ```