如何通过相同的关系属性进行汇总和排序

时间:2019-05-16 07:17:43

标签: neo4j cypher

我是neo4j的新手,想为用户和项目构建推荐引擎,这里是数据结构:

CREATE
 (u1:User {id: 2, title: "symfony php", description:"php"})

CREATE (p:Project {id: 1, title: "php", description: "symfony"}),
(p1:Project {id: 4, title: "symfony php", description:"php"})

CREATE (t1:Tag { id: 1, name: "php"}),
(t2:Tag { id: 2, name: "symfony"})

CREATE (t2)-[:BORADER]->(t1)

CREATE
       (u1)-[:TAGGED {position: "title"}]->(t2),
       (u1)-[:TAGGED {position: "title"}]->(t1),
       (u1)-[:TAGGED {position: "desc"}]->(t1),

       (p)-[:TAGGED {position: "title"}]->(t1),
       (p)-[:TAGGED {position: "desc"}]->(t2),

       (p1)-[:TAGGED {position: "title"}]->(t2),
       (p1)-[:TAGGED {position: "title"}]->(t1),
       (p1)-[:TAGGED {position: "desc"}]->(t1)

我想找到按大多数关系排序并按标题和描述匹配数排序的最佳项目

我尝试了很多解决方案,我认为这是目前最好的查询

MATCH (u:User)
WHERE u.id = 1
MATCH (u)-[ut:TAGGED]->(t:Tag)<-[pt:TAGGED]-(p:Project)
RETURN DISTINCT p.title, { position: ut.position, tags: collect(t.name), size: size(collect(t.name))} as data   
ORDER by SIZE(data.size) desc

结果将是: https://ibb.co/MGVv0V7

问题在于项目按位置分组,但在标题和描述匹配项的结果中重复,而且我不知道如何允许标签之间的:BORADER标签关系

预期结果应该像

"php symfony" | { position: "title" , tags: ["php", "symfony"], size: 2}, { position: "desc", tags: ["symfony"], size: 1 }
"php" | { position: "title" , tags: ["php"], size: 1}, { position: "desc", tags: ["symfony"], size: 1 }

*编辑*

我尝试了其他一些查询,现在我接近所需的结果

MATCH (u: User)-[ut:TAGGED]->(t:Tag)<-[pt:TAGGED]-(p:Project)
    WHERE u.id = 2
    WITH   p.id as pid, 
           {position: ut.position, tags: collect(t.name)} as data, 
           p.title as title
    WITH pid, title, collect({position: data.position, tags: data.tags, size: size (data.tags)}) as data
    RETURN pid, title, data
    ORDER BY data[0].size, data[1].size desc

但是通过此查询,我的结果中有重复的节点:

╒═════╤═════════════╤══════════════════════════════════════════════════════════════════════╕
│"pid"│"title"      │"data"                                                                │
╞═════╪═════════════╪══════════════════════════════════════════════════════════════════════╡
│1    │"php"        │[{"size":1,"position":"desc","tags":["php"]},{"size":2,"position":"tit│
│     │             │le","tags":["php","symfony"]}]                                        │
├─────┼─────────────┼──────────────────────────────────────────────────────────────────────┤
│4    │"symfony php"│[{"size":2,"position":"desc","tags":["php","php"]},{"size":3,"position│
│     │             │":"title","tags":["php","php","symfony"]}]                            │
└─────┴─────────────┴──────────────────────────────────────────────────────────────────────┘

0 个答案:

没有答案