Search code examples
graphneo4jcypher

Can Neo4j automatically detect relationships between uploaded entities without a separate file containing only relationships?


Is it possible for Neo4j to detect relationships between entities without uploading a file which containing only relationships?

When I use Neo4j, first I create nodes by upload files that contain the entities, and then create the relationship among the nodes by a file (or files) that defines the relationships between the entities. Would it be possible to have Neo4j detect the relationships without uploading the relationship file(s)? As an example, we have two entities that have already been indexed and uploaded as follows: A including: A.ID, A.Year, A.Name B including: B.ID, B.Year, B.Name Would it be possible to detect a relationship between A and B based on A.ID=B.ID AND A.Year<=B.Year?


Solution

  • [UPDATED]

    You can do something like this:

    MATCH (a:Foo), (b:Foo)
    WHERE a <> b AND a.ID = b.ID AND (a.Year < b.Year OR (a.Year = b.Year AND id(a) < id(b)))
    CREATE (a)-[:BAR]->(b)
    

    Notes:

    1. To speed up this query, you should consider creating either an index or uniqueness constraint on :Foo(ID).
    2. To avoid creating a relationship from a Foo node to itself, we specify the a <> b condition.
    3. The a.Year <= b.Year condition allows equal Year values, so the same pair of Foo nodes can be matched twice (as a/b, and as b/a). So we specify the (a.Year = b.Year AND ID(a) < ID(b)) condition to avoid creating 2 relationships between the same pair of nodes in opposite directions. The id function returns the native ID, not your ID property.
    Final tweak

    While the above query works, we don't actually need to specify the a <> b condition as stated in Note #2, since the code mentioned in Note #3 is sufficient to enforce that condition. So, you can omit a <> b AND from the query.