Returning a new graph with Cypher or OpenCypher

Viewed 97

This question comes from experience with the CONSTRUCT operator in SPARQL, which allows to take variable bindings in a graph query and return a new graph as result.

Is there anything like that in Cypher/OpenCypher?

I mean, suppose you have:

react1 - [part-of] -> pathway1
mol1 - [consumed-by] -> react1
mol2 - [consumed-by] -> react1
mol3 - [produced-by] -> react1

I'd like to return a simplified graph like:

pathway1 - [input] - mol1
pathway1 - [input] - mol2
pathway1 - [output] - mol3

Note that I've already played with WITH/COLLECT/UNWIND to return JSON structures very similar to the graph above, but this approach is much more difficult to write.

1 Answers

You can experiment with virtual relationships using the APOC library.

For example, you have the following test data:

MERGE p1 = (R:react {name:'react_1'})-[:`part-of`] ->(:pathway {name: 'pathway_1'})
MERGE p2 = (:mol {name: 'mol_1'})-[:`consumed-by`]->(R)
MERGE p3 = (:mol {name: 'mol_2'})-[:`consumed-by`]->(R)
MERGE p4 = (:mol {name: 'mol_3'})-[:`produced-by`]->(R)
RETURN *

Then you can try the following query:

MATCH (R:react)
MATCH (R)-[rp:`part-of`]-(p:pathway)
MATCH (m:mol)-[mr]-(R)
WITH p, m, mr,
     CASE WHEN type(mr) = 'consumed-by' 
          THEN {from: p, type: "input",  props: properties(mr), to: m}
          WHEN type(mr) = 'produced-by'
          THEN {from: m, type: "output", props: properties(mr), to: p}
     END AS vRel
WITH vRel WHERE vRel IS NOT NULL
CALL apoc.create.vRelationship(
  vRel.from,
  vRel.type,
  vRel.props,
  vRel.to
) YIELD rel
RETURN vRel.from, rel, vRel.to

What will give the following result:

enter image description here

Related