Valkey: Example: Using Valkey search in Node.js

This documentation is part of the Search and JSON guide. You can view the complete guide here: Store and query JSON documents with the Valkey search module.

👋 Welcome to the Stackhero documentation!

Stackhero offers a ready-to-use Valkey cloud solution that delivers numerous advantages, including:

  • Valkey Admin web UI included.
  • Unlimited message size and transfers.
  • One-click updates for easy maintenance.
  • Optimal performance and enhanced security thanks to a private, dedicated infrastructure.

Save time and make your life easier: it only takes 5 minutes to try Stackhero's Valkey cloud hosting solution!

Because Valkey uses the same protocol as Redis, any Redis client is compatible. You can use this example with the official node-redis client:

import { createClient, SCHEMA_FIELD_TYPE } from 'redis';

const client = createClient({ url: process.env.STACKHERO_VALKEY_URL_TLS });
await client.connect();

// Create the index once at startup
try {
  await client.ft.create(
    'productsIndex',
    {
      name: SCHEMA_FIELD_TYPE.TEXT,
      brand: SCHEMA_FIELD_TYPE.TAG,
      price: SCHEMA_FIELD_TYPE.NUMERIC
    },
    { ON: 'HASH', PREFIX: 'product:' }
  );
} catch (error) {
  if (!error.message.includes('Index already exists')) {
    throw error;
  }
}

await client.hSet('product:1', { name: 'Espresso machine', brand: 'Bianca', price: '459' });

const results = await client.ft.search('productsIndex', '@brand:{Bianca} @price:[0 500]');
console.log(results.total, results.documents);

await client.quit();