Redis Vector Search: Real-Time Similarity Search Guide
Redis Vector Search brings sub-millisecond vector similarity search to your existing Redis infrastructure. Built into Redis Stack via the RediSearch module, it supports HNSW and FLAT indexes, metadata filtering alongside KNN queries, and the high-level redisvl Python library — ideal for real-time AI features where latency is critical.
Related Products
on GumroadDeveloper Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →AI Prompt Engineering Toolkit
58 structured prompt templates for Claude, ChatGPT, and Gemini — organized by use case. Code Review, Debugging, Documentation, Architecture, and 10 model-specific tips. Stop writing prompts from scratch.
Buy on Gumroad →Developer Cheat Sheet Bundle
10 print-ready cheat sheets for the tools developers use every day: Git, Docker, Linux CLI, SQL, Regex, HTTP Status codes, VS Code shortcuts, Bash scripting, jq/JSON, and Markdown.
Buy on Gumroad →You Might Also Need
JSON Formatter & Validator
Format, beautify, and validate JSON online. Paste your JSON to instantly pretty-print it with 2-space, 4-space, or tab indentation. Minify JSON too. Free, runs in your browser.
Open free tool →
Regex Tester
Free regex tester. Test regular expressions against multiple strings with expected match/no-match assertions — see instant pass/fail results. Built-in presets for email, URL, IPv4, and phone. Pro: unl
Open free tool →
Base64 Encoder & Decoder
Free Base64 Encoder & Decoder. Convert text, images, and any file to Base64 and back. Supports URL-safe Base64, image data URIs, and file download from Base64. Runs 100% in your browser — no data sent
Open free tool →
More Free Tools
Related Articles
curl 深度使用手冊:API 測試從入門到進階
curl 是每位開發者必備的 CLI 工具。本文涵蓋 GET/POST/PUT/DELETE 請求、認證、header 設定、檔案上傳、除錯技巧,以及 REST API 測試的完整實戰範例。
Best AI Code Review Tools 2026: CodeRabbit, Sourcery, DeepCode & Bito Compared
Compare top AI code review tools for 2026: CodeRabbit, Sourcery, DeepCode, and Bito. Features, pricing, GitHub/GitLab integration, and choosing the right tool for your team.
AI Code Review Tools 2026: GitHub Copilot, CodeRabbit, Qodo Merge Ranked
Compare AI code review tools for 2026: GitHub Copilot code review, CodeRabbit, Qodo Merge, Sourcery, and PR-Agent. Pricing, accuracy, and GitHub integration.
AI Coding Tools Comparison 2026: GitHub Copilot vs Cursor vs Windsurf vs Cline
Comprehensive comparison of the best AI coding tools in 2026: GitHub Copilot, Cursor, Windsurf, and Cline. Pricing, features, model support, and real-world benchmarks.
AI Pair Programming in 2026: GitHub Copilot vs Cursor vs Claude Code
Master AI pair programming in 2026. Compare GitHub Copilot, Cursor, and Claude Code for autocomplete, chat, and agentic workflows. Includes setup guides and productivity tips.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$9/mo after trial · Cancel anytime
Want the full toolkit?
Get DevPlaybook Pro
Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →Setup: Redis Stack & FT.CREATE Vector Index
Run Redis Stack with Docker and create a vector index using the raw Redis commands.
# Run Redis Stack locally (includes RediSearch + vector search)
# docker run -d -p 6379:6379 redis/redis-stack
pip install redis openai redisvl
import redis
import struct
import json
r = redis.Redis(host="localhost", port=6379, decode_responses=False)
# Create HNSW vector index on Hash documents
# Fields: embedding (vector), category (tag), year (numeric), content (text)
r.execute_command(
"FT.CREATE", "idx:articles",
"ON", "HASH",
"PREFIX", "1", "article:",
"SCHEMA",
"content", "TEXT",
"category", "TAG",
"year", "NUMERIC", "SORTABLE",
"embedding", "VECTOR", "HNSW", "6",
"TYPE", "FLOAT32",
"DIM", "1536",
"DISTANCE_METRIC", "COSINE"
)
# FLAT (brute-force) index for small datasets / exact search
r.execute_command(
"FT.CREATE", "idx:small_docs",
"ON", "HASH",
"PREFIX", "1", "doc:",
"SCHEMA",
"embedding", "VECTOR", "FLAT", "6",
"TYPE", "FLOAT32",
"DIM", "1536",
"DISTANCE_METRIC", "COSINE"
) Insert Vectors & FT.SEARCH KNN Query
Store documents as Redis Hashes and query with FT.SEARCH KNN syntax including metadata filters.
import openai
oa = openai.OpenAI()
def embed(text: str) -> bytes:
vec = oa.embeddings.create(
model="text-embedding-3-small", input=text
).data[0].embedding
# Convert float list to bytes for Redis storage
return struct.pack(f"{len(vec)}f", *vec)
# Insert documents as Redis Hashes
docs = [
{"id": "1", "content": "RAG systems improve LLM accuracy", "category": "ai", "year": 2024},
{"id": "2", "content": "Redis supports real-time vector search", "category": "db", "year": 2024},
{"id": "3", "content": "HNSW index for fast ANN search", "category": "db", "year": 2023},
]
for doc in docs:
r.hset(f"article:{doc['id']}", mapping={
"content": doc["content"],
"category": doc["category"],
"year": doc["year"],
"embedding": embed(doc["content"])
})
# KNN search with metadata pre-filter
query_bytes = embed("how does retrieval augmented generation work")
# Filter: category=ai, year >= 2024, then KNN top-3
results = r.execute_command(
"FT.SEARCH", "idx:articles",
"(@category:{ai} @year:[2024 +inf])=>[KNN 3 @embedding $query_vec AS score]",
"PARAMS", "2", "query_vec", query_bytes,
"RETURN", "3", "content", "category", "score",
"SORTBY", "score",
"DIALECT", "2"
)
# Parse results (format: [count, key, [field, val, ...], ...])
count = results[0]
print(f"Found {count} results:")
for i in range(1, len(results), 2):
key = results[i].decode()
fields = dict(zip(results[i+1][::2], results[i+1][1::2]))
print(f" {key} | score={float(fields[b'score']):.4f} | {fields[b'content'].decode()}") redisvl: High-Level Python Library
redisvl abstracts FT.CREATE and FT.SEARCH into a clean Pythonic API with schema definitions and embedding functions.
from redisvl.index import SearchIndex
from redisvl.query import VectorQuery
from redisvl.utils.vectorize import OpenAITextVectorizer
# Define schema
schema = {
"index": {"name": "articles", "prefix": "article"},
"fields": [
{"name": "content", "type": "text"},
{"name": "category", "type": "tag"},
{"name": "year", "type": "numeric"},
{
"name": "embedding",
"type": "vector",
"attrs": {
"dims": 1536,
"distance_metric": "cosine",
"algorithm": "hnsw",
"datatype": "float32"
}
}
]
}
vectorizer = OpenAITextVectorizer(model="text-embedding-3-small")
index = SearchIndex.from_dict(schema)
index.connect("redis://localhost:6379")
index.create(overwrite=True)
# Load documents — redisvl auto-generates embeddings
data = [
{"content": "RAG systems improve LLM accuracy", "category": "ai", "year": 2024},
]
embeddings = vectorizer.embed_many([d["content"] for d in data])
for d, emb in zip(data, embeddings):
d["embedding"] = emb
index.load(data)
# Query
query_emb = vectorizer.embed("retrieval augmented generation")
query = VectorQuery(
vector=query_emb,
vector_field_name="embedding",
return_fields=["content", "category", "year"],
num_results=3,
filter_expression="@category:{ai}"
)
results = index.query(query)
for r in results:
print(r) Redis Vector Search vs Dedicated Vector Databases
| Feature | Redis Vector | Pinecone | Qdrant | pgvector |
|---|---|---|---|---|
| Latency | <1ms (in-memory) | ~10–50ms | ~5–20ms | ~5–50ms |
| Practical scale | ~10M vectors (RAM limited) | 100M+ | 100M+ | ~50M |
| Hybrid search | KNN + RediSearch filters | Limited | Sparse + dense | Manual |
| Multi-purpose | Cache + queue + vector | Vector only | Vector only | Full SQL database |
| Persistence | RDB + AOF | Managed | WAL + snapshots | Full ACID |
| Best for | Real-time, low-latency, existing Redis | Managed cloud prod | High perf self-host | SQL+vector in PG |
Frequently Asked Questions
What is Redis Vector Search?▼
Redis Vector Search is a feature of Redis Stack (and Redis Cloud) that adds vector similarity search capabilities to Redis. It uses the RediSearch module under the hood, allowing you to create HNSW or FLAT (brute-force) vector indexes on Redis Hash or JSON documents and run KNN (K-Nearest Neighbor) queries. Because Redis is an in-memory data structure store, vector search results return in sub-millisecond latency.
What is the difference between HNSW and FLAT index types in Redis?▼
FLAT performs brute-force exact nearest neighbor search — it scans every vector and guarantees 100% recall accuracy, but search time is O(n). Use FLAT for small collections (<100K vectors) or when 100% accuracy is required. HNSW is an approximate index that trades a small amount of recall accuracy for dramatically faster search at scale. HNSW is the recommended choice for production workloads with >100K vectors.
What is redisvl (Redis Vector Library)?▼
redisvl (redis-py-vector) is the official high-level Python library for Redis Vector Search. It provides a declarative schema definition, automatic index management, document ingestion with embedding functions, and a clean search API. It abstracts away the raw FT.CREATE and FT.SEARCH commands, making it much easier to build RAG pipelines on Redis. Install with: pip install redisvl
Can I filter by metadata alongside vector search in Redis?▼
Yes. When you define a vector index with FT.CREATE, you can also index scalar fields (TEXT, TAG, NUMERIC, GEO) in the same schema. At search time, you combine a KNN vector query with any RediSearch filter expression — for example: (@category:{ai} @year:[2024 +inf])=>[KNN 5 @embedding $query_vec]. This pre-filters candidates before KNN scoring.
When should I use Redis Vector Search vs a dedicated vector database?▼
Redis Vector Search excels for real-time, low-latency applications where you already use Redis for caching, session management, or pub/sub — adding vector search avoids a separate service. It is ideal for <10M vectors with sub-millisecond latency requirements. For billion-scale workloads, dedicated vector databases (Milvus, Qdrant) provide better scaling, more index types, and features like quantization. Redis cannot cost-effectively hold hundreds of millions of vectors entirely in RAM.
Does Redis Vector Search work with Redis Cloud?▼
Yes. Redis Cloud (Managed Redis) includes RediSearch and vector search capabilities in all paid tiers. You can also use Redis Stack locally (docker run -d redis/redis-stack) or on Redis Enterprise. The redisvl library and raw FT.CREATE commands work identically across all deployment options — just change the connection URL.
Related Products
on GumroadAI Prompt Engineering Toolkit
58 structured prompt templates for Claude, ChatGPT, and Gemini — organized by use case. Code Review, Debugging, Documentation, Architecture, and 10 model-specific tips. Stop writing prompts from scratch.
Buy on Gumroad →AI Developer Prompts Pack
55 battle-tested prompt templates for the workflows developers actually use: code review, debugging, architecture, documentation, and testing. Stop writing prompts from scratch.
Buy on Gumroad →Developer Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →You Might Also Need
Redis Command Tester
Test Redis commands in your browser with no install needed. Simulate SET, GET, HSET, LPUSH, EXPIRE, TTL and more with color-coded output and a built-in command reference.
Open free tool →
Redis Pipeline Builder
Build Redis command pipelines visually. Add GET, SET, HSET, LPUSH, EXPIRE and other commands, reorder them, and export as raw pipeline, redis-cli, or Node.js ioredis code.
Open free tool →
CrewAI Agent Config Generator
Build CrewAI agent configurations visually. Define roles, goals, backstories, and tools. Generate YAML or Python code for multi-agent crews.
Open free tool →
More Free Tools
Related Articles
Vector Database Comparison 2026: Pinecone vs Weaviate vs Qdrant vs Chroma
In-depth comparison of the top vector databases in 2026. Evaluate Pinecone, Weaviate, Qdrant, and Chroma on performance, scalability, filtering, pricing, and self-hosting for production AI applications.
Vector Databases Explained: Pinecone vs Weaviate vs Qdrant vs Chroma (2026 Guide)
A complete comparison of the best vector databases in 2026: Pinecone, Weaviate, Qdrant, Chroma, and pgvector. Pricing, code examples, performance benchmarks, and a clear decision framework for AI and LLM applications.
Building a RAG Pipeline from Scratch: Embeddings, Vector Databases, and Retrieval
Step-by-step guide to building a production-ready RAG pipeline in Python. Covers embeddings, chunking strategies, Chroma and Pinecone setup, hybrid search, reranking, and evaluation with RAGAS.
Building Production RAG Systems with LlamaIndex and Vector Databases 2026
Complete guide to building production-ready RAG systems with LlamaIndex v0.10+. Covers chunking strategies, embedding models, Chroma, Pinecone, Weaviate integration, and advanced retrieval patterns.
Building a Production RAG Pipeline: Complete Implementation Guide 2026
A comprehensive guide to building production-ready RAG pipelines in 2026. Covers chunking strategies, embedding models, vector store selection, retrieval techniques, reranking, evaluation with RAGAS/TruLens, and LangChain vs LlamaIndex vs custom implementations.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$9/mo after trial · Cancel anytime
Want the full toolkit?
Get DevPlaybook Pro
Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →