【问题标题】:Neo4j: Match three or more relationships to a single dynamic nodeNeo4j:将三个或更多关系匹配到单个动态节点
【发布时间】:2014-10-06 01:22:52
【问题描述】:

我正在为个人项目尝试 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

感谢您的帮助。

干杯,卡姆。

【问题讨论】:

    标签: neo4j graph-databases


    【解决方案1】:

    你可以试试这个:

    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

    【讨论】:

    • 这个查询有一些不错的想法,但是输出错误。感谢您的洞察力,我将看看是否可以使用 WITH 参数缩短查询。一个问题:在 SQL 语句中使用 IN 子句是否会遭受同样的性能损失?
    猜你喜欢
    • 2015-06-19
    • 2022-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-27
    相关资源
    最近更新 更多