Redis®*: 示例:Node.js 使用方法
本文档属于搜索与 JSON指南的一部分。您可以在此处查看完整指南:使用 Redis 查询引擎高效存储和查询 JSON 文档。
👋 欢迎查阅 Stackhero 文档!
Stackhero 提供即开即用的 Redis cloud 解决方案,带来多项优势,包括:
- 集成
Redis CommanderWeb 管理界面。- 无限制的消息大小与传输。
- 一键完成升级,操作便捷。
- 基于专属私有基础设施,实现卓越性能与强大安全性。
节省时间,简化运维:仅需 5 分钟即可体验 Stackhero 的 Redis cloud 托管 方案!
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();