简体   繁体   中英

How to use cypher to create a relationship between items in an array and another node

I would like to use cypher to create a relationship between items in an array and another node.

The result from this query was a list of empty nodes connected to each other.

MATCH (person:person),(preference:preference) 
UNWIND person.preferences AS p
WITH p
WHERE NOT (person)-[:likes]->(preference) AND 
p = preference.name CREATE (person)-[r:likes]->(preference)

Where person.preferences contains an array of preference names.

Obviously I am doing something wrong. I am new to neo4j and any help with above would be much appreciated.

Properties are attributes of a nodes while relationships involve one or two nodes. As such, it's not possible to create a relationship between properties of two nodes. You'd need to split the properties into their own collection of nodes, and then create a relationship between the respective nodes.

You can do all that in one statement - like so:

create (:Person {name: "John"})-[:LIKES]->(:Preference {food: "ice cream"})

For other people, you don't want to create duplicate Preferences, so you'd look up the preference, create the :Person node, and then create the relationship, like so:

match (preference:Preference {food: "ice cream"})
create (person:Person {name: "Jane"})
create (person)-[:LIKES]->(preference)

The bottom line for your use case is you'll need to split the preference arrays into a set of nodes and then create relationships between the people nodes and your new preference nodes.

One thing....

MATCH (person:person),(preference:preference)
Creates a Cartesian product (inefficient and causes weird things)

Try this...

// Get all persons
MATCH (person:person)
// unwind preference list, (table is now person | preference0, person | preference1)
UNWIND person.preferences AS p
// For each row, Match on prefrence 
MATCH (preference:preference)
// Filter on preference column
WHERE preference.name=p
// MERGE instead of CREATE to "create if doesn't exist"
MERGE (person)-[:likes]->(preference)
RETURN person,preference

If this doesn't work, could you supply your sample data and noe4j version? (As far as I can tell, your query should technically work)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM