递归neo4j查询

时间:2013-04-23 13:49:30

标签: neo4j cypher

我有一个图表,其中包含无限级别的类别和子类别以及子子类别。 如何在一个密码查询中获取所有这些分层数据?

我目前有这个查询:

START category=node:categoryNameIndex(categoryName = "category") 
MATCH path = category <-        [rel:parentCategory] - subcategory 
RETURN category, collect(subcategory);

这给了我以下结果:

| category                                                                                               | collect(subcategory)                                                                                                                                                                                           |
==> +-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
==> | Node[26]{categoryName:"Test2",categoryDescription:"testDesc",imageUrl:"testUrl",imageName:"imageName"} | [Node[25]{categoryName:"Test1",categoryDescription:"testDesc",imageUrl:"testUrl",imageName:"imageName"}]                                                                                                       |
==> | Node[1]{categoryName:"Test1",categoryDescription:"testDesc",imageUrl:"testUrl",imageName:"imageName"}  | [Node[26]{categoryName:"Test2",categoryDescription:"testDesc",imageUrl:"testUrl",imageName:"imageName"},Node[2]{categoryName:"Test2",categoryDescription:"testDesc",imageUrl:"testUrl",imageName:"imageName"}] |

我正在使用node-neo4j。 我将以json格式给出一个我想要的例子。

[{
    "categoryName": "Test2",
    "categoryDescription": "testDesc",
    "imageUrl": "testUrl",
    "children": [{
        "categoryName": "Test1",
        "categoryDescription": "testDesc",
        "imageUrl": "testUrl",
        "children" :  [{
            "categoryName": "Test1",
            "categoryDescription": "testDesc",
            "imageUrl": "testUrl"
        }]
    }]
}]

我有可能吗?我知道我总是可以通过编程方式或使用多个查询来完成。但如果可以在单个查询中完成它将非常有用。

1 个答案:

答案 0 :(得分:3)

您可以通过在关系类型之后添加*来匹配任意深度的路径:

START category=node:categoryNameIndex(categoryName = "category") 
MATCH path = category <-[rel:parentCategory*]- subcategory 
RETURN category, collect(subcategory);

您也可以选择指定最小和/或最大路径长度:

START category=node:categoryNameIndex(categoryName = "category") 
MATCH path = category <-[rel:parentCategory*2..5]- subcategory 
RETURN category, collect(subcategory);

参见此处的参考资料:

http://docs.neo4j.org/chunked/milestone/query-match.html#match-variable-length-relationships