0
votes

I am trying to make a Cypher query which makes 2 nodes and adds a relationship between them.

For adding a node I'm checking if the node is existing or not, if existing then I'm simply going ahead and setting a property.

// Query 1 for creating or updating node 1

MERGE (Kunal:PERSON)
ON CREATE SET
    Kunal.name = 'Kunal',
    Kunal.type = 'Person',
    Kunal.created = timestamp()
ON MATCH SET
    Kunal.lastUpdated = timestamp()
RETURN Kunal

// Query 2 for creating or updating node 2

MERGE (Bangalore: LOC)
ON CREATE SET
    Bangalore.name = 'Bangalore',
    Bangalore.type = 'Location',
    Bangalore.created = timestamp()
ON MATCH SET
    Bangalore.lastUpdated = timestamp()
RETURN Bangalore

Likewise I am checking if a relationship exists between the above created nodes, if not exists then creating it else updating its properties.

// Query 3 for creating relation or updating it.

MERGE (Kunal: PERSON { name: 'Kunal', type: 'Person' })
MERGE (Bangalore: LOC { name: 'Bangalore', type: 'Location' })
MERGE (Kunal)-[r:LIVES_IN]->(Bangalore)
ON CREATE SET
    r.duration = 36
ON MATCH SET
    r.duration = r.duration + 1 
RETURN *

The problem is these are 3 separate queries which will have 3 database calls when I run it via the Python driver. Is there a way to optimize these queries into a single query.

1

1 Answers

2
votes

Of course you can concatenate your three queries to one. In this case you can omit the first and second MERGE of your last query, because it is assured by the start of new query already.

MERGE (kunal:PERSON {name: ‘Kunal'})
ON CREATE SET
    kunal.type = 'Person',
    kunal.created = timestamp()
ON MATCH SET
    kunal.lastUpdated = timestamp()
MERGE (bangalore:LOC {name: 'Bangalore'})
ON CREATE SET
    bangalore.type = 'Location',
    bangalore.created = timestamp()
ON MATCH SET
    bangalore.lastUpdated = timestamp()
MERGE (kunal)-[r:LIVES_IN]->(bangalore)
ON CREATE SET
    r.duration = 36
ON MATCH SET
    r.duration = r.duration + 1 
RETURN *