我有一个包含图书,章节和角色的图表。书籍包含章节,章节提到角色。我想写一个查询,向我展示大多数书中出现的10个字符,以及它们出现的书籍。
假设我的问题有点简单,我可以轻松编写一个查询,向我展示大多数章节中出现的10个字符:
MATCH (chapter)-[:MENTIONS]->(character)
RETURN character,
COLLECT(chapter) as chapters
ORDER BY SIZE(chapters) DESC
LIMIT 10
上面的查询工作正常。现在我正在尝试编写一个类似的查询来显示书籍而不是章节:
MATCH (book)-[:CONTAINS]->(chapter)-[:MENTIONS]->(character)
RETURN character,
COLLECT(book) as books
ORDER BY SIZE(books) DESC
LIMIT 10
这个查询似乎运行正常,但它只报告了一堆没有任何关系的字符和书籍,因为书籍和字符之间没有直接的关系。 neo4j可以推断出这些间接关系,并在查询中显示它们,而不必修改数据并为每个模式手动插入
(book)-[:CONTAINS]->(chapter)-[:MENTIONS]->(character)
新关系
(book)-[:TALKS_ABOUT]->(character)
答案 0 :(得分:4)
看起来你需要虚拟关系。您可以尝试apoc.create.vRelationship
:
MATCH (book)-[:CONTAINS]->(chapter)-[:MENTIONS]->(character)
WITH character,
COLLECT(distinct book) as books
ORDER BY SIZE(books) DESC LIMIT 10
UNWIND books as book
CALL apoc.create.vRelationship(book,'TALKS_ABOUT',{}, character) yield rel
RETURN character, collect(rel) as rels