Valkey: 範例:在 Node.js 使用 Valkey 搜尋
本文件是搜尋與 JSON指南的一部分。請在此處查看完整指南:使用 Valkey 搜尋模組儲存與查詢 JSON 文件。
👋 歡迎來到 Stackhero 文件中心!
Stackhero 提供即時可用的 Valkey cloud 解決方案,帶來多項優勢,包括:
- 內建
Valkey Admin網頁管理介面。- 無限制的訊息大小與傳輸量。
- 一鍵輕鬆完成更新。
- 以專屬私有基礎架構提供最佳效能與強大安全性。
節省時間、簡化您的工作流程:只需 5 分鐘即可體驗 Stackhero 的 Valkey cloud hosting 解決方案!
Valkey 採用與 Redis 相同的協定,因此任何 Redis 客戶端皆可相容。您可搭配官方 node-redis client 使用下列範例:
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();