有许多关系和节点。我们想从Neo4j数据库中以对象数组的形式检索数据。
如果我们匹配为:
MATCH (user: user {name:"x"})
OPTIONAL MATCH (user)-[r]->(item)
OPTIONAL MATCH (item)-[s]->(approver)
RETURN user, item, approver
我们得到的结果为:
[{user:{properties:{name:"x"}}, item:{properties:{name:"abc"}}, approver:{properties:{name:"a"}}},
{user:{properties:{name:"x"}}, item:{properties:{name:"abc"}}, approver:{properties:{name:"b"}]}},
{user:{properties:{name:"x"}}, item:{properties:{name:"xyz"}}, approver:{properties:{name:"c"}}},
{user:{properties:{name:"x"}}, item:{properties:{name:"xyz"}}, approver:{properties:{name:"d"}}} }]
我们需要获得类似于结果,以降低复杂性,同时在客户端处理巨大的关系:
[{user:{properties:{name:"x"}}, item:{properties:{name:"abc"}}, approvers:[{properties:{name:"a"}}, {properties:{name:"b"}}]},
{user:{properties:{name:"x"}}, item:{properties:{name:"xyz"}}, approvers:[{properties:{name:"c"}}, {properties:{name:"d"}}] }]
这个怎么做?
最佳答案
听起来您需要收集列表中的项目。尝试这个:
MATCH (user: user {name:"x"})
OPTIONAL MATCH (user)-[r]->(item)
RETURN user, COLLECT(item)
您可能需要花一些时间浏览Cypher备忘单,并检查COLLECT()函数以及列表操作。
编辑
好像您在说明中添加了对项目的潜在批准者。在这种情况下,您似乎想按用户和项目分组,并有一组批准者。
MATCH (user: user {name:"x"})
OPTIONAL MATCH (user)-[r]->(item)
OPTIONAL MATCH (item)-[s]->(approver)
RETURN user, item, COLLECT(approver) AS approvers