问题
I have a graph which has categories and sub-categories and sub-sub-categories to indefinite level. How I can I get all this hierarchical data in one cipher query?
I currently have this query :
START category=node:categoryNameIndex(categoryName = "category")
MATCH path = category <- [rel:parentCategory] - subcategory
RETURN category, collect(subcategory);
Which gives me following result:
| 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"}] |
I am using node-neo4j. I will give an example of what I want in json format.
[{
"categoryName": "Test2",
"categoryDescription": "testDesc",
"imageUrl": "testUrl",
"children": [{
"categoryName": "Test1",
"categoryDescription": "testDesc",
"imageUrl": "testUrl",
"children" : [{
"categoryName": "Test1",
"categoryDescription": "testDesc",
"imageUrl": "testUrl"
}]
}]
}]
I this possible? I know I can always do it programmatically OR by using multiple queries. But it will very helpful if it can be done in a single query.
回答1:
You can match paths of arbitrary depth by adding a *
after the relationship type:
START category=node:categoryNameIndex(categoryName = "category")
MATCH path = category <-[rel:parentCategory*]- subcategory
RETURN category, collect(subcategory);
Optionally, you can also specify a minimum and/or maximum path length:
START category=node:categoryNameIndex(categoryName = "category")
MATCH path = category <-[rel:parentCategory*2..5]- subcategory
RETURN category, collect(subcategory);
See reference here:
http://docs.neo4j.org/chunked/milestone/query-match.html#match-variable-length-relationships
来源:https://stackoverflow.com/questions/16171064/recursive-neo4j-query