Valkey: Example: Using Valkey search in Node.js
This documentation is part of the Search and JSON guide. View the full 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 provides a host of benefits, including:
Valkey Adminweb UI included.- Unlimited message size and transfers.
- Effortless updates with just a click.
- Optimal performance and robust security powered by a private, dedicated infrastructure.
Save time and simplify your life: 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();