Gabriel Nogueira
Gabriel Nogueira

Reputation: 11

Using UNWIND to insert general entities in Neo4J

A while ago I made this post about a matching issue with similar nodes when inserting general entities in the Neo4J database. The proposed solution was not to use MERGE and instead do something like:

OPTIONAL MATCH (p:Position)
WHERE PROPERTIES(p) = $props
CALL {
  WITH p
  WITH p WHERE p IS NULL
  CREATE (q:Position)
  SET q = $props
  RETURN q AS result
  UNION
  WITH p
  WITH p WHERE p IS NOT NULL
  RETURN p AS result
}
RETURN ID(result)

Now I want to use UNWIND to create multiple entites at once like this

UNWIND $positions as props
OPTIONAL MATCH (p:Position)
WHERE PROPERTIES(p) = props
CALL {
  WITH p
  WITH p WHERE p IS NULL
  CREATE (q:Position)
  SET q = $props
  RETURN q AS result
  UNION
  WITH p
  WITH p WHERE p IS NOT NULL
  RETURN p AS result
}
RETURN ID(result)

However, when there are equal properties in the $positions list, like this:

[{symbol: "xxx", name: "yyy", location:"zzz", effective: false},
{symbol: "xxx", name: "yyy", location:"zzz", effective: false}]

Then, two equal nodes are created. How can I prevent de creation of duplicate nodes?

Upvotes: 1

Views: 45

Answers (1)

cybersam
cybersam

Reputation: 66999

You just need to use WITH DISTINCT props to get rid of the duplicates:

UNWIND $positions as props
WITH DISTINCT props
OPTIONAL MATCH (p:Position)
WHERE PROPERTIES(p) = props
CALL {
  WITH p, props
  WITH p, props WHERE p IS NULL
  CREATE (q:Position)
  SET q = props
  RETURN q AS result
  UNION
  WITH p
  WITH p WHERE p IS NOT NULL
  RETURN p AS result
}
RETURN ID(result)

This query also fixes a few other issues in your query.

Upvotes: 0

Related Questions