Neo4j条件交叉的可选匹配

时间:2015-10-07 18:12:30

标签: graph neo4j cypher

 MATCH (category:Category {id:'123'} ),
                     (stream:Stream {id:'567'} )
 OPTIONAL MATCH path=(stream)-[:CONTAINS]->(categories:Category)-[:CHILD_OF*0..50]->(category)-[:CHILD_OF*0..50]->(subcats2:Category)<-[:PHOTO_OF]-(photo)
 with stream, subcats2, photo
 OPTIONAL MATCH (stream)<-[:PARTICIPANT_OF]-(users:User)-[:OWNER]->(photo)-[:PHOTO_OF]->(subcats:Category
 return photo

我想要这样的查询;

如果流contains类别执行第一个可选

如果stream(has)participants用户执行第二个可选

如果两者都返回照片

但在上面的查询中;它就像联合查询一样,如果流有参与者或用户,则返回OK,但如果它同时具有类别和用户,则无法获取交集。

需要类似的东西

MATCH (category:Category {id:'123'} ),
      (stream:Stream {id:'567'} )
MATCH (stream)-[:CONTAINS]->(categories:Category)
WITH count(categories) as cat_count
IF cat_count > 0
     MATCH path=(stream)-[:CONTAINS]->(categories:Category)-[:CHILD_OF*0..50]->(category)-[:CHILD_OF*0..50]->(subcats2:Category)<-[:PHOTO_OF]-(photo)
     with stream, subcats2, photo
MATCH (stream)-[:PARTICIPANT_OF]->(users:User)
WITH count(users) as user_count
IF user_count > 0
     MATCH (stream)<-[:PARTICIPANT_OF]-(users:User)-[:OWNER]->  (photo)-[:PHOTO_OF]->(subcats:Category
return photo

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

您可以进行联合,第二部分也会检查是否不使用它:

MATCH (stream:Stream {id:'567'} )
WHERE size((stream)-[:CONTAINS]->()) > 0
MATCH (category:Category {id:'123'} )
MATCH path=(stream)-[:CONTAINS]->(categories:Category)-[:CHILD_OF*0..50]-(category)-[:CHILD_OF*0..50]->(subcats2:Category)<-[:PHOTO_OF]-(photo)
RETURN stream, subcats2 as category, photo

UNION 

MATCH (stream:Stream {id:'567'} )
WHERE size((stream)-[:CONTAINS]->()) = 0
MATCH (category:Category {id:'123'} )
MATCH (stream)<-[:PARTICIPANT_OF]-(users:User)-[:OWNER]->(photo)-[:PHOTO_OF]-(category)
return stream, category,photo