You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于Neo4j电影样本图:如何找出仅含PRODUCED关系的节点间唯一关联

找出节点间仅含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 existing PRODUCED relationship.
  • The WHERE clause checks two things:
    1. There are no outgoing relationships from a to b that aren't PRODUCED.
    2. There are no outgoing relationships from b to a that aren't PRODUCED.
  • Finally, we count the remaining PRODUCED relationships—based on your data, this should return 13 (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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:27:02