Redis®*: 範例:使用 Node.js

此文件屬於搜尋與 JSON指南的一部分。請在此處查看完整指南:使用 Redis 查詢引擎高效儲存及查詢 JSON 文件

👋 歡迎瀏覽 Stackhero 文件!

Stackhero 提供即開即用的 Redis cloud 方案,帶來多項優勢,包括:

  • 已包含 Redis Commander 網頁介面
  • 無限訊息大小及傳輸量。
  • 一鍵輕鬆完成更新
  • 專屬私人基礎設施提供最佳效能及強大安全性

節省時間簡化您的工作流程:只需5分鐘即可體驗 Stackhero 的 Redis cloud hosting 方案!

import { createClient, SCHEMA_FIELD_TYPE } from 'redis';

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

// 啟動時建立索引
try {
  await client.ft.create(
    'productsIndex',
    {
      '$.name': { type: SCHEMA_FIELD_TYPE.TEXT, AS: 'name' },
      '$.brand': { type: SCHEMA_FIELD_TYPE.TAG, AS: 'brand' },
      '$.price': { type: SCHEMA_FIELD_TYPE.NUMERIC, AS: 'price', SORTABLE: true }
    },
    { ON: 'JSON', PREFIX: 'product:' }
  );
}
catch (error) {
  if (!error.message.includes('Index already exists')) {
    throw error;
  }
}

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

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

await client.quit();