Merge multiple nodes/relationship subgraphs from table

Dear colleagues,

I'm struggling to structure a cypher query capable of merging nodes/relationship subgraphs in a greater graph.

Basically, I have a hierarchical tree structure in my tabular dataset:

Env Type Animal Action
sky bird woodpecker eat
sky raptor eagle hunt
land feline lion run
land reptile snake sleep
water cetacean whale eat
water fish barracuda swin

I would like commit merge operations row by row with a CYPHER query in which I'd be able to preserve hierarchical level uniquenesses and map tree leaves with the "Action" column.

A possible subgraph for the data excerpt (first row) would be something like:


I can sort of build this structure by merging with multiple match/merge operations but I'm afraid of overcomplicating things and I believe I could do the same with less operations. Runing merge with the whole subgraph creates the same nodes/relationships multiple times once merge creates a new subgraph for the entire pattern. I'd like to avoid this behavior.

Hence, is that a way to build a graph for this hierarchical structure by iterating over the rows of my dataset and merging nodes/relationships keeping level uniquenesses?

If you MERGE each node and relationship separately you should get what you want:

// assume loading with row as the exposed variable:
MERGE (env:Env {name:row.Env})
MERGE (type:Type {name:row.Type})
MERGE (animal:Animal {name:row.Animal})
MERGE (action:Action {name:row.Action})
MERGE (env)<-[:LIVES_IN]-(type)
MERGE (type)<-[:IS_EXEMPLAR_OF]-(animal)
MERGE (animal)-[:DOES]->(action)

Of course you'd want to create indexes and/or unique constraints on the relevant labels/props to support quick merges of the nodes.

It's kinda my initial approach.

I solved the problem using paths (with py2neo). Thanks anyway.