Extracting subgraph into JSON format

Okay, so you want JSON output of a list of nodes (all properties + label, assuming only a single label per node in your model), and a list of relationships (all properties + type, + start and end nodes but only the label and key for each node.

This query should do the trick.

MATCH (n) 
WHERE n.user_id='0000001'
CALL apoc.path.subgraphAll(n, {maxLevel:1}) YIELD nodes, relationships
WITH [node in nodes | node {.*, label:labels(node)[0]}] as nodes, 
     [rel in relationships | rel {.*, fromNode:{label:labels(startNode(rel))[0], key:startNode(rel).key}, toNode:{label:labels(endNode(rel))[0], key:endNode(rel).key}}] as rels
WITH {nodes:nodes, relationships:rels} as json
RETURN apoc.convert.toJson(json)

Keep in mind you really should be using labels in your query, corresponding with the index you SHOULD have on the label + user_id property for fast lookup of your start node.

Next we use apoc.path.subgraphAll(), as this will yield lists of distinct nodes and distinct relationships. You can adjust maxLevel to whatever depth you want (or leave off for unlimited depth). You didn't specify a type or direction for your match, but if you have restrictions here you can add them with a relationshipFilter config parameter in the procedure call.

Since nodes don't output their labels when returning them, and same with types for relationships, we need to project out the desired properties first (including start and end nodes for relationships), stuff those into a map, then convert it to JSON.

2 Likes