You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Node版Redis OM对Redis搜索结果执行聚合及嵌套对象转换?

使用Node版Redis OM实现聚合与嵌套对象转换

一、Redis端聚合(推荐,性能更优)

Redis OM提供Aggregation API可直接在Redis服务器端完成聚合操作,避免大量数据传输到客户端后再处理。

步骤1:定义实体与仓库

先基于Redis OM定义对应实体和仓库(需匹配你的数据结构):

const { Entity, Schema, Repository } = require("redis-om");

class SchemaTest1 extends Entity {}
const schemaTest1Schema = new Schema(SchemaTest1, {
  category: { type: "string" },
  name: { type: "string" },
  value: { type: "number" }
  // 补充你的其他字段定义
});

const repository = client.fetchRepository(schemaTest1Schema);
await repository.createIndex(); // 确保索引已创建

步骤2:构建聚合查询

通过链式调用实现过滤、分组与嵌套转换:

const aggregatedResult = await repository.aggregate()
  .where(key).equals(value) // 匹配原搜索条件 @${key}:${value}
  .groupBy("category") // 替换为你的分组依据字段
  .reduceToList("items", "$") // 将每组文档存入items数组,形成嵌套结构
  .execute();

// 返回结果示例:
// [
//   { category: "groupA", items: [{...}, {...}] },
//   { category: "groupB", items: [{...}] }
// ]

二、客户端聚合转换(基于已获取的搜索结果)

如果已通过ft.search拿到原始结果,可在Node.js端用数组方法处理为嵌套结构:

步骤1:提取原始数据

从搜索结果中提取对象数组:

const searchResult = await client.ft.search('idx:schemaTest1', `@${key}:${value}`);
const rawData = searchResult.documents.map(doc => doc.value);

步骤2:用reduce实现分组嵌套

以按category字段分组为例,将平级数组转为嵌套结构:

// 替换category为你的实际分组字段
const nestedData = rawData.reduce((acc, currentItem) => {
  const groupField = currentItem.category;
  const existingGroup = acc.find(item => item.category === groupField);
  
  if (existingGroup) {
    existingGroup.items.push(currentItem);
  } else {
    acc.push({
      category: groupField,
      items: [currentItem]
    });
  }
  return acc;
}, []);

若需多层嵌套,可多次调用reduce或编写递归逻辑处理。


内容的提问来源于stack exchange,提问作者Lakshmi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 12:10:25