Neo4j - 如果发现很少的结果,则使用替代匹配完成查询
Neo4j - complete a query with an alternative match if it finds few results
我正在尝试编写一个查询,根据共同的朋友和兴趣在 Neo4j 数据库中寻找潜在的朋友。
我不想post整个查询(学校作业的一部分),但这是重要的部分
MATCH (me:User {firstname: "Name"}), (me)-[:FRIEND]->(friend:User)<-[:FRIEND]-(potential:User), (me)-[:MEMBER]->(i:Interest)
WHERE NOT (potential)-[:FRIEND]->(me)
WITH COLLECT(DISTINCT potential) AS potentialFriends,
COLLECT(DISTINCT friend) AS friends,
COLLECT(i) as interests
UNWIND potentialFriends AS potential
/*
@HANDLING_FINDINGS
Here I count common friends, interests and try to find relationships between
potential friends too -- hence the collect/unwind
*/
RETURN potential,
commonFriends,
commonInterests,
(commonFriends+commonInterests) as totalPotential
ORDER BY totalPotential DESC
LIMIT 10
在@HANDLING_FINDINGS部分,我使用找到的潜在朋友来寻找彼此之间的关系并计算他们的潜力(即共享朋友和共同兴趣的总和),然后按潜力排序。
问题是可能会有没有朋友的用户,我也想推荐一些朋友。
我的问题 - 我能否以某种方式将一些随机用户插入 "potential" 结果中,如果他们的数量低于 10,以便每个人都能得到推荐?
我试过这样的东西
...
UNWIND potentialFriends AS potential
CASE
WHEN (count(potential) < 10 )
...
但是,一旦它命中 CASE 的开始,就会产生错误。我认为这种情况只能用作 return 这样的命令的一部分? (也许只是 return)
编辑第二个相关问题:
我已经在考虑匹配所有用户,然后根据共同点对他们进行排名 friends/interestes,但是搜索整个数据库不是很密集吗?
CASE
表达式可以用在任何需要值的地方,但不能用作完整的子句。
关于您的主要问题,您可以在现有的 WITH
和 UNWIND
子句之间放置一个 WITH
子句,如下所示:
WITH friends, interests,
CASE WHEN SIZE(potentialFriends) < 10 THEN {randomFriends} ELSE potentialFriends END AS potentialFriends
如果 potentialFriends
集合的大小小于 10,则 CASE
表达式将 {randomFriends}
parameter 的值赋给 potentialFriends
。
关于你的第二个问题,是的,它会很贵。
我正在尝试编写一个查询,根据共同的朋友和兴趣在 Neo4j 数据库中寻找潜在的朋友。
我不想post整个查询(学校作业的一部分),但这是重要的部分
MATCH (me:User {firstname: "Name"}), (me)-[:FRIEND]->(friend:User)<-[:FRIEND]-(potential:User), (me)-[:MEMBER]->(i:Interest)
WHERE NOT (potential)-[:FRIEND]->(me)
WITH COLLECT(DISTINCT potential) AS potentialFriends,
COLLECT(DISTINCT friend) AS friends,
COLLECT(i) as interests
UNWIND potentialFriends AS potential
/*
@HANDLING_FINDINGS
Here I count common friends, interests and try to find relationships between
potential friends too -- hence the collect/unwind
*/
RETURN potential,
commonFriends,
commonInterests,
(commonFriends+commonInterests) as totalPotential
ORDER BY totalPotential DESC
LIMIT 10
在@HANDLING_FINDINGS部分,我使用找到的潜在朋友来寻找彼此之间的关系并计算他们的潜力(即共享朋友和共同兴趣的总和),然后按潜力排序。
问题是可能会有没有朋友的用户,我也想推荐一些朋友。
我的问题 - 我能否以某种方式将一些随机用户插入 "potential" 结果中,如果他们的数量低于 10,以便每个人都能得到推荐?
我试过这样的东西
...
UNWIND potentialFriends AS potential
CASE
WHEN (count(potential) < 10 )
...
但是,一旦它命中 CASE 的开始,就会产生错误。我认为这种情况只能用作 return 这样的命令的一部分? (也许只是 return)
编辑第二个相关问题: 我已经在考虑匹配所有用户,然后根据共同点对他们进行排名 friends/interestes,但是搜索整个数据库不是很密集吗?
CASE
表达式可以用在任何需要值的地方,但不能用作完整的子句。
关于您的主要问题,您可以在现有的 WITH
和 UNWIND
子句之间放置一个 WITH
子句,如下所示:
WITH friends, interests,
CASE WHEN SIZE(potentialFriends) < 10 THEN {randomFriends} ELSE potentialFriends END AS potentialFriends
如果 potentialFriends
集合的大小小于 10,则 CASE
表达式将 {randomFriends}
parameter 的值赋给 potentialFriends
。
关于你的第二个问题,是的,它会很贵。