与 Cypher 的可选关系

Optional relationship with Cypher

有一面墙 post 类型的场景,我想在其中溢出 post 你,你的朋友,并按时间顺序对它们进行排序

有没有办法不使用联合来做到这一点?

喜欢,我几乎喜欢这样的东西(如果你能原谅伪查询):

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

我只是想知道如何在一个查询中获取您的 post 以及您的朋友 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

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

基本上这不应该是我的结果 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"}}]

有什么指点吗?

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

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

我认为如果 post 属于第一个帐户,那位朋友应该是 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

其中任何一个都能满足您的需求吗?

Brian Underwood 的回答恰好将我引向了正确的方向,但最终尝试的解决方案产生了不太正确的结果

然而,经过一番修改后,我确实设法偶然发现了这个成功的查询:

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" 喜欢包含您自己的帖子的更新。

欢迎对此查询进行任何改进,但是,我不知道它的效率到底有多高,只是它确实正确排序并且据我所知到目前为止存在相应的限制