0

Suppose I have a JSON file like this:

{
    data: [
        {
            name: "1",
            description: "Node 1",
            parent: ""
        },
        {
            name: "2",
            description: "Node 2",
            parent: "1"
        },
        {
            name: "3",
            description: "Node 3",
            parent: "1"
        },
        {
            name: "4",
            description: "Node 4",
            parent: "3"
        },
    ]
}

I wish to create the nodes and the relationships in the same query using neo4j-driver for Node.js. Suppose I have that JSON file loaded in a variable called data. I've tried this, but haven't been able to create the relationships:

const result = await session.run(`
    UNWIND $nodes AS node
    MERGE (n:Node { name: node.name, description: node.description })
    WITH $nodes AS relationships
    UNWIND relationships AS relationship
    MATCH(c:Node { name: relationship.name }), (p:Node { name: relationship.parent })
    MERGE (p)-[:PARENT_OF]->(n)
`, { nodes: data });

I get two relationships from 1 to a null node and from 2 to a null node.

Is there any way to do this or should I first create the nodes and then in another query create the relationships.

Thank you

1 Answer 1

1

You can do it in a single run:

UNWIND $nodes AS node
MERGE (n:Node { name: node.name })
ON CREATE SET n.description = node.description
FOREACH ( i IN (CASE WHEN node.parent<>'' THEN [1] ELSE [] END) |
     MERGE (p:Node { name: node.parent }) 
     MERGE (p)-[:PARENT_OF]->(n)
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.