简体   繁体   中英

Neo4j Many to 1 Relationship

I currently have two nodes known as "friend" and "friendOfAFriend" I want to display a many to 1 relationship where many "friends" are "friends_to" only 1 "friendOfFriend". The only exception is I want to only have "friends" going to the "friendsOfFriend" when the "friend" can only go to 1 "friendofAFriend". I have a csv file that pulls in the names of the "friends" and the "friendOfAFriends", but some friends can go to multiple different "friendsOfAFriends" and I want to avoid that. Here is my current code:

MERGE(f:Friend{name:csv.name}) 
MERGE(fo:FriendOfAFriend{name:csv.fof}) 
OPTIONAL MATCH (f:f)-[fr:friend_to]->(fo:fo)
CREATE (f)-[newf:friend_to]->(newfo:fo)
RETURN f, new, fewfo

I would really appreciate if someone can point me in the right direction to where I only display "friends" who can only reach out to one "FriendOfAFriend" in a Many-to-1 relationship. Right now it is currently displaying each "friend" from my csv (duplicating the friend list) going to each "FriendOfAFriend".

Your data is in the CSV file, and not yet in the neo4j DB, So, to avoid storing unwanted nodes and relationships in the DB, you would have to write a query that read all the CSV data into memory, filtered out the unwanted data in memory, and finally stored the wanted data into the DB. That is definitely possible to do, but may not be necessary and could cause an out-of-memory situation if the CSV file is too big.

I suggest that you do what you want in 2 steps. First, just create all the nodes and relationships from the CSV file, without filtering out anything (and omitting your OPTIONAl MATCH clause, which is not doing anything anyway except waste time).

Second, delete the nodes and relationships you don't want:

MATCH (f:Friend)
WHERE SIZE((f)-[:friend_to]->(:FriendOfAFriend)) > 1
FOREACH(p IN (f)-[:friend_to]->(:FriendOfAFriend) | DELETE RELATIONSHIPS(p)[0])
DETACH DELETE f;

The WHERE clause is a quick degree-ness check to efficiently find the Friend nodes with more than 1 outgoing friend_to relationship. The FOREACH clause will delete the unwanted friend_to relationships, and the DETACH DELETE clause will delete the unwanted Friend nodes (and any remaining relationships they may have).

[By the way, your data model (with both Friend and FriendOfAFriend ) seems wrong, but that is another issue.]

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