Valkey: 示例:在 Node.js 中使用 Valkey 搜索

本文档属于搜索与 JSON指南的一部分。您可以在此处查看完整指南:使用 Valkey 搜索模块存储和查询 JSON 文档

👋 欢迎查阅 Stackhero 文档!

Stackhero 提供即开即用的 Valkey 云端 解决方案,带来多项优势,包括:

  • 集成 Valkey Admin Web 管理界面
  • 无限制的消息大小与传输。
  • 一键完成升级,操作便捷。
  • 基于专属私有基础设施,实现卓越性能与强大安全性

节省时间简化您的工作流程:只需 5 分钟即可体验 Stackhero 的 Valkey 云托管 方案!

由于 Valkey 与 Redis 协议兼容,任何 Redis 客户端都可直接使用。以下示例适用于官方 node-redis 客户端

import { createClient, SCHEMA_FIELD_TYPE } from 'redis';

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

// 启动时仅需创建一次索引
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();