FranG91
FranG91

Reputation: 83

Create relation between nodes with same property in Neo4J

I want to create a new relation between two actors that have been born in the same year.

I'm running this query, but it seems not working:

MATCH (a:Person)
with a AS personA
MATCH (b:Person)
with b AS personB
WHERE personA.born = personB.born AND personA <> personB
CREATE UNIQUE (personA)-[:HAS_SAME_AGE {sameAge: "Has same age"}]-(personB)

Thank you a lot.

Upvotes: 0

Views: 1567

Answers (2)

cybersam
cybersam

Reputation: 67044

  1. In your query, the second WITH clause did not include personA, so that variable was dropped.
  2. But both WITH clauses are not even needed in your query, and therefore should be omitted (for clarity, if nothing else).
  3. Your query could also very easily just have a single MATCH clause that uses the personA and personB variable names directly.
  4. Your WHERE clause would allow the same pair of Person nodes to be processed twice (in reverse order). You can ensure that the same pair is processed only once by using, for instance, ID(personA) < ID(personB) instead of personA <> personB.
  5. CREATE UNIQUE is deprecated, and MERGE should be used instead.
  6. MERGE does not require you to specify the directionality of a relationship -- it can automatically assign one for you. This is appropriate if you want to consider the relationship as undirected (which is true in your case).

Here is a query that takes care of all the above items:

MATCH (personA:Person), (personB:Person)
WHERE ID(personA) < ID(personB) AND personA.born = personB.born
MERGE (personA)-[:HAS_SAME_AGE {sameAge: "Has same age"}]-(personB)

Note: You may want to give sameAge a boolean value (true or false). Or, better yet, just eliminate sameAge entirely, since the HAS_SAME_AGE relationship would only exist if the 2 related nodes have the same age anyway.

Upvotes: 1

Rajendra Kadam
Rajendra Kadam

Reputation: 4052

This query will create empty nodes and create relationships between the empty node and given node.

The issue here is 'personA' is not in the scope of 'CREATE UNIQUE'.

You need to pass it along with 'personB' in second 'with' clause.

CREATE UNIQUE is not supported in new versions of Cypher use MERGE instead.

MATCH (a:Person)
with a AS personA
MATCH (b:Person)
with personA, b AS personB
WHERE personA.born = personB.born AND personA <> personB
CREATE UNIQUE (personA)-[:HAS_SAME_AGE {sameAge: "Has same age"}]->(personB)

Upvotes: 0

Related Questions