基于Neo4j电影样本图:如何找出仅含PRODUCED关系的节点间唯一关联
Got it, let's break down how to solve this problem using Cypher. Based on your existing data (15 total PRODUCED relationships, 2 of which have extra connections between their nodes), we need to isolate the PRODUCED relationships where the connected nodes have no other relationship types between them (in either direction).
Approach 1: Direct Filter with NOT EXISTS
This is the most straightforward and efficient method—we'll match all PRODUCED relationships, then exclude any pairs where additional non-PRODUCED relationships exist:
// Count the number of PRODUCED relationships with no other connections between nodes MATCH (a)-[r:PRODUCED]->(b) // Exclude pairs with any outgoing/incoming non-PRODUCED relationships WHERE NOT EXISTS( (a)-[other_rel]->(b) WHERE type(other_rel) <> 'PRODUCED' ) AND NOT EXISTS( (b)-[other_rel]->(a) WHERE type(other_rel) <> 'PRODUCED' ) RETURN count(r) as unique_produced_relations
How this works:
MATCH (a)-[r:PRODUCED]->(b)grabs every existingPRODUCEDrelationship.- The
WHEREclause checks two things:- There are no outgoing relationships from
atobthat aren'tPRODUCED. - There are no outgoing relationships from
btoathat aren'tPRODUCED.
- There are no outgoing relationships from
- Finally, we count the remaining
PRODUCEDrelationships—based on your data, this should return13(15 total minus 2 with extra connections).
If you want to see the actual node pairs instead of just the count, modify the return clause:
MATCH (a)-[r:PRODUCED]->(b) WHERE NOT EXISTS( (a)-[other_rel]->(b) WHERE type(other_rel) <> 'PRODUCED' ) AND NOT EXISTS( (b)-[other_rel]->(a) WHERE type(other_rel) <> 'PRODUCED' ) RETURN a.name, b.name, count(r) as produced_count
Approach 2: Aggregate Relationship Types
If you prefer a more explicit way to verify relationship types between nodes, you can first collect all relationship types for each pair, then filter for pairs that only have PRODUCED:
// First, get all node pairs and their distinct relationship types MATCH (a)-[r]->(b) WITH a, b, collect(DISTINCT type(r)) as rel_types // Keep only pairs where PRODUCED is the only relationship type WHERE rel_types = ['PRODUCED'] // Now count the PRODUCED relationships for these pairs MATCH (a)-[r:PRODUCED]->(b) RETURN count(r) as unique_produced_relations
This method is useful if you want to inspect the relationship types first, but it's slightly less efficient than the first approach since it requires an extra aggregation step.
内容的提问来源于stack exchange,提问作者skibee

