我的neo4j数据库中有一个关系:
(r:RateableEntity)<-[t:TAG]-(h:HashTags)
现在,我想查询一个返回包含以下内容的列表的查询:
hashtagCount
,以及与此哈希标签相关的项目的列表。
hashtagName
和hashtagItems
带有id
标签。注意:我正在从输入参数中接收hashtag
和hashtagItems
的数目作为变量。
这是我从密码查询中得到的结果:
"hashtagList": [
{
"hashtagName": "hashtagName1",
"hashtagCount": number of times hashtag has been used in database,
"hashtagItems": [ list of relevant items for hashtagName1 ]
},
{
"hashtagName": "hashtagName2",
"hashtagCount": number of times hashtag has been used in database,
"hashtagItems": [ list of relevant items for hashtagName2 ]
},
...
]
我写了这个密码:
MATCH p = (r:RateableEntity)<-[t:TAG]-(h:HashTag)
UNWIND TAIL (NODES(p)) AS hash
WITH COUNT(hash) as Count, h, hash
ORDER BY hash LIMIT 3
WHERE h.tag in hash.tag
MATCH (r:RateableEntity)<-[:TAG]-(h:HashTag)
RETURN DISTINCT h.tag, r.id, Count
LIMIT 3
但它返回此结果:
h.tag r.id Count
"vanessa" "cdd14968-404c-41e9-84d5-bf147030a023" 15
"vanessa" "b7e74f38-44e4-4b7f-b2c4-8301023ffa9b" 15
"vanessa" "2064d3e4-2995-4202-b178-bb2a6f230ab0" 15
非常感谢您的帮助。
答案 0 :(得分:3)
有些事情要记住:
密码运算符针对每一行执行。
尽量不要将UNWIND视为循环结构。所有这些操作是对变量与列表元素的直角乘积进行笛卡尔乘积运算。
因此,当您取消缠绕列表时,该列表的每个元素都会有一行,以及该行已经存在的所有变量。然后,当发生对每行执行的后续操作(如MATCH或WITH)时,它看起来像是一个循环结构,但实际上并非如此。
无论如何,这里不需要UNWIND。对于两节点匹配的模式,tail(nodes(p))
只是一个仅包含最后一个节点的单元素列表。它没有更改行数(因为列表大小为1),因此这里无济于事。
此查询应该更好地工作:
MATCH (h:HashTag)
WITH h LIMIT 3 // best to limit early to avoid doing unnecessary work
WITH h, h.tag as hashtagName, size((h)-[:TAG]->()) as hashtagCount, [(h)-[:TAG]->(r:RateableEntity) | r.id] as hashtagItems
WITH h {hashtagName, hashtagCount, hashtagItems} as entry
RETURN collect(entry) as hashtagList
编辑
如果要按大小显示前3个主题标签,则可以使用以下修改后的查询:
MATCH (h:HashTag)
WITH h, size((h)-[:TAG]->()) as hashtagCount
ORDER BY hashtagCount DESC
LIMIT 3
WITH h, hashtagCount, h.tag as hashtagName, [(h)-[:TAG]->(r:RateableEntity) | r.id] as hashtagItems
WITH h {hashtagName, hashtagCount, hashtagItems} as entry
RETURN collect(entry) as hashtagList
答案 1 :(得分:0)
我已经找到了这个问题,也许其他人需要知道:
MATCH (:RateableEntity)<-[:TAG]-(p:HashTag)
RETURN p.tag As Tag, COUNT(p) as Count, [(p)-[:TAG]->(m) | m.id][..3] AS
RateableEntities ORDER BY Count DESC LIMIT 3
以下是网站上文档的链接: