Skip to main content

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.

✓ Sub-millisecond latency ✓ HNSW & FLAT indexes ✓ KNN + metadata filter ✓ redisvl high-level SDK ✓ Redis Cloud managed option
Share this tool: X / Twitter LinkedIn
✓ 60,000+ developers use DevPlaybook ★★★★★ 4.8 / 5 on Gumroad ✓ MIT licensed · Instant download ✓ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

Enjoying this tool? Get more like it.

Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • ⚡ AI Code Review, Doc Generator & SQL Builder
  • ⚡ All premium templates & early access
  • ⚡ Member discounts on Gumroad products
Start Free Trial →

$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.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro — $79 →

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 searchKNN + RediSearch filtersLimitedSparse + denseManual
Multi-purposeCache + queue + vectorVector onlyVector onlyFull SQL database
PersistenceRDB + AOFManagedWAL + snapshotsFull ACID
Best forReal-time, low-latency, existing RedisManaged cloud prodHigh perf self-hostSQL+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.

Share this tool: X / Twitter LinkedIn
✓ 60,000+ developers use DevPlaybook ★★★★★ 4.8 / 5 on Gumroad ✓ MIT licensed · Instant download ✓ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

Redis Command Tester Redis Pipeline Builder CrewAI Agent Config Generator Embedding Storage Calculator Redis Connection String Builder Redis Command Cheatsheet Test Coverage Calculator AI Safety Checklist Generator Jotai Atom Explorer RAG Chunk Size Optimizer CSS Container Query Builder AI Agent Memory Planner AI Hallucination Detector LangChain PromptTemplate Builder Redis TTL Calculator MySQL Query Explainer PostgreSQL EXPLAIN Analyzer GraphQL Fragment Generator Jest Coverage Config Generator Cron Expression Explainer Font Pairing Preview AI Agent Run Cost Tracker AI Pipeline DAG Builder AI Rate Limit Calculator Prompt Injection Tester Vibe Coding Prompt Optimizer AI IDE Comparator RAG Chunking Calculator AI Commit Message Generator AI Doc Generator — Pro Tool AI Regex Explainer — Pro Tool AI System Guardian AI Token Cost Calculator LLM Cost Calculator Vitest Configuration Generator AI Prompt Cost Calculator AI Model Comparator Mermaid Diagram Generator Elasticsearch Query Tester mTLS Certificate Chain Builder AI Model Benchmark Comparator JS Prototype Chain Visualizer OpenAI Token Counter AI Model Context Window Visualizer LLM JSON Schema Builder RAG Chunking Calculator OpenAI Prompt Tester AI Model Comparison Tool Multi-Agent Orchestration Planner OpenAI Function Calling Generator Token Counter & Cost Estimator AI Model Comparison Table AI API Rate Limit Calculator LLM Prompt Template Builder HTTP Headers Analyzer AI Code Review — Pro Tool AI Error Explainer — Pro Tool AI SQL Builder — Pro Tool AI Unit Test Generator — Pro Tool Color Palette Generator Docker Compose Generator JWT Decoder Prompt Template Builder Regex Tester Pro Regex Tester RSA Key Pair Generator SMTP Server Tester Biome Config Generator Terraform Variable Validator Haproxy Config Validator SBOM Generator AI Variable Namer AI PR Description Generator AI JSDoc Generator K8s Resource Limits Calculator LLM Context Window Calculator Regex Flags Explainer OAuth2 Flow Visualizer Prompt Token Estimator Jest Testing Framework Guide Vitest Guide — Vite-native Testing Playwright E2E Testing Guide Core Web Vitals Calculator LLM Prompt Cost Calculator System Prompt Builder Solana Program ID Generator Multi-Chain Wallet Address Validator LLM System Prompt Analyzer AI Embeddings Dimension Explorer Bezier Curve Editor LLM Benchmark Calculator Token Context Calculator LLM Prompt Caching Calculator AI Prompt Token Estimator AI Context Window Visualizer Embedding Similarity Calculator TypeScript Discriminated Union Builder Core Web Vitals Budget Calculator JWT Decoder & Validator Blockchain Transaction Fee Calculator Database Query Cost Analyzer

Related Articles

Apr 1, 2026 · 12 min read

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.

Apr 1, 2026 · 13 min read

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.

Mar 28, 2026 · 12 min read

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.

Mar 28, 2026 · 14 min read

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.

Mar 28, 2026 · 18 min read

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.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • ⚡ AI Code Review, Doc Generator & SQL Builder
  • ⚡ All premium templates & early access
  • ⚡ Member discounts on Gumroad products
Start Free Trial →

$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.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro — $79 →

MIT licensed · Instant download · No subscription

See what's included → Browse all deals →