Search code examples
neo4jcyphergraph-databasespy2neo

How to create conditional edge among nodes in neo4j?


I am trying to create edges between nodes that share properties in neo4j. Each node has 5 properties say a,b,c,d,e. If 2 nodes share only property 'a' then edge will have name as 'a'. If 2 nodes share properties b,d,e then edge will have name as 'bde'. For each pair, if they share properties then ,I want to create a single edge only. Thanks.


Solution

  • This query should create a FOO relationship with the name of a property that has the same value between every pair of nodes (that share any property values):

    MATCH (m), (n)
    WHERE ID(m) < ID(n)
    WITH m, n, [x IN KEYS(m) WHERE m[x] = n[x] | x] AS common_keys
    FOREACH (k IN common_keys | CREATE (m)-[:FOO {name: k}]->(m))
    

    The WHERE ID(m) < ID(n) clause prevents m and n from being the same node, and also prevents duplicate evaluation of the same pair.

    [UPDATE]

    If you want only a single FOO relationship between 2 nodes, even if they share multiple property values, then this query should work:

    MATCH (m), (n)
    WHERE ID(m) < ID(n)
    WITH m, n,
       REDUCE(s = '', k IN KEYS(m) | CASE m[k] WHEN n[k] THEN s + k ELSE s END) AS common_keys
    WHERE common_keys <> ''
    CREATE (m)-[:FOO {name: common_keys}]->(m)