1. Create Index
- TypeScript
- Python
- Redis CLI
import { Redis, s } from "@upstash/redis";
const redis = Redis.fromEnv();
const index = await redis.search.createIndex({
name: "products",
dataType: "json",
prefix: "product:",
schema: s.object({
name: s.string(),
description: s.string(),
category: s.string().noTokenize(),
price: s.number(),
inStock: s.boolean(),
}),
});
from upstash_redis import Redis
redis = Redis.from_env()
index = redis.search.create_index(
name="products",
data_type="json",
prefix="product:",
schema={
"name": "TEXT",
"description": "TEXT",
"category": {"type": "TEXT", "notokenize": True},
"price": "F64",
"inStock": "BOOL",
},
)
SEARCH.CREATE products ON JSON PREFIX 1 product: SCHEMA name TEXT description TEXT category TEXT NOTOKENIZE price F64 FAST inStock BOOL
2. Add Data
Add data using standard Redis JSON commands. Any key matching the index prefix will be automatically indexed.- TypeScript
- Python
- Redis CLI
await redis.json.set("product:1", "$", {
name: "Wireless Headphones",
description:
"Premium noise-cancelling wireless headphones with 30-hour battery life",
category: "electronics",
price: 199.99,
inStock: true,
});
await redis.json.set("product:2", "$", {
name: "Running Shoes",
description: "Lightweight running shoes with advanced cushioning technology",
category: "sports",
price: 129.99,
inStock: true,
});
redis.json().set("product:1", "$", {
"name": "Wireless Headphones",
"description": "Premium noise-cancelling wireless headphones with 30-hour battery life",
"category": "electronics",
"price": 199.99,
"inStock": True,
})
redis.json().set("product:2", "$", {
"name": "Running Shoes",
"description": "Lightweight running shoes with advanced cushioning technology",
"category": "sports",
"price": 129.99,
"inStock": True,
})
index.wait_indexing()
JSON.SET product:1 $ '{"name": "Wireless Headphones", "description": "Premium noise-cancelling wireless headphones with 30-hour battery life", "category": "electronics", "price": 199.99, "inStock": true}'
JSON.SET product:2 $ '{"name": "Running Shoes", "description": "Lightweight running shoes with advanced cushioning technology", "category": "sports", "price": 129.99, "inStock": true}'
SEARCH.WAITINDEXING products
3. Search Data
- TypeScript
- Python
- Redis CLI
const results = await index.query({
filter: { description: "wireless" },
});
const count = await index.count({
filter: { price: { $lt: 150 } },
});
results = index.query(filter={"description": "wireless"})
count = index.count(filter={"price": {"$lt": 150}})
SEARCH.QUERY products '{"description": "wireless"}'
SEARCH.COUNT products '{"price": {"$lt": 150}}'