RedisConfig#
- classlangchain_redis.config.RedisConfig[source]#
Bases:
BaseModel
Configuration class for Redis vector store settings.
This class defines the configuration parameters for setting up and interacting witha Redis vector store. It uses Pydantic for data validation and settings management.
- index_name#
Name of the index in Redis. Defaults to a generated ULID.
- Type:
str
- from_existing#
Whether to use an existing index. Defaults to False.
- Type:
bool
- key_prefix#
Prefix for Redis keys. Defaults to index_nameif not set.
- Type:
Optional[str]
- redis_url#
URL of the Redis instance. Defaults to “redis://localhost:6379”.
- Type:
str
- connection_args#
Additional Redisconnection arguments.
- Type:
Optional[Dict[str, Any]]
- distance_metric#
Distance metric for vector similarity.Defaults to “COSINE”.
- Type:
str
- indexing_algorithm#
Algorithm used for indexing. Defaults to “FLAT”.
- Type:
str
- vector_datatype#
Data type of the vector. Defaults to “FLOAT32”.
- Type:
str
- storage_type#
Storage type in Redis. Defaults to “hash”.
- Type:
str
- id_field#
Field name for document ID. Defaults to “id”.
- Type:
str
- content_field#
Field name for document content. Defaults to “text”.
- Type:
str
- embedding_field#
Field name for embedding vector. Defaults to “embedding”.
- Type:
str
- default_tag_separator#
Separator for tag fields. Defaults to “|”.
- Type:
str
- metadata_schema#
Schema for metadata fields.
- Type:
Optional[List[Dict[str, Any]]]
- index_schema#
Full index schema definition.
- Type:
Optional[IndexSchema]
- schema_path#
Path to a YAML file containing the index schema.
- Type:
Optional[str]
- return_keys#
Whether to return keys after adding documents.Defaults to False.
- Type:
bool
- custom_keys#
Custom keys for documents.
- Type:
Optional[List[str]]
- embedding_dimensions#
Dimensionality of embedding vectors.
- Type:
Optional[int]
Example
fromlangchain_redisimportRedisConfigconfig=RedisConfig(index_name="my_index",redis_url="redis://localhost:6379",distance_metric="COSINE",embedding_dimensions=1536)# Use this config to initialize a RedisVectorStorevector_store=RedisVectorStore(embeddings=my_embeddings,config=config)
Note
Only one of ‘index_schema’, ‘schema_path’, or ‘metadata_schema’should be specified.
The ‘key_prefix’ is automatically set to ‘index_name’ if not provided.
When ‘from_existing’ is True, it connects to an existing index insteadof creating a new one.
Custom validation ensures that incompatible options are notsimultaneously specified.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot bevalidated to form a valid model.
self is explicitly positional-only to allowself as a field name.
- paramconnection_args:Dict[str,Any]|None={}#
- paramcontent_field:str='text'#
- paramcustom_keys:List[str]|None=None#
- paramdefault_tag_separator:str='|'#
- paramdistance_metric:str='COSINE'#
- paramembedding_dimensions:int|None=None#
- paramembedding_field:str='embedding'#
- paramfrom_existing:bool=False#
- paramid_field:str='id'#
- paramindex_name:str[Optional]#
- paramindex_schema:Annotated[IndexSchema|None,SkipValidation()]=None(alias'schema')#
- paramindexing_algorithm:str='FLAT'#
- paramkey_prefix:str|None=None#
- parammetadata_schema:List[Dict[str,Any]]|None[Optional]#
- paramredis_client:Redis|None=None#
- paramredis_url:str='redis://localhost:6379'#
- paramreturn_keys:bool=False#
- paramschema_path:str|None=None#
- paramstorage_type:str='hash'#
- paramvector_datatype:str='FLOAT32'#
- classmethodfrom_existing_index(
- index_name:str,
- redis:Redis,
Create a RedisConfig object from an existing Redis index.
This class method creates a RedisConfig instance based on the configurationof an existing index in Redis. It’s useful for connecting to and working withpre-existing Redis vector store indexes.
- Parameters:
index_name (str) – The name of the existing index in Redis.
redis (Redis) – An active Redis client instance connected to the Redis serverwhere the index exists.
- Returns:
- A new instance of RedisConfig configured to match the existing
index.
- Return type:
Example
fromredisimportRedisfromlangchain_redisimportRedisConfig# Assuming an existing Redis connectionredis_client=Redis.from_url("redis://localhost:6379")config=RedisConfig.from_existing_index(index_name="my_existing_index",redis_client=redis_client)print(config.index_name)# Output: my_existing_indexprint(config.from_existing)# Output: True
Note
This method sets the ‘from_existing’ attribute to True, indicating thatthe configuration is based on an existing index.
The method doesn’t fetch the full schema or configuration of theexisting index. It only sets up the basic parameters needed to connectto the index.
Additional index details (like field configurations) are not retrieved andshould be known or discovered separately if needed.
This method is particularly useful when you need to work with or extend anexisting Redis vector store index.
Ensure that the provided Redis client has the necessary permissions toaccess the specified index.
If the index doesn’t exist, this method will still create a config, butoperations using this config may fail until the index is created.
- Raises:
ValueError – If the index_name is empty or None.
ConnectionError – If there’s an issue connecting to Redis using the provided client.
- Parameters:
index_name (str)
redis (Redis)
- Return type:
- classmethodfrom_kwargs(
- **kwargs:Any,
- Create a RedisConfig object with default values,
overwritten by provided kwargs.
This class method allows for flexible creation of a RedisConfig object,using default values where not specified and overriding with any providedkeyword arguments. If a ‘schema’ argument is provided, it will be set as‘index_schema’ in the config.
- Parameters:
**kwargs (Any) –
- Keyword arguments that match RedisConfig attributes. These will
override default values.
Common kwargs include:- index_name (str): Name of the index in Redis.- redis_url (str): URL of the Redis instance.- distance_metric (str): Distance metric for vector similarity.- indexing_algorithm (str): Algorithm used for indexing.- vector_datatype (str): Data type of the vector.- embedding_dimensions (int): Dimensionality of embedding vectors.
- Returns:
A new instance of RedisConfig with applied settings.
- Return type:
Example
fromlangchain_redisimportRedisConfigconfig=RedisConfig.from_kwargs(index_name="my_custom_index",redis_url="redis://custom-host:6379",distance_metric="COSINE",embedding_dimensions=768)print(config.index_name)# Output: my_custom_indexprint(config.distance_metric)# Output: COSINE
- classmethodfrom_schema(
- schema:IndexSchema,
- **kwargs:Any,
Create a RedisConfig object from an IndexSchema.
This class method creates a RedisConfig instance using the provided IndexSchema,which defines the structure of the Redis index.
- Parameters:
schema (IndexSchema) – An IndexSchema object defining the structure ofthe Redis index.
**kwargs –
- Additional keyword arguments to override or supplement the
schema-derived settings.
Common kwargs include:- redis_url (str): URL of the Redis instance.- distance_metric (str): Distance metric for vector similarity.- embedding_dimensions (int): Dimensionality of embedding vectors.
- Returns:
- A new instance of RedisConfig configured based on the provided
schema and kwargs.
- Return type:
Example
fromredisvl.schemaimportIndexSchemafromlangchain_redisimportRedisConfigschema=IndexSchema.from_dict({"index":{"name":"my_index","storage_type":"hash"},"fields":[{"name":"text","type":"text"},{"name":"embedding","type":"vector","attrs":{"dims":1536,"distance_metric":"cosine"}}]})config=RedisConfig.from_schema(schema,redis_url="redis://localhost:6379")print(config.index_name)# Output: my_indexprint(config.storage_type)# Output: hash
Note
The method extracts index name, key prefix, and storage type from theschema.
If the schema specifies a vector field, its attributes (like dimensionsand distance metric) are used.
Additional kwargs can override settings derived from the schema.
This method is useful when you have a pre-defined index structure and wantto create a matching config.
The resulting config can be used to ensure that a RedisVectorStore matchesan existing index structure.
- classmethodfrom_yaml(
- schema_path:str,
- **kwargs:Any,
Create a RedisConfig object from a YAML file containing the index schema.
This class method creates a RedisConfig instance using a YAML file that definesthe structure of the Redis index.
- Parameters:
schema_path (str) – Path to the YAML file containing the index schemadefinition.
**kwargs –
- Additional keyword arguments to override or supplement the
schema-derived settings.
Common kwargs include:- redis_url (str): URL of the Redis instance.- distance_metric (str): Distance metric for vector similarity.- embedding_dimensions (int): Dimensionality of embedding vectors.
- Returns:
- A new instance of RedisConfig configured based on the YAML
schema and kwargs.
- Return type:
Example
fromlangchain_redisimportRedisConfig# Assuming 'index_schema.yaml' contains a valid index schemaconfig=RedisConfig.from_yaml(schema_path="path/to/index_schema.yaml",redis_url="redis://localhost:6379")print(config.index_name)# Output: Name defined in YAMLprint(config.storage_type)# Output: Storage type defined in YAML
Note
The YAML file should contain a valid index schema definitioncompatible with RedisVL.
This method internally uses IndexSchema.from_yaml() to parsethe YAML file.
Settings derived from the YAML schema can be overridden byadditional kwargs.
This method is particularly useful when index structures are definedexternally in YAML files.
Ensure that the YAML file is correctly formatted and accessible atthe given path.
Any errors in reading or parsing the YAML file will be propagatedas exceptions.
- Raises:
FileNotFoundError – If the specified YAML file does not exist.
YAMLError – If there are issues parsing the YAML file.
ValueError – If the YAML content is not a valid index schema.
- Parameters:
schema_path (str)
kwargs (Any)
- Return type:
- classmethodwith_metadata_schema(
- metadata_schema:List[Dict[str,Any]],
- **kwargs:Any,
Create a RedisConfig object with a specified metadata schema.
This class method creates a RedisConfig instance using a providedmetadata schema, which defines the structure of additional metadatafields in the Redis index.
- Parameters:
metadata_schema (List[Dict[str,Any]]) – A list of dictionaries definingthe metadata fields. Each dictionary should contain at least ‘name’and ‘type’ keys.
**kwargs –
- Additional keyword arguments to configure the RedisConfig
instance.
Common kwargs include:- index_name (str): Name of the index in Redis.- redis_url (str): URL of the Redis instance.- distance_metric (str): Distance metric for vector similarity.- embedding_dimensions (int): Dimensionality of embedding vectors.
- Returns:
- A new instance of RedisConfig configured with the specified
metadata schema.
- Return type:
Example
fromlangchain_redisimportRedisConfigmetadata_schema=[{"name":"author","type":"text"},{"name":"publication_date","type":"numeric"},{"name":"tags","type":"tag","separator":","}]config=RedisConfig.with_metadata_schema(metadata_schema,index_name="book_index",redis_url="redis://localhost:6379",embedding_dimensions=1536)print(config.metadata_schema)# Output: The metadata schema listprint(config.index_name)# Output: book_index
Note
The metadata_schema defines additional fields beyond the default contentand embedding fields.
Common metadata field types include ‘text’, ‘numeric’, and ‘tag’.
For ‘tag’ fields, you can specify a custom separator using the‘separator’ key.
This method is useful when you need to index and search on specificmetadata attributes.
The resulting config ensures that the RedisVectorStore will createan index with the specified metadata fields.
Make sure the metadata schema aligns with the actual metadata youplan to store with your documents.
This method sets only the metadata_schema; other configurationsshould be provided via kwargs.
- Raises:
ValueError – If the metadata_schema is not a list of dictionaries or if required keys are missing.
- Parameters:
metadata_schema (List[Dict[str,Any]])
kwargs (Any)
- Return type:
- to_index_schema()→IndexSchema[source]#
Convert the RedisConfig to an IndexSchema.
This method creates an IndexSchema object based on the current configuration.It’s useful for generating a schema that can be used to create or updatea Redis index.
- Returns:
An IndexSchema object representing the current configuration.
- Return type:
IndexSchema
Example
fromlangchain_redisimportRedisConfigconfig=RedisConfig(index_name="my_index",embedding_dimensions=1536,distance_metric="COSINE",metadata_schema=[{"name":"author","type":"text"},{"name":"year","type":"numeric"}])schema=config.to_index_schema()print(schema.index.name)# Output: my_indexprint(len(schema.fields))# Output: 4 (id, content, embedding, author, year)
Note
If an index_schema is already set, it will be returned directly.
If a schema_path is set, the schema will be loaded from the YAML file.
Otherwise, a new IndexSchema is created based on the currentconfiguration.
The resulting schema includes fields for id, content, and embeddingvector, as well as any additional fields specified in metadata_schema.
The embedding field is configured with the specified dimensions,distance metric, and other relevant attributes.
This method is particularly useful when you need to create a new index orvalidate the structure of an existing one.
The generated schema can be used with RedisVL operations that requirean IndexSchema.
- Raises:
ValueError – If essential configuration elements (like embedding_dimensions) are missing.
- Return type:
IndexSchema