inersha
inersha

Reputation: 462

Neo4j: How to speed up a query with multiple merges?

I have a query that creates a node, and relates a large number of nodes to it.

Example:

CREATE (target :x {index:'a'})
WITH target
MERGE (x1:x {index:'1'}) MERGE (x1)-[:r]->(target)
MERGE (x2:x {index:'2'}) MERGE (x2)-[:r]->(target)
MERGE (x3:x {index:'3'}) MERGE (x3)-[:r]->(target)
...
MERGE (x1000:x {index:'1000'}) MERGE (x1000)-[:r]->(target)

I have already set an indexes with CREATE CONSTRAINT ON (x:x) ASSERT x.index IS UNIQUE. However, this query is currently taking ~45 minutes to complete.

Is there anything I can do to speed it up? Is adding more CPU power the only option from here?

Upvotes: 0

Views: 220

Answers (1)

Tore Eschliman
Tore Eschliman

Reputation: 2507

When you stack MERGE or MATCH statements like that, you can end up with performance issues (related to result rows). For a case like this, use an iterative loop:

CREATE (target :x {index:'a'})
WITH target
FOREACH(i IN RANGE(1, 1000)|
    MERGE (a:x {index: toString(i)})
    MERGE (a) - [:r] -> (target)  )

Upvotes: 3

Related Questions