### Install tair-py from source Source: https://github.com/tair-opensource/tair-py/blob/main/README.zh_CN.md This process involves cloning the tair-py repository from GitHub, navigating into the project directory, and then installing it using the setup.py script. This method is useful for development or when needing the latest unreleased changes. ```shell git clone https://github.com/alibaba/tair-py.git cd tair-py python setup.py install ``` -------------------------------- ### Install tair-py using pip Source: https://github.com/tair-opensource/tair-py/blob/main/README.zh_CN.md This command installs the tair-py library and its dependencies using the pip package manager. Ensure you have pip installed and configured correctly. ```shell pip install tair ``` -------------------------------- ### Install and Connect to Tair (Python) Source: https://context7.com/tair-opensource/tair-py/llms.txt Demonstrates how to install the tair-py library using pip and establish connections to a Tair instance. It covers basic connections, authentication, connecting via URL, and SSL-secured connections. ```python # Install via pip # pip install tair from tair import Tair # Basic connection tair = Tair(host="localhost", port=6379, db=0) # Connection with authentication tair = Tair( host="localhost", port=6379, db=0, password="your_password", decode_responses=False ) # Connection from URL tair = Tair.from_url("redis://localhost:6379/0") # SSL connection tair = Tair( host="localhost", port=6380, ssl=True, ssl_cert_reqs="required", ssl_ca_certs="/path/to/ca.crt" ) ``` -------------------------------- ### TairString: Versioned Strings and Optimistic Locking (Python) Source: https://context7.com/tair-opensource/tair-py/llms.txt Illustrates the use of TairString for managing versioned string data with support for optimistic locking using CAS (Compare-and-Swap). Includes examples for setting, getting, expiring, conditional setting (NX/XX), versioned CAS, bounded counters, and manual version setting/deletion. ```python from tair import Tair, ExgetResult tair = Tair(host="localhost", port=6379, db=0) # Set a string value with version tracking tair.exset("foo", "bar") # Get value with version result = tair.exget("foo") print(result.value) # b'bar' print(result.version) # 1 # Set with expiration (10 seconds) tair.exset("key1", "value1", ex=10) # Set only if not exists (NX flag) tair.exset("key2", "value2", nx=True) # Set only if exists (XX flag) tair.exset("key2", "updated_value", xx=True) # Compare-and-swap based on version (optimistic locking) result = tair.exget("foo") cas_result = tair.excas("foo", "new_value", result.version) print(cas_result.msg) # 'OK' if successful print(cas_result.version) # incremented version # Increment with bounds (bounded counter) tair.exset("counter", "0") tair.exincrby("counter", num=1, minval=0, maxval=100) # Raises error if increment would exceed bounds # Increment float with version check tair.exincrbyfloat("price", 1.5, ver=1, ex=60) # Set version manually tair.exsetver("key", 5) # Compare-and-delete based on version tair.excad("key", version=5) ``` -------------------------------- ### Basic tair-py Usage Example Source: https://github.com/tair-opensource/tair-py/blob/main/README.zh_CN.md This Python code snippet demonstrates the basic usage of the tair-py client. It shows how to connect to a Tair instance, set a string key-value pair with an expiration, retrieve the value and its version, and handle potential exceptions. The exget method returns an ExgetResult object containing the value and version. ```python #!/usr/bin/env python from tair import Tair if __name__ == "__main__": try: t = Tair(host="localhost", port=6379, db=0) t.exset("foo", "bar") # exget return a ExgetResult object. ret = t.exget("foo") print(ret.value) # output b'bar'. print(ret.version) # output 1 except Exception as e: print(e) exit(1) ``` -------------------------------- ### JSON Document Operations with Tair Python Source: https://context7.com/tair-opensource/tair-py/llms.txt Provides examples for managing JSON documents using the Tair Python client. Operations include setting, getting, updating, appending, and deleting fields within JSON documents, as well as array manipulations and type checking. Requires the tair library and a running Tair instance. ```python from tair import Tair tair_client = Tair(host="localhost", port=6379, db=0) # Set JSON document at root path json_data = '''{ "name": "John Doe", "age": 30, "email": "john@example.com", "address": { "city": "New York", "zip": "10001" }, "tags": ["developer", "python"], "active": true }''' tair_client.json_set("user:1000", ".", json_data) # Set nested value tair_client.json_set("user:1000", ".address.country", '"USA"', nx=True) # Get entire document doc = tair_client.json_get("user:1000", ".").decode() print(doc) # Get specific field name = tair_client.json_get("user:1000", ".name").decode() print(name) # "John Doe" # Get nested field city = tair_client.json_get("user:1000", ".address.city").decode() print(city) # "New York" # Get with formatting options formatted = tair_client.json_get("user:1000", ".", format="JSON", rootname="user", arrname="items") # Get type of field field_type = tair_client.json_type("user:1000", ".age") print(field_type) # b'number' # Increment numeric field new_age = tair_client.json_numincrby("user:1000", ".age", 1) print(new_age) # b'31' # Decrement tair_client.json_numincrby("user:1000", ".age", -1) # Append to string tair_client.json_strappend("user:1000", ".name", '" Jr."') # Get string length strlen = tair_client.json_strlen("user:1000", ".name") # Append to array tair_client.json_arrappend("user:1000", ".tags", ['"javascript"', '"nodejs"']) # Get array length arrlen = tair_client.json_arrlen("user:1000", ".tags") print(f"Tags count: {arrlen}") # Pop from array (last element by default) popped = tair_client.json_arrpop("user:1000", ".tags") print(popped) # Pop specific index popped = tair_client.json_arrpop("user:1000", ".tags", index=0) # Insert into array at index tair_client.json_arrinsert("user:1000", ".tags", ['"react"'], index=1) # Trim array tair_client.json_arrtrim("user:1000", ".tags", start=0, stop=2) # Delete field deleted = tair_client.json_del("user:1000", ".address.zip") print(f"Fields deleted: {deleted}") # Complete example: user profile management profile = '''{ "username": "alice", "stats": {"views": 0, "likes": 0}, "posts": [] }''' tair_client.json_set("profile:alice", ".", profile) tair_client.json_numincrby("profile:alice", ".stats.views", 1) tair_client.json_arrappend("profile:alice", ".posts", ['"post_123"']) ``` -------------------------------- ### TairZset: Multi-Dimensional Sorted Sets (Python) Source: https://context7.com/tair-opensource/tair-py/llms.txt Provides an introduction to TairZset, which enables the creation of sorted sets where elements can be ordered based on multiple dimensions using compound scores. The example shows basic instantiation of the Tair client. ```python from tair import Tair, TairZsetItem tair = Tair(host="localhost", port=6379, db=0) ``` -------------------------------- ### Bitmap Operations with Tair Python Source: https://context7.com/tair-opensource/tair-py/llms.txt Demonstrates various bitmap operations supported by the Tair Python client. These include counting set bits, optimizing compression, scanning bits, retrieving ranges, finding min/max set bits, calculating Jaccard similarity, checking containment, and getting bit ranks. No external dependencies are strictly required beyond the tair library itself. ```python import tair tair_client = tair.Tair(host="localhost", port=6379, db=0) # Count result of operation without storing count = tair_client.tr_bitopcard("OR", ["user:active:2024-01-15", "user:active:2024-01-16"]) print(f"Users active on either day: {count}") # Optimize bitmap compression tair_client.tr_optimize("user:active:2024-01-15") # Scan set bits result = tair_client.tr_scan("user:active:2024-01-15", start_offset=0, count=100) print(f"Next offset: {result.start_offset}") print(f"User IDs: {result.offsets}") # Get range of set bits offsets = tair_client.tr_range("user:active:2024-01-15", 1000, 2000) print(offsets) # Get min/max set bit min_id = tair_client.tr_min("user:active:2024-01-15") max_id = tair_client.tr_max("user:active:2024-01-15") # Calculate Jaccard similarity similarity = tair_client.tr_jaccard("user:active:2024-01-15", "user:active:2024-01-16") print(f"Jaccard similarity: {similarity}") # Check containment contains = tair_client.tr_contains("user:active:all", "user:active:2024-01-15") # Get rank (count of set bits up to offset) rank = tair_client.tr_rank("user:active:2024-01-15", 1500) ``` -------------------------------- ### Manage Vector TTL and Numeric Attributes in TairVector Source: https://context7.com/tair-opensource/tair-py/llms.txt Provides examples for setting Time-To-Live (TTL) for vectors in TairVector, both in seconds and milliseconds. It also shows how to increment numeric and float attributes associated with vectors, useful for counters or updating scores. ```python from tair import Tair tair = Tair(host="localhost", port=6379, db=0) tair.tvs_hexpire("image_embeddings", "img_temp", 3600) tair.tvs_hpexpire("image_embeddings", "img_temp", 3600000) ttl = tair.tvs_httl("image_embeddings", "img_temp") print(f"TTL: {ttl} seconds") tair.tvs_hincrby("image_embeddings", "img_001", "view_count", 1) tair.tvs_hincrbyfloat("image_embeddings", "img_001", "rating", 0.5) ``` -------------------------------- ### TairHash: Hash Fields with Expiration and Versioning (Python) Source: https://context7.com/tair-opensource/tair-py/llms.txt Details how to use TairHash for managing hash data where individual fields can have separate expiration times (seconds or milliseconds) and version tracking. Supports setting, getting, multi-set/get, retrieving all fields, checking TTL, incrementing values, and deleting fields. ```python from tair import Tair, ValueVersionItem import time tair = Tair(host="localhost", port=6379, db=0) # Set hash field with 60 second expiration tair.exhset("user:1000", "session_token", "abc123", ex=60) # Set field with millisecond expiration tair.exhset("user:1000", "temp_data", "xyz", px=5000) # Set field only if not exists tair.exhset("user:1000", "email", "user@example.com", nx=True) # Set field with version tracking tair.exhset("user:1000", "status", "active", ver=1) # Get field value value = tair.exhget("user:1000", "email") print(value) # b'user@example.com' # Get field with version result = tair.exhgetwithver("user:1000", "status") if result: print(result.value, result.version) # Set multiple fields at once tair.exhmset("user:1000", { "name": "John Doe", "age": "30", "city": "New York" }) # Get multiple fields with versions results = tair.exhmgetwithver("user:1000", ["name", "age"]) for item in results: if item: print(f"{item.value} (version: {item.version})") # Get all fields and values all_items = tair.exhgetall("user:1000") for item in all_items: print(f"{item.field}: {item.value}") # Check field TTL in seconds ttl = tair.exhttl("user:1000", "session_token") print(f"TTL: {ttl} seconds") # Increment hash field with bounds tair.exhincrby("user:1000", "login_count", 1, minval=0, maxval=1000) # Increment float field tair.exhincrbyfloat("user:1000", "balance", 50.25) # Set field expiration (doesn't modify value) tair.exhexpire("user:1000", "temp_field", 120) # Delete fields tair.exhdel("user:1000", ["temp_data", "temp_field"]) ``` -------------------------------- ### Perform GIS Searches with Tair-Py Source: https://context7.com/tair-opensource/tair-py/llms.txt Demonstrates various GIS search operations using the Tair-Py library, including searching within a specified geometry, finding geometries that contain a point, checking for spatial containment, and identifying intersecting geometries. It also includes an example of deleting a geometry. These operations are crucial for location-based data retrieval. ```python search_area = "POLYGON((115.0 39.0, 118.0 39.0, 118.0 41.0, 115.0 41.0, 115.0 39.0))" results = tair.gis_search("city:stores", geom=search_area) point = "POINT(116.405 39.920)" results = tair.gis_contains("city:stores", point, withoutwkts=False) results = tair.gis_within("city:stores", search_area) results = tair.gis_intersects("city:stores", search_area) tair.gis_del("city:stores", "store1") def find_nearby_stores(user_lng, user_lat, radius_meters): search_radius = TairGisSearchRadius( longitude=user_lng, latitude=user_lat, distance=radius_meters, unit="m" ) nearby = tair.gis_search("city:stores", radius=search_radius, withdist=True, count=5, asc=True) return nearby stores = find_nearby_stores(116.401, 39.915, 5000) ``` -------------------------------- ### Create and Manage Vector Indexes with TairVector Source: https://context7.com/tair-opensource/tair-py/llms.txt Shows how to create vector indexes for TairVector, specifying dimensions, distance metrics (e.g., L2), and index types (e.g., HNSW) with relevant parameters. It also covers retrieving index information, demonstrating the foundational steps for enabling vector similarity search. ```python from tair import Tair from tair.tairvector import DistanceMetric, IndexType import random tair = Tair(host="localhost", port=6379, db=0) dim = 128 index_params = { "M": 32, # HNSW parameter "ef_construct": 200 # construction time accuracy } tair.tvs_create_index("image_embeddings", dim=dim, distance_type=DistanceMetric.L2, index_type=IndexType.HNSW, **index_params) index_info = tair.tvs_get_index("image_embeddings") print(index_info) ``` -------------------------------- ### Cluster Support with TairCluster Source: https://context7.com/tair-opensource/tair-py/llms.txt Demonstrates how to connect to a Redis Cluster deployment using TairCluster and utilize Tair commands, including pipelined operations, in a clustered environment. ```python from tair import TairCluster # Connect to Redis Cluster cluster = TairCluster( startup_nodes=[ {"host": "127.0.0.1", "port": 7000}, {"host": "127.0.0.1", "port": 7001}, {"host": "127.0.0.1", "port": 7002} ], decode_responses=False, skip_full_coverage_check=False, max_connections_per_node=32 ) # Use same API as Tair client cluster.exset("key1", "value1") result = cluster.exget("key1") print(result.value, result.version) # All Tair module commands work in cluster mode cluster.bf_add("bloom_key", "item1") cluster.json_set("doc_key", ".", '{"status": "ok"}') # Pipeline in cluster mode pipeline = cluster.pipeline() pipeline.exset("key1", "value1") pipeline.exset("key2", "value2") pipeline.execute() ``` -------------------------------- ### Async Operations with Tair Source: https://context7.com/tair-opensource/tair-py/llms.txt Shows how to perform asynchronous operations using the tair-py async client, including connecting, executing commands, performing vector searches, and using async pipelines. ```python from tair.asyncio import Tair import asyncio async def main(): # Connect with async client tair = Tair(host="localhost", port=6379, db=0) try: # Async operations await tair.exset("async_key", "async_value") result = await tair.exget("async_key") print(result.value, result.version) # Async vector search await tair.tvs_create_index("async_vectors", dim=128) vector = [0.1] * 128 await tair.tvs_hset("async_vectors", "vec1", vector=vector) results = await tair.tvs_knnsearch("async_vectors", k=10, vector=vector) # Async pipeline pipeline = tair.pipeline() pipeline.exset("key1", "value1") pipeline.exset("key2", "value2") await pipeline.execute() finally: await tair.close() # Run async code asyncio.run(main()) ``` -------------------------------- ### Geospatial Operations with Tair Python Source: https://context7.com/tair-opensource/tair-py/llms.txt Demonstrates geospatial indexing and querying using the Tair Python client with WKT format support. Includes adding points and polygons, retrieving geometries, and performing radius and member-based searches with distance calculations. Requires the tair library and a Tair instance with GIS capabilities. ```python from tair import Tair, TairGisSearchRadius, TairGisSearchMember tair_client = Tair(host="localhost", port=6379, db=0) # Add polygons/points using WKT format tair_client.gis_add("city:stores", { "store1": "POINT(116.401 39.915)", # Beijing "store2": "POINT(121.473 31.230)", # Shanghai "store3": "POLYGON((116.0 39.5, 117.0 39.5, 117.0 40.5, 116.0 40.5, 116.0 39.5))", }) # Add area area_wkt = "POLYGON((100.0 30.0, 110.0 30.0, 110.0 40.0, 100.0 40.0, 100.0 30.0))" tair_client.gis_add("regions", {"region1": area_wkt}) # Get geometry by name geometry = tair_client.gis_get("city:stores", "store1") print(geometry) # WKT format # Get all geometries all_geoms = tair_client.gis_getall("city:stores") for geom in all_geoms: print(geom) # Get all without WKT (just names) names = tair_client.gis_getall("city:stores", withoutwkts=True) # Search within radius (from point) radius = TairGisSearchRadius( longitude=116.400, latitude=39.900, distance=50000, # 50km unit="m" ) results = tair_client.gis_search("city:stores", radius=radius, withdist=True, count=10) for result in results: print(f"{result}") # Search by member distance (from existing point) member_search = TairGisSearchMember( field="store1", distance=100000, # 100km unit="m" ) results = tair_client.gis_search("city:stores", member=member_search, withdist=True, asc=True) ``` -------------------------------- ### Hybrid Search with Tair Source: https://context7.com/tair-opensource/tair-py/llms.txt Demonstrates how to create a hybrid index for vector and text search, add data with both vector and text fields, and perform a hybrid search operation using a specified ratio. ```python import tair kwargs = {"lexical_algorithm": "bm25"} tair.tvs_create_index("products", dim=4, **kwargs) vectors = [[i, i, i, i] for i in range(1, 4)] texts = [ {"TEXT": "Turtle Check Men Navy Blue Shirt"}, {"TEXT": "Peter England Men Party Blue Jeans"}, {"TEXT": "Titan Women Silver Watch"} ] for i in range(3): tair.tvs_hset("products", f"prod_{i}", vector=vectors[i], is_binary=False, **texts[i]) # Search with hybrid ratio (0=text only, 0.5=hybrid, 1=vector only) results = tair.tvs_knnsearch("products", k=10, vector="[1,1,1,0]", TEXT="Women Watch", hybrid_ratio=0.5) ``` -------------------------------- ### Pipeline Operations with Tair Source: https://context7.com/tair-opensource/tair-py/llms.txt Illustrates how to use the Tair pipeline for batch operations, including regular commands, vector operations, and batch retrieval, to improve performance by reducing network latency. ```python from tair import Tair import random tair = Tair(host="localhost", port=6379, db=0) # Create pipeline (non-transactional for better performance) pipeline = tair.pipeline(transaction=False) # Queue multiple operations pipeline.exset("key1", "value1") pipeline.exset("key2", "value2", ex=60) pipeline.exget("key1") pipeline.exincrby("counter", 1, minval=0, maxval=1000) pipeline.exhset("hash1", "field1", "value1") pipeline.bf_add("bloom1", "item1") pipeline.json_set("doc1", ".", '{"name": "test"}') # Execute all at once results = pipeline.execute(raise_on_error=False) # Process results for i, result in enumerate(results): try: print(f"Command {i}: {result}") except Exception as e: print(f"Command {i} error: {e}") # Vector operations in pipeline pipeline = tair.pipeline(transaction=False) for i in range(100): vector = [random.random() for _ in range(128)] pipeline.tvs_hset("embeddings", f"vec_{i}", vector=vector, is_binary=False, label=f"item_{i}") results = pipeline.execute(raise_on_error=False) # Pipeline for batch retrieval keys = [f"vec_{i}" for i in range(100)] pipeline = tair.pipeline(transaction=False) for key in keys: pipeline.tvs_hgetall("embeddings", key) results = pipeline.execute(raise_on_error=False) ``` -------------------------------- ### Manage Bloom Filters with Python - TairBloom Source: https://context7.com/tair-opensource/tair-py/llms.txt Illustrates how to create and manage Bloom filters using the TairBloom module in Python. It covers reserving filters with specified error rates and capacities, adding single or multiple items, checking for item existence, and using filters for recommendation systems to avoid duplicate suggestions. ```python from tair import Tair import uuid tair_client = Tair(host="localhost", port=6379, db=0) # Create Bloom filter with error rate and capacity # error_rate: false positive rate (0.01 = 1%) # capacity: expected number of items tair_client.bf_reserve("user_recommendations", error_rate=0.01, capacity=10000) # Add single item doc_id = str(uuid.uuid4()) added = tair_client.bf_add("user:1000:seen_docs", doc_id) print(added) # 1 if added, 0 if already exists # Add multiple items doc_ids = [str(uuid.uuid4()) for _ in range(5)] results = tair_client.bf_madd("user:1000:seen_docs", doc_ids) print(results) # [1, 1, 1, 1, 1] for new items # Check if item exists exists = tair_client.bf_exists("user:1000:seen_docs", doc_id) print(exists) # True (or possibly false positive) # Check multiple items exists_list = tair_client.bf_mexists("user:1000:seen_docs", doc_ids) print(exists_list) # [True, True, True, True, True] # Insert with auto-creation tair_client.bf_insert("user:2000:seen_docs", ["item1", "item2", "item3"], capacity=5000, error_rate=0.01) # Insert into existing filter only (no auto-create) tair_client.bf_insert("user:1000:seen_docs", ["item4"], nocreate=True) # Recommendation system example def recommended_system(userid, docid): if tair_client.bf_exists(userid, docid): print(f"{docid} may have been seen by {userid}") else: # Send recommendation tair_client.bf_add(userid, docid) print(f"Recommending {docid} to {userid}") # Use case: avoid duplicate recommendations user_id = "user:5000" for doc in ["doc_a", "doc_b", "doc_a"]: # doc_a repeated recommended_system(user_id, doc) ``` -------------------------------- ### Add and Manipulate EXZSet Members with Python Source: https://context7.com/tair-opensource/tair-py/llms.txt Demonstrates adding members with multi-dimensional scores to an EXZSet, including conditional additions, score increments, and retrieval of member scores. It also covers range queries by rank, score, and lexicographical order, as well as rank retrieval, counting, and removal operations. ```python import tair tair_client = tair.Tair(host="localhost", port=6379, db=0) # Add members with multi-dimensional scores # Format: "score1#score2#score3" tair_client.exzadd("leaderboard", { "player1": "100.5#50#1000", # level#rank#points "player2": "100.5#48#950", "player3": "99.0#55#1100" }) # Add with options tair_client.exzadd("leaderboard", {"player4": "100.5#51#980"}, nx=True) # only if not exists tair_client.exzadd("leaderboard", {"player1": "101.0#50#1050"}, xx=True) # only if exists # Increment member score new_score = tair_client.exzincrby("leaderboard", 10.5, "player1") print(new_score) # returns updated score string # Get member score score = tair_client.exzscore("leaderboard", "player1") print(score) # "101.0#50#1050" # Range by rank (0-based index) items = tair_client.exzrange("leaderboard", 0, 2, withscores=True) for item in items: print(f"{item.member}: {item.score}") # Reverse range (highest to lowest) items = tair_client.exzrevrange("leaderboard", 0, 2, withscores=True) # Range by score items = tair_client.exzrangebyscore("leaderboard", "100#0#0", "101#100#2000", withscores=True) # Range with pagination items = tair_client.exzrangebyscore("leaderboard", "-inf", "+inf", withscores=True, offset=0, count=10) # Range by lexicographic order items = tair_client.exzrangebylex("leaderboard", "[player1", "[player3") # Get rank of member (0-based) rank = tair_client.exzrank("leaderboard", "player1") print(f"Rank: {rank}") # Reverse rank rev_rank = tair_client.exzrevrank("leaderboard", "player1") # Count members in score range count = tair_client.exzcount("leaderboard", "100#0#0", "101#100#2000") # Get rank by specific score rank = tair_client.exzrankbyscore("leaderboard", "100.5#50#1000") # Remove members tair_client.exzrem("leaderboard", ["player4"]) # Remove by rank range tair_client.exzremrangebyrank("leaderboard", 0, 0) # Remove by score range tair_client.exzremrangebyscore("leaderboard", "90#0#0", "95#100#1000") # Get cardinality card = tair_client.exzcard("leaderboard") print(f"Total members: {card}") ``` -------------------------------- ### Add and Retrieve Vectors with Attributes in TairVector Source: https://context7.com/tair-opensource/tair-py/llms.txt Illustrates adding vectors to a TairVector index, both with and without associated attributes (like categories and tags). It also demonstrates retrieving all attributes or specific attributes for a given vector key, highlighting data storage and access patterns. ```python import random from tair import Tair tair = Tair(host="localhost", port=6379, db=0) dim = 128 vector = [random.random() for _ in range(dim)] tair.tvs_hset("image_embeddings", "img_001", vector=vector, is_binary=False, category="animals", tags="cat,pet") tair.tvs_hset("image_embeddings", "img_002", vector=vector) tair.tvs_hset("image_embeddings", "img_001", category="animals", subcategory="feline") result = tair.tvs_hgetall("image_embeddings", "img_001") print(result["VECTOR"]) print(result["category"]) attrs = tair.tvs_hmget("image_embeddings", "img_001", "category", "tags") ``` -------------------------------- ### Exception Handling in Tair Source: https://context7.com/tair-opensource/tair-py/llms.txt Demonstrates how to handle various Tair-specific exceptions, including ResponseError, ConnectionError, TimeoutError, and the base TairError, for robust error management in applications. ```python from tair import Tair, TairError, ResponseError, ConnectionError, TimeoutError tair = Tair(host="localhost", port=6379, db=0) try: # Operation that might violate bounds tair.exincrby("counter", 1, minval=0, maxval=10) except ResponseError as e: print(f"Server error: {e}") except ConnectionError as e: print(f"Connection failed: {e}") except TimeoutError as e: print(f"Operation timed out: {e}") except TairError as e: print(f"Tair error: {e}") # Bounded counter example with error handling def safe_increment(key, amount): try: return tair.exincrby(key, amount, minval=0, maxval=100) except ResponseError as e: if "overflow" in str(e).lower(): print("Counter would overflow") return None raise result = safe_increment("inventory", 10) if result is not None: print(f"New count: {result}") ``` -------------------------------- ### Perform Roaring Bitmap Operations with Python - TairRoaring Source: https://context7.com/tair-opensource/tair-py/llms.txt Details the use of the TairRoaring module for efficient compressed bitmap operations in Python. It covers setting and clearing individual bits, setting ranges, flipping bits, retrieving bit values, counting set bits within ranges, finding bit positions, and performing bitwise operations like AND, OR, XOR, and ANDNOT between bitmaps. ```python from tair import Tair tair_client = Tair(host="localhost", port=6379, db=0) # Set single bit tair_client.tr_setbit("user:active:2024-01-15", 1001, 1) tair_client.tr_setbit("user:active:2024-01-15", 1005, 1) # Set multiple bits at once tair_client.tr_setbits("user:active:2024-01-15", [1010, 1015, 1020]) # Clear bits tair_client.tr_clearbits("user:active:2024-01-15", [1005]) # Set range of bits (inclusive) tair_client.tr_setrange("user:active:2024-01-16", 2000, 2099) # Flip range of bits tair_client.tr_fliprange("user:active:2024-01-16", 2050, 2060) # Get single bit bit = tair_client.tr_getbit("user:active:2024-01-15", 1001) print(bit) # 1 # Get multiple bits bits = tair_client.tr_getbits("user:active:2024-01-15", [1001, 1005, 1010]) print(bits) # [1, 0, 1] # Count set bits count = tair_client.tr_bitcount("user:active:2024-01-15") print(f"Active users: {count}") # Count in range count = tair_client.tr_bitcount("user:active:2024-01-15", start=1000, end=2000) # Find first set/unset bit pos = tair_client.tr_bitpos("user:active:2024-01-15", value=1, count=1) print(f"First active user ID: {pos}") # Bitmap operations (AND, OR, XOR, ANDNOT) tair_client.tr_bitop("users:both_days", "AND", ["user:active:2024-01-15", "user:active:2024-01-16"]) ``` -------------------------------- ### Perform Vector Similarity Search (KNN) with TairVector Source: https://context7.com/tair-opensource/tair-py/llms.txt Demonstrates how to perform k-nearest neighbor (KNN) searches in TairVector using a query vector. It covers basic KNN search, KNN search with attribute filtering, and batch KNN search for multiple query vectors. This functionality is core to applications requiring similarity-based retrieval. ```python import random from tair import Tair tair = Tair(host="localhost", port=6379, db=0) dim = 128 query_vector = [random.random() for _ in range(dim)] results = tair.tvs_knnsearch("image_embeddings", k=10, vector=query_vector) for key, distance in results: print(f"{key}: distance={distance}") results = tair.tvs_knnsearch("image_embeddings", k=5, vector=query_vector, filter_str="category == 'animals'") queries = [[random.random() for _ in range(dim)] for _ in range(3)] batch_results = tair.tvs_mknnsearch("image_embeddings", k=5, vectors=queries) for i, results in enumerate(batch_results): print(f"Query {i}: {results}") results = tair.tvs_mindexknnsearch( index=["image_embeddings", "video_embeddings"], k=10, vector=query_vector ) ``` -------------------------------- ### Delete Vectors and Scan Data in TairVector Source: https://context7.com/tair-opensource/tair-py/llms.txt Demonstrates how to delete individual vectors and their attributes from a TairVector index. It also covers scanning vectors within an index, with and without filtering, allowing for data retrieval and management operations. ```python from tair import Tair tair = Tair(host="localhost", port=6379, db=0) tair.tvs_del("image_embeddings", "img_001") tair.tvs_hdel("image_embeddings", "img_002", "tags", "subcategory") scan_result = tair.tvs_scan("image_embeddings", pattern="img_*", batch=100) for key in scan_result: print(key) scan_result = tair.tvs_scan("image_embeddings", filter_str="category == 'animals'", batch=50) tair.tvs_del_index("image_embeddings") ```