Redis is an in-memory data platform with vector search, full-text search, and semantic caching capabilities, designed for real-time AI applications.
This notebook shows how to use functionality related to the RedisVectorStore.
Setup
To use the RedisVectorStore you first need to install the partner package, as well as the other packages used throughout this notebook.
pip install -qU langchain-redis langchain-openai
You’ll need a running Redis instance with Redis Search features enabled. We recommend Redis 8.4+. You can start one locally with Docker:
docker run -d --name redis -p 6379:6379 redis:8.4
Or use Redis Cloud for a managed deployment.
(Optional) Download RedisInsight — a browser-based GUI for inspecting your data and indexes.
docker run -d --name redisinsight -p 5540:5540 redis/redisinsight:latest
Credentials
Configure your Redis connection by setting the following environment variable:
export REDIS_URL="redis://localhost:6379"
For Redis with authentication:
export REDIS_URL="redis://username:password@localhost:6379"
For Redis Cloud, use the connection string from your database dashboard:
export REDIS_URL="redis://default:<password>@<host>:<port>"
This package also supports SSL/TLS (rediss://) and high-availability Redis Sentinel deployments (redis+sentinel://). See the langchain-redis README for full connection options.
Set your OpenAI API key:
export OPENAI_API_KEY="your-api-key-here"
The langchain-redis package also provides RedisChatMessageHistory for conversation memory and RedisSemanticCache for LLM response caching — all backed by the same Redis instance as your vector store.
Initialization
import os
from langchain_openai import OpenAIEmbeddings
embeddings = OpenAIEmbeddings(model="text-embedding-3-small")
from langchain_redis import RedisConfig, RedisVectorStore
config = RedisConfig(
index_name="my_vectors",
redis_url=os.getenv("REDIS_URL", "redis://localhost:6379"),
distance_metric="COSINE", # Options: COSINE, L2, IP
metadata_schema=[
{"name": "baz", "type": "tag"},
{"name": "foo", "type": "tag"},
]
)
vector_store = RedisVectorStore(embeddings=embeddings, config=config)
The metadata_schema parameter tells Redis which metadata fields to index. Fields not listed here cannot be used in filters. Use "tag" for categorical string values and "numeric" for numbers.
Manage vector store
Add items to vector store
texts = ["foo", "bar"]
metadatas = [{"baz": "bar"}, {"foo": "baz"}]
vector_store.add_texts(texts, metadatas=metadatas)
You can also add documents with custom keys:
custom_keys = ["doc1", "doc2"]
vector_store.add_texts(texts, metadatas=metadatas, keys=custom_keys)
Or use add_documents with LangChain Document objects:
from langchain_core.documents import Document
document_1 = Document(page_content="foo", metadata={"baz": "bar"})
document_2 = Document(page_content="bar", metadata={"foo": "baz"})
document_3 = Document(page_content="to be deleted")
documents = [document_1, document_2, document_3]
ids = ["1", "2", "3"]
vector_store.add_documents(documents=documents, ids=ids)
Delete items from vector store
vector_store.delete(ids=["3"])
Query vector store
Once your vector store has been created and the relevant documents have been added you will most likely wish to query it during the running of your chain or agent.
Query directly
Performing a simple similarity search can be done as follows:
query = "foo"
docs = vector_store.similarity_search(query, k=2)
for doc in docs:
print(f"* {doc.page_content} [{doc.metadata}]")
Similarity search with score
docs_and_scores = vector_store.similarity_search_with_score(query, k=2)
for doc, score in docs_and_scores:
print(f"* [SIM={score:.3f}] {doc.page_content} [{doc.metadata}]")
Similarity search with filtering
from redisvl.query.filter import Tag
results = vector_store.similarity_search(
query="foo",
k=1,
filter=Tag("baz") == "bar"
)
for doc in results:
print(f"* {doc.page_content} [{doc.metadata}]")
Maximum marginal relevance search
docs = vector_store.max_marginal_relevance_search(query, k=2, fetch_k=10)
for doc in docs:
print(f"* {doc.page_content} [{doc.metadata}]")
Other search methods
There are more search methods not listed in this notebook, to find all of them be sure to read the API reference.
Redis supports hybrid search combining vector similarity with full-text search. See the API reference for similarity_search parameters including return_all and distance_threshold.
Query by turning into retriever
You can also transform the vector store into a retriever for easier usage in your chains.
retriever = vector_store.as_retriever(
search_type="mmr",
search_kwargs={"k": 1, "fetch_k": 2, "lambda_mult": 0.5},
)
retriever.invoke("your query here")
Usage for retrieval-augmented generation
For guides on how to use this vector store for retrieval-augmented generation (RAG), see the following sections:
For a full RAG walkthrough using langchain-redis, see this example notebook.
API reference
For detailed documentation of RedisVectorStore features and configurations head to the API reference.