1

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.

Neo
  • 4,200
  • 5
  • 21
  • 27
  • There are a few information that would help answering your question. 1. By the edge name, do you mean the `type` of the edge? 2. If so, can you use the [APOC library](https://neo4j-contrib.github.io/neo4j-apoc-procedures/)? – Gabor Szarnyas Oct 19 '17 at 17:37

1 Answers1

3

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)
cybersam
  • 63,203
  • 6
  • 53
  • 76
  • Thanks. Your query creates multiple edges. So I made a change to create single edge with names like 'ade'. – Neo Oct 19 '17 at 20:30
  • Thanks for the update @cybersam. Is there any more efficient way for large dataset. Thanks! – Neo Oct 20 '17 at 15:50
  • This query produces Cartesian product and size of my data is very large (~ 1million). is there any more efficient way to create edges. Thanks! – Neo Oct 24 '17 at 21:02