Mary1980
Mary1980

Reputation: 3

Neo4J Movie-Graph - actors with same age

I want to analyze in Neo4J with the movie data set provided (: play movie-graph) those actors who were born in the same year, and then perform a query that allows me to obtain which actors of the same age have worked together. To do this, I have tried to create a relationship type "HAS_SAME_AGE" in the database between actors who were born in the same year, but it gave me an error and I don't know how to continue.

This is what I have written:

MATCH (a:Person),(b:Person) WHERE a.born=b.born WITH a AS PersonA, b AS PersonB MERGE (PersonA)- [:HAS_SAME_AGE]-(PersonB)

Can someone help me fill in the correct code? Any help would be appreciated!

Upvotes: 0

Views: 212

Answers (1)

cybersam
cybersam

Reputation: 67019

  1. It is bad practice to add redundant data (eg, relationships that duplicate information you can already get from the DB in other ways) unless there is a really good reason for it (eg, you cannot meet a strict performance requirement otherwise).

    It is easy to get all actors born in the same year without a relationship. For example:

    MATCH (p:Person)
    RETURN p.born AS year, COLLECT(p) AS actors
    

    So, unless you have a critical need to get the same information a little faster, you should just use the above kind of query instead of storing redundant relationships.

  2. However, if you really do need to add the relationships, you can do something like this:

    MATCH (p:Person)
    WITH p.born AS year, COLLECT(p) AS ps
    UNWIND apoc.coll.combinations(ps, 2) AS pair
    WITH pair[0] AS p1, pair[1] AS p2
    MERGE (p1)-[:HAS_SAME_AGE]-(p2)
    

    The APOC function apoc.coll.combinations is used to generate distinct pairs of actors born in the same year.

Upvotes: 0

Related Questions