我有爱丽丝,鲍勃,查理和丹的书籍偏好的加权neo4j图表:
CREATE (alice:Person {name:'Alice'})
CREATE (bob:Person {name: 'Bob'})
CREATE (charlie:Person {name: 'Charlie'})
CREATE (dan:Person {name: 'Dan'})
CREATE (b00:Book {title:'Book 00'})
CREATE (b01:Book {title:'Book 01'})
CREATE (b02:Book {title:'Book 02'})
CREATE (b03:Book {title:'Book 03'})
CREATE (b04:Book {title:'Book 04'})
CREATE (b05:Book {title:'Book 05'})
CREATE (b06:Book {title:'Book 06'})
CREATE (b07:Book {title:'Book 07'})
CREATE (b08:Book {title:'Book 08'})
CREATE (b09:Book {title:'Book 09'})
CREATE (b10:Book {title:'Book 10'})
CREATE (alice)-[:LOVES {how_much:0.1}]->(b01)
CREATE (alice)-[:LOVES {how_much:0.2}]->(b02)
CREATE (alice)-[:LOVES {how_much:0.3}]->(b03)
CREATE (bob)-[:LOVES {how_much:0.2}]->(b02)
CREATE (bob)-[:LOVES {how_much:0.4}]->(b04)
CREATE (bob)-[:LOVES {how_much:0.5}]->(b05)
CREATE (bob)-[:LOVES {how_much:0.6}]->(b06)
CREATE (bob)-[:LOVES {how_much:0.7}]->(b07)
CREATE (charlie)-[:LOVES {how_much:0.3}]->(b03)
CREATE (charlie)-[:LOVES {how_much:0.8}]->(b08)
CREATE (charlie)-[:LOVES {how_much:0.9}]->(b09)
CREATE (charlie)-[:LOVES {how_much:1.0}]->(b10)
CREATE (dan)-[:LOVES {how_much:0.1}]->(b01)
CREATE (dan)-[:LOVES {how_much:0.8}]->(b08)
我想以这样的方式向Alice推荐书籍,我只考虑每个人的前2 LOVES
个关系。
因此,对于爱丽丝来说,我只会看看#02;书02"和"书03" (前2本书)。这些书将把我和鲍勃和查理联系起来(而不是丹,她通过她最不喜欢的书与爱丽丝联系)。
反过来,鲍勃将把爱丽丝连接到#06; Book 06"和" Book 07&#34 ;;查理将把爱丽丝连接到
" Book 09"和"第10册"。最后,我想看到四条建议:
"书06"和" Book 07"通过鲍勃;和" Book 09"和"第10册"通过查理。什么是最有效和最有效的Neo4j查询此任务?
这是我尝试做的事情:
MATCH (alice:Person {name:'Alice'})-[la:LOVES]->(ba:Book)<-[lf:LOVES]-(friend:Person)
WITH alice, la
ORDER BY la.how_much DESC
WITH alice, COLLECT(la)[0..2] as alice_likes
UNWIND alice_likes as la
return *
这是我如何将查询限制在前2爱丽丝的喜欢。但是,我不知道如何 继续这项任务。我尝试执行以下操作,但它并不像我期望的那样工作:
MATCH (alice:Person {name:'Alice'})-[la:LOVES]->(ba:Book)<-[lf:LOVES]-(friend:Person)
WITH alice, la
ORDER BY la.how_much DESC
WITH alice, COLLECT(la)[0..2] as alice_likes
UNWIND alice_likes as la
MATCH (alice)-[la]->(ba:Book)<-[lf:LOVES]-(friend:Person)
WITH alice, la, lf, friend
ORDER by friend.name, lf.how_much DESC
WITH friend, collect(lf)[0..2] as friend_likes, collect(la)[0..2] as alice_likes
RETURN friend.name, friend_likes, alice_likes
答案 0 :(得分:1)
这应该有效:
MATCH (alice:Person { name:'Alice' })-[la:LOVES]->(:Book)<-[:LOVES]-(friend:Person)
WITH alice, la, friend
ORDER BY la.how_much DESC
LIMIT 2
MATCH (bf:Book)<-[lf:LOVES]-(friend:Person)
WITH alice, lf, bf, friend
ORDER BY lf.how_much DESC
RETURN alice, friend, COLLECT(bf)[..2] AS books;
ALice
可能只有一个节点,因此我们可以使用LIMIT 2
为她获得前2本书。
然而,可能有多个朋友&#34;谁也喜欢这两本书,所以你不能用LIMIT 2
来获得每本书的2本书(相反,你只能为他们作为一组获得前两本书)。为了获得您想要的结果,此查询汇总了每位朋友的热门书籍,然后选择前2名(同样,为每位朋友)。