简体   繁体   中英

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.

  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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM