Cypher Query具有多个MATCH语句并返回COLLECT数组

时间:2015-09-16 19:48:57

标签: neo4j cypher

我遇到了一个特定的密码查询问题,我希望有人可以提供帮助。我正在尝试查询父级的不同关系类型,以便我可以返回一个响应,其中包含父级的id,name和node标签的一些键/值对,同时还返回一个子数组作为另一个键/值对返回相同的对象。孩子的数组来自第二关系MATCH集。当我运行它时,我在该数组中获得的元素数量远远大于与父元素的关系(大约100个元素而不是预期的三个元素)。

MATCH (n)-[relone:RELATIONSHIP_ONE]->(children_one),
      (n)-[reltwo:RELATIONSHIP_TWO]->(children_two)
WHERE n.id='839930493049039430'
RETURN n.id          AS id,
       n.name        AS name,
       labels(n)[0]  AS type,
       {
         keystring: {
           id: (n.id + '_all'),
           count: count(relone)
         }
       } AS rel_one_representation,
       COLLECT({ 
          name        : children_two.name
       }) AS rel_two_representation

这是我希望最终产生的json输出:

{
    "id"                        : "839930493049039430",
    "name"                      : "lorem",
    "type"                      : "epsim",
    "rel_one_representation"    : {
        "keystring"             : { 
            "id"                : "839930493049039430_all",
            "count"             : 7
        }
    },
    "rel_two_representation"    : [
        {
            "name"              : "barker"
        },
        {
            "name"              : "bird"
        },
        {
            "name"              : "tiki"
        }
    ]
}

提前感谢您提出的建议。

1 个答案:

答案 0 :(得分:3)

您的查询存在的问题是它返回了{strong> children_onechildren_two个节点的所有可能对的结果。这导致每个children_two节点重复N1次,其中N1是children_one个节点的数量。它还导致每个children_one节点重复N2次,其中N2是children_two个节点的数量。

解决方案1:

此方法使用WITH分隔两个MATCH子句,以避免“配对效应”。

MATCH (n)-[relone:RELATIONSHIP_ONE]->(children_one)
WHERE n.id='839930493049039430'
WITH n, COUNT(relone) AS cnt
MATCH (n)-[reltwo:RELATIONSHIP_TWO]->(children_two)
RETURN n.id AS id, n.name AS name, LABELS(n)[0] AS type, { keystring: { id: (n.id + '_all'), count: cnt }} AS rel_one_representation, COLLECT({ name : children_two.name }) AS rel_two_representation

解决方案2:

此方法使用DISTINCT关键字过滤掉重复项。

MATCH (n)-[relone:RELATIONSHIP_ONE]->(children_one),(n)-[reltwo:RELATIONSHIP_TWO]->(children_two)
WHERE n.id='839930493049039430'
RETURN n.id AS id, n.name AS name, LABELS(n)[0] AS type, { keystring: { id: (n.id + '_all'), count: COUNT(DISTINCT relone)}} AS rel_one_representation, COLLECT(DISTINCT { name: children_two.name }) AS rel_two_representation