DataG
DataG

Reputation: 125

Neo4j and Cypher: Create relationships to nodes that have similar property keys

Given the following nodes:

create(:ABC{id:'1', a:'axle',b:'bat'})
create(:ABC{id:'2', a:'ant',b:'ball',c:'clown'})
create(:ABC{id:'3', e:'elk',f:'fog',g:'gaff'})
create(:ABC{id:'4', a:'ax',c:'car',z:'zink'})

Using cypher, how would one create edges between nodes that share 1 or more property keys (regardless of their property value and with an unknown set of properties)? I'm fairly certain I could iterate thru nodes individually via python and create edges, but I have tried without success to do this in cypher.

Upvotes: 1

Views: 422

Answers (1)

cybersam
cybersam

Reputation: 67044

Here is a query that creates a SHARES_KEYS_WITH relationship between every pair of nodes that share at least one property with the same name (ignoring the id property, which all your example nodes have).

MATCH (m),(n)
WHERE (ID(m) > ID(n)) AND ANY (k IN KEYS(m) 
                              WHERE k <> 'id' AND k IN KEYS(n))
CREATE (m)-[:SHARES_KEYS_WITH]->(n)
RETURN m, n;

The ID(m) > ID(n) test ensures that we only evaluate each pair of distinct nodes just once. (Note that the ID() function returns the neo4j-generated internal identifier -- with is not the same as your id property.)

Upvotes: 1

Related Questions