[docs]classTokenEscaper:""" Escape punctuation within an input string. """# Characters that RediSearch requires us to escape during queries.# Source: https://redis.io/docs/stack/search/reference/escaping/#the-rules-of-text-field-tokenizationDEFAULT_ESCAPED_CHARS=r"[,.<>{}\[\]\\\"\':;!@#$%^&*()\-+=~\/ ]"
[docs]defescape(self,value:str)->str:ifnotisinstance(value,str):raiseTypeError("Value must be a string object for token escaping."f"Got type {type(value)}")defescape_symbol(match:re.Match)->str:value=match.group(0)returnf"\\{value}"returnself.escaped_chars_re.sub(escape_symbol,value)
[docs]defget_client(redis_url:str,**kwargs:Any)->RedisType:"""Get a redis client from the connection url given. This helper accepts urls for Redis server (TCP with/without TLS or UnixSocket) as well as Redis Sentinel connections. Before creating a connection the existence of the database driver is checked and ValueError raised otherwise. To use, you should have the ``redis`` python package installed. Example: .. code-block:: python from langchain_community.utilities.redis import get_client redis_client = get_client( redis_url="redis://username:password@localhost:6379" index_name="my-index", embedding_function=embeddings.embed_query, ) """# Initialize with necessary components.try:importredis# type: ignore[import-untyped]exceptImportError:raiseImportError("Could not import redis python package. ""Please install it with `pip install redis>=4.1.0`.")# Connect to redis server from url, reconnect with cluster client if neededredis_client=redis.from_url(redis_url,**kwargs)if_check_for_cluster(redis_client):redis_client.close()redis_client=_redis_cluster_client(redis_url,**kwargs)returnredis_client