您好我在neo4j上我遇到了一些问题我有一个查询,我希望返回一个节点(菜肴)具有最高百分比,如此
// 1. Find the most_popular_cuisine
MATCH (n:restaurants)
WITH COUNT(n.cuisine) as total
MATCH (r:restaurants)
RETURN r.cuisine , 100 * count(*)/total as percentage
order by percentage desc
limit 1
我试图通过获得最高结果并与之匹配来进一步扩展这一点,以获得具有该属性的节点,如此
WITH COUNT(n.cuisine) as total
MATCH (r:restaurants)
WITH r.cuisine as cuisine , count(*) as cnt
MATCH (t:restaurants)
WHERE t.cuisine = cuisine AND count(*) = MAX(cnt)
RETURN t
答案 0 :(得分:0)
我认为你可能会更好地重构一下你的模型,:Cuisine
是一个标签,每个美食都有自己的节点。
(:Restaurant)-[:OFFERS]->(:Cuisine)
或
(:Restaurant)-[:SPECIALIZES_IN]->(:Cuisine)
然后您的查询可能如下所示
MATCH (cuisine:Cuisine)
RETURN cuisine, size((cuisine)<-[:OFFERS]-()) AS number_of_restaurants
ORDER BY number_of_restaurants DESC
答案 1 :(得分:0)
我无法在WITH r.cuisine as cuisine , count(*) as cnt
而非WITH
声明中使用RETURN
,因此我不得不采用稍微冗长的方式。
可能有更优化的方法来做到这一点,但这也有效,
// Get all unique cuisines in a list
MATCH (n:Restaurants)
WITH COUNT(n.Cuisine) as total, COLLECT(DISTINCT(n.Cuisine)) as cuisineList
// Go through each cuisine and find the number of restaurants associated with each
UNWIND cuisineList as c
MATCH (r:Restaurants{Cuisine:c})
WITH total, r.Cuisine as c, count(r) as cnt
ORDER BY cnt DESC
WITH COLLECT({Cuisine: c, Count:cnt}) as list
// For the most popular cuisine, find all the restaurants offering it
MATCH (t:Restaurants{Cuisine:list[0].Cuisine})
RETURN t