Neo4j:将三个或更多关系与单个动态节点匹配

时间:2014-10-06 01:22:52

标签: neo4j graph-databases

我正在尝试将Neo4j用于实施推荐系统的个人项目。系统需要多个字符串作为输入和输出建议。系统具有动物和群组形式的节点。动物和群体之间的关系是动物属于一个群体。动物可以属于多个群体。

输入可以是任意数量的动物。我试图回答的问题是"哪些动物存在于包含所有输入动物的组中?"

正确输出的一个例子:

Input: Lion, Parrot, Giraffe
Output: Elephant, Zebra
The lion, parrot and giraffe all belong to group 2 and 3.  The elephant belongs to group 2 and the zebra belongs to group 3, so they are outputted.

我目前的解决方案:

 Match (:Animal { name: "Parrot" })
            -[:BELONGS_TO]->(matchingGroup:Group)
            <-[:BELONGS_TO]-(:Animal { name: "Lion" }),
        (:Animal { name: "Giraffe" })
            -[:BELONGS_TO]->matchingGroup
            <-[:BELONGS_TO]-(animalsInMatchingGroup:Animal)
    Return animalsInMatchingGroup.name AS name, count(animalsInMatchingGroup.name) as matches
    ORDER BY count(animalsInMatchingGroup.name) DESC

问题: 当我的查询中有两个以上的动物时,问题就出现了。在上面的查询中,我使用等于输入动物数量的Match语句来查询图形 - 1.我想知道是否有人知道这个问题的更好解决方案会阻止多次查询图形。

这是图表。 http://s29.postimg.org/inhhvqcd3/Screen_Shot_2014_10_05_at_8_09_23_PM.png

创建声明

CREATE 
(elephant:Animal { name: 'Elephant' }),
(lion:Animal { name: 'Lion' }),
(tiger:Animal { name: 'Tiger' }),
(giraffe:Animal { name: 'Giraffe' }),
(parrot:Animal { name: 'Parrot' }),
(zebra:Animal { name: 'Zebra' }),
(group1:Group { name: 'Group 1' }),
(group2:Group { name: 'Group 2' }),
(group3:Group { name: 'Group 3' }),
(group4:Group { name: 'Group 4' }),
(group5:Group { name: 'Group 5' }),
elephant-[:BELONGS_TO]->group2,
elephant-[:BELONGS_TO]->group3,
lion-[:BELONGS_TO]->group1,
lion-[:BELONGS_TO]->group2,
lion-[:BELONGS_TO]->group3,
parrot-[:BELONGS_TO]->group2,
parrot-[:BELONGS_TO]->group3,
parrot-[:BELONGS_TO]->group5,
giraffe-[:BELONGS_TO]->group2,
giraffe-[:BELONGS_TO]->group3,
giraffe-[:BELONGS_TO]->group4,
tiger-[:BELONGS_TO]->group5,
zebra-[:BELONGS_TO]->group4,
zebra-[:BELONGS_TO]->group3

感谢您的帮助。

干杯,Cam。

1 个答案:

答案 0 :(得分:0)

你可以试试这个:

WITH ['Parrot', 'Lion', 'Giraffe'] AS names
MATCH (:Animal { name: head(names)})-[:BELONGS_TO]->(g:Group)
WITH g,names
MATCH (g)<-[:BELONGS_TO]-(a:Animal)
WITH g,collect(a.name) AS animals,names
WHERE ALL (n IN names 
           WHERE n IN animals)
RETURN g.name, animals,names,size(animals)

请参阅此控制台:http://console.neo4j.org/r/vd2mba