Iterate through [property] maps, map keys and map[key] values

apoc
cypher

(Gabriel Toma) #1

I want to be able to create graphs mimicking sql normal forms (linking parent to child entities through foreigh keys), and i don't want to do it column by column.
Hence, i need to be able to create relationships between identically named properties, having identical values. Direction of the relationship to be considered later.
Problem is that i don't know how to access/iterate through "keys" inside a property map (currently using apoc.any.properties(n) to extract all attributes of a node).

So, my query would look like:
considering two node tags "parent" and "child"
for each "parent" node p
for each "child" node c
for each property of p
for each property of c
if c.property name ~= p.property name and if c[property name].value=p[property name].value
then create relationship between p and c

Of course, looks like a horrendous Cartesian product, but the thing i am interested in is marked in bold : how can i iterate through the keys of a map?


(Benoit Simard) #2

If you want to iterate over the properties of a node, you can use something like that :

MATCH (n) WITH n LIMIT 1
UNWIND keys(n) AS key
RETURN n[key]

(Michael Hunger) #3

Not sure if you want one rel per property or one in general. Here is the code for the latter.

MATCH (p:Parent), (c:Child)
WHERE any(k in keys(p) WHERE p[k] = c[k])
CREATE (p)-[:PARENT_OF]->(c)

(Gabriel Toma) #4

Many thanks, both of you. Below works for me:

MATCH (n),(p) where n<>p WITH n,p
UNWIND keys(n) AS keyn
UNWIND keys(p) as keyp
with n,p,keyp,keyn WHERE keyp=keyn
RETURN keyn,n[keyn],keyp,n[keyp] limit 10

I will stick to the UNWIND as not always the key names are the same (hence the ~=)

PS: is there any notepad++ formatter for Cypher? Or, what are you using to format Cypher code?