Skip to main content
This section demonstrates a complete workflow: creating an index, adding data, and searching.
import { Redis, s } from "@upstash/redis";

const redis = Redis.fromEnv();

// Create an index for product data stored as JSON
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("F64"),
    inStock: s.boolean(),
  }),
});

// Add some products (standard Redis JSON commands)
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,
});

await redis.json.set("product:3", "$", {
  name: "Coffee Maker",
  description: "Programmable coffee maker with built-in grinder",
  category: "kitchen",
  price: 89.99,
  inStock: false,
});

// Wait for indexing to complete (optional, for immediate queries)
await index.waitIndexing();

// Search for products
const wirelessProducts = await index.query({
  filter: { description: "wireless" },
});

for (const product of wirelessProducts) {
  console.log(product);
}

// Search with more filters
const runningProducts = await index.query({
  filter: { description: "running", inStock: true },
});

for (const product of runningProducts) {
  console.log(product);
}

// Count matching documents
const count = await index.count({ filter: { price: { $lt: 150 } } });
console.log(count);