Created
September 21, 2014 19:47
-
-
Save ikwattro/eb7190f3f142ed591e0e to your computer and use it in GitHub Desktop.
Cloning subtree of graph in PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$clearQuery = 'MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE r,n'; | |
$setupQuery = "CREATE (root:Root) | |
CREATE (n1:Child {id:'left1'})-[:CHILD_OF]->(root) | |
CREATE (n2:Child {id:'right1'})-[:CHILD_OF]->(root) | |
CREATE (n3:Child {id:'left2'})-[:CHILD_OF]->(n1) | |
CREATE (n4:Child {id:'left3'})-[:CHILD_OF]->(n3)"; | |
$client->sendCypherQuery($clearQuery); | |
$client->sendCypherQuery($setupQuery); | |
$matchQuery = "MATCH (n:Child {id:'left1'})<-[r:CHILD_OF*]-(children), (n2:Child {id:'right1'}) RETURN n, n2, r, children"; | |
$results = $client->sendCypherQuery($matchQuery, array(), null, array('row', 'graph')); | |
$result = json_decode($results, true); | |
$left1NodeID = null; | |
$right1NodeID = null; | |
$nodes = array(); | |
$newIds = array(); | |
$rels = array(); | |
$cloneQuery = ''; | |
$parameters = array(); | |
foreach ($result['results'][0]['data'] as $id => $incr) { | |
foreach ($incr['graph']['nodes'] as $node) { | |
$nodes[] = $node; | |
} | |
foreach ($incr['graph']['relationships'] as $rel) { | |
$rels[] = $rel; | |
} | |
} | |
foreach ($nodes as $node) { | |
// Skip Left1 node as it is already created, but get the left1 node internal id for modifying relationship | |
// Assign also new identifiers for (nxxx:Child) so we can refert to them for creating relationships | |
if ($node['properties']['id'] === 'left1' || $node['properties']['id'] === 'right1') { | |
if (null === $left1NodeID && $node['properties']['id'] === 'left1') { | |
$left1NodeID = $node['id']; | |
$newIds[$left1NodeID] = 'n'.uniqid(); | |
} elseif (null === $left1NodeID && $node['properties']['id'] === 'right1') { | |
$right1NodeID = $node['properties']['id']; | |
} | |
} else { | |
if (isset($parameters['props'.$node['id']])) { | |
continue; | |
} | |
$newIds[$node['id']] = 'n'.uniqid(); | |
$labels = !empty($node['labels']) ? ':'.implode(':', $node['labels']) : null; | |
$parameters['props'.$node['id']] = $node['properties']; | |
$cloneQuery .= 'CREATE ('.$newIds[$node['id']].$labels.' {props'.$node['id'].'})'; | |
} | |
} | |
foreach ($rels as $rel) { | |
$labels = isset($rel['type']) ? ':'.$rel['type'] : null; | |
$cloneQuery .= 'MERGE ('.$newIds[$rel['startNode']].')-['.$labels.']->('.$newIds[$rel['endNode']].')'; | |
} | |
$endQuery = 'MATCH ('.$newIds[$left1NodeID].':Child {id:\'right1\'}) ' . $cloneQuery; | |
$newResult = $client->sendCypherQuery($endQuery, $parameters); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment