bornytm
bornytm

Reputation: 813

Batch node relationship creation in cypher/neo4j

What is the most efficient way to break down this CREATE cypher query?

The end pattern is the following:

(newTerm:term)-[:HAS_META]->(metaNode:termMeta)

In this pattern this is a single newTerm node and about ~25 termMeta nodes. The HAS_META relationship will have a single property (languageCode) that will be different for each termMeta node.

In the application, all of these nodes and relationships will be created at the same time. I'm trying to determine the best way to add them.

Is there anyway to add these without having to have perform individual query for each TermMeta node?

I know you can add multiple instances of a node using the following query format:

 "metaProps" : [ 
            {"languageCode" : "en", "name" : "1", "dateAdded": "someDate1"}, 
            {"languageCode" : "de", "name" : "2", "dateAdded": "someDate2"},
            {"languageCode" : "es", "name" : "3", "dateAdded": "someDate3"}, 
            {"languageCode" : "fr", "name" : "3", "dateAdded": "someDate4"}
        ]

But you can only do that for one type of node at a time and there (as far as I can tell) is no way to dynamically add the relationship properties that are needed.

Any insight would be appreciated.

Upvotes: 0

Views: 904

Answers (2)

Nischal Kumar
Nischal Kumar

Reputation: 522

Select and name each vertex differently and then create relations using it. For ex

match (n:Tag), (m:Account), (l:FOO) CREATE (n)-[r:mn]->(m),(m)-[x:ml]->(l)
match (n:Tag{a:"a"}), (m:Account{b:"x"}), (l:FOO) CREATE (n)-[r:mn]->(m),(m)-[x:ml]->(l)

Upvotes: 0

Jon Packer
Jon Packer

Reputation: 123

There's no really elegant way to do it, as far as I can tell—from your example, I'm assuming you're using parameters. You can use a foreach to loop through the params and do a create on each one, but it's pretty ugly, and requires you to explicitly specify literal maps of your properties. Here's what it would look like for your example:

CREATE (newTerm:term)
FOREACH ( props IN {metaProps} | 
  CREATE newTerm-[:HAS_META {languageCode: props.languageCode}]->
           (:termMeta {name: props.name, dateAdded: props.dateAdded})
)
WITH newTerm
MATCH newTerm-[rel:HAS_META]->(metaNode:termMeta)
RETURN newTerm, rel, metaNode

If you don't need to return the results, you can delete everything after the FOREACH.

Upvotes: 3

Related Questions