与Cypher的可选关系

时间:2015-08-03 17:56:01

标签: neo4j cypher union

有一个墙贴式的场景,我想把你,你的朋友发布帖子,并按时间顺序按照限制排序

有没有办法在不使用联合的情况下执行此操作?

我喜欢这样的事情(如果你原谅伪查询):

match (a:Account)-([:FRIEND]->(friend:Account)-)?[:POST]->(post:Post)
where id(a) = 0
return friend,post

我只是想知道如何在一个查询中获取您的帖子以及您的朋友帖子

现在我有(0是现在登录帐户的ID):

match (a:Account)-[:FRIEND]->(friend:Account)-[:POST]->(post:Post)
where id(a) = 0
return friend,post
union
match (friend:Account)-[:POST]->(post:Post)
where id(friend) = 0
return friend,post
order by post.date_created DESC
limit 10

虽然这可以获得我想要的所有期望的帖子(根据我的测试),但是顺序似乎只是基于单个结果集而不是整个联合结果集来组织

基本上这不应该是我的结果json:

[{"id":4,"date_created":1438621410,"content":"This is a test post!","account":{"id":10,"username":"test","email":"test@test.com"}},{"id":5,"date_created":1438621422,"content":"about to try this thing","account":{"id":0,"username":"test2","email":"test2@gmail.com"}}]

应该是

[{"id":5,"date_created":1438621422,"content":"about to try this thing","account":{"id":0,"username":"test2","email":"test2@gmail.com"}}, {"id":4,"date_created":1438621410,"content":"This is a test post!","account":{"id":10,"username":"test","email":"test@test.com"}}]

任何指针?

2 个答案:

答案 0 :(得分:3)

布莱恩·安德伍德的答案恰好引导我朝着正确的方向前进,但最终尝试的解决方案却产生了不太正确的结果

然而,在经过一些修补之后,我确实设法偶然发现了这个获胜的问题:

MATCH (a:Account)-[:FRIEND*0..1]->(friend:Account)-[:POST]->(post:Post)
WHERE id(a) = 0
RETURN friend,post
ORDER BY post.date_created DESC
LIMIT 10

希望这有助于其他人使用Neo获取Facebook“Wall”,就像包含您自己帖子的更新一样。

对此查询的任何改进都会受到欢迎,但我不知道它的实际效率如何,只是它确实排序正确并且据我所知到目前为止的限制

答案 1 :(得分:1)

我认为您可以通过以下两种方式之一完成此任务:

MATCH (a:Account)-[:FRIEND]->(friend:Account)-[:POST*0..1]->(post:Post)
WHERE id(a) = 0
RETURN friend, post
ORDER BY post.date_created DESC
LIMIT 10

我认为,在属于第一个帐户的帖子中,该朋友将是NULL。这也应该有效:

MATCH (a:Account), (post:Post)
WHERE id(a) = 0
OPTIONAL MATCH (friend:Account)
WHERE
  a-[:POST]->post OR
  a-[:FRIEND]->friend-[:POST]->post
RETURN friend, post
ORDER BY post.date_created DESC
LIMIT 10

其中任何一个能让你得到你想要的东西吗?