Sorting hierarchical data by property when using apoc.convert.toTree

Viewed 911

New to Neo4j and I've tried various approaches with both Cypher and APOC based on similar questions asked on here but no luck since none are sort-tree combos. Let's say I have some hierarchical data that is just a bunch of root nodes with children and all nodes have the property 'name'. As of right now (with query below), when displaying the result by name, my data resembles:

zxcv
  rtyu
asdf
  qwer
    wert
  bbbb
    fghj
    yuio

What can I add to the following query that will sort by name such that the entire tree is sorted?

MATCH p=(n:Code)-[:HAS_CHILD*]->(m)
WHERE NOT ()-[:HAS_CHILD]->(n)
WITH COLLECT(p) AS ps
CALL apoc.convert.toTree(ps) yield value
RETURN value

If I tack on SORT BY value.name it only sorts the root nodes since that is what is at the top of what is returned. Can't figure out how/where to sort the nodes before collecting, or when I did then I couldn't figure out how to make the collection afterward. Happy to use apoc.coll.sortNodes, apoc.coll.sort, etc., but can't quite figure out how to work them in.

Update

This gets a little closer but still only sorting the root

MATCH (n:Code)-[:HAS_CHILD*]->(m)
WHERE NOT ()-[:HAS_CHILD]->(n)
WITH n
ORDER BY n.name
MATCH p=(n:Code)-[:HAS_CHILD*]->(m)
WHERE NOT ()-[:HAS_CHILD]->(n)
WITH COLLECT (p) AS ps
CALL apoc.convert.toTree(ps) yield value
RETURN value
1 Answers
Related