规范化查询结果

时间:2014-02-05 06:36:26

标签: neo4j cypher

我有一个设置,其中许多节点连接到多个节点。

当我获取某些路径时,连接到多个节点的那1个节点在查询结果中重复

MATCH (r:Red)
OPTIONAL MATCH (r:Red)-[rel]-(g:Grey)
RETURN ID(r), g.prop, rel.prop

返回

ID(r)   g.prop  rel.prop
1131    null    null
>1132   b       value1
>1132   b2      value2
>1132   b3      value3
1134    c       value4

然后我将其转换为可用的javascript数组/对象

results.forEach(function(result){
    Red.push({
        red: result['ID(r)'],
        Grey: {
            greyProp: result['g.prop'],
            greyRelation: result['r.prop']
        }
    });
});

生成

Red:
[
{"red":1131,"Grey":{"greyProp":null,"greyRelation":null}}
,
{"red":1132,"Grey":{"greyProp":"b","greyRelation":"value1"}}
,
{"red":1132,"Grey":{"greyProp":"b2","greyRelation":"value2"}}
,
{"red":1132,"Grey":{"greyProp":"b3","greyRelation":"value3"}}
,
{"red":1134,"Grey":{"greyProp":"c","greyRelation":"value4"}}
]

但我宁愿把它作为

Red:
[
{"red":1131,"Grey":{"greyProp":null,"greyRelation":null}}
,
{"red":1132,"Grey":
    [
        {"greyProp":"b","greyRelation":"value1"},
        {"greyProp":"b2","greyRelation":"value2"},
        {"greyProp":"b3","greyRelation":"value3"}
    ]
,
{"red":1134,"Grey":{"greyProp":"c","greyRelation":"value4"}}
]

我想不出办法做到这一点。当我从第一个查询的结果中创建对象时,是否需要再次运行查询?或者是否有一种更简单的方法可以做到这一点?

1 个答案:

答案 0 :(得分:1)

您可能想要这样做

MATCH (r:Red)
OPTIONAL MATCH (r:Red)-[rel]-(g:Grey)
RETURN ID(r), collect(g.prop) as g_prop, collect(rel.prop) as rel_prop

这会给你一些像

的结果
ID(r)   g_prop        rel_prop
1131    null          null
1132    [b,b2,b3]     [value1,value2,value3]
1134    c             value4

**根据laggingreflex指出的缺点。修改后的查询将在集合中的“NULL”字符串放置在没有找到rel道具的地方。(假设所有g.prop都是never null,以防它同样使用{{1} } case .. when}

collect(g.prop)

这会给你一些像

的结果
MATCH (r:Red)
OPTIONAL MATCH (r:Red)-[rel]-(g:Grey)
RETURN ID(r), collect(g.prop) as g_prop, collect(case when rel.prop is null then 'null' 
else rel.prop end) as rel_prop