简体   繁体   中英

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.

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 .

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM