我有一些数据,其中一些关系比其他关系重要,并加权来表明它。 例如,我有这样的图:
(city_a:City)-[:has{weight:10}]->(casino:Event)
(city_a:City)-[:has{weight:1}]->(restaurant:Event)
(city_a:City)-[:has{weight:30}]->(university:Event)
(city_a:City)-[:has{weight:25}]->(library:Event)
......
(city_b:City)-[:has{weight:2}]->(casino:Event)
(city_b:City)-[:has{weight:2}]->(restaurant:Event)
(city_b:City)-[:has{weight:5}]->(university:Event)
(city_b:City)-[:has{weight:10}]->(library:Event)
......
我输入如下
Input: {casino, restaurant, university}
我应该输出
Output: city_a
作为答案,因为它的关系比其他城市的关系更多。
(也许我的图表模型不是正确的,但我也想不到什么。建议非常受欢迎)。
那么,如何为这种情况编写密码查询?
提前致谢!
答案 0 :(得分:2)
以下是基于您的描述的示例图表,其中引入了“city_c”以涵盖所需输入事件少于一个城市的情况:
merge (city_a:City{name:'city_a'})
merge (city_b:City{name:'city_b'})
merge (city_c:City{name:'city_c'})
merge (casino:Event{name:'casino'})
merge (restaurant:Event{name:'restaurant'})
merge (university:Event{name:'university'})
merge (library:Event{name:'library'})
merge (city_a)-[:has{weight:10}]->(casino)
merge (city_a)-[:has{weight:1}]->(restaurant)
merge (city_a)-[:has{weight:30}]->(university)
merge (city_a)-[:has{weight:25}]->(library)
merge (city_b)-[:has{weight:2}]->(casino)
merge (city_b)-[:has{weight:2}]->(restaurant)
merge (city_b)-[:has{weight:5}]->(university)
merge (city_b)-[:has{weight:10}]->(library)
merge (city_c)-[:has{weight:100}]->(university)
我们还需要一个索引:事件(名称),用于通过输入字符串进行快速查找(您可能还需要索引:城市(名称),尽管这不需要或与此一起使用特别查询)
create index on :Event(name)
由此我们可以创建查询,以便根据输入事件与具有这些事件的城市进行匹配,并按每个城市的匹配事件数量和评级总和进行排序。
而不是with ... as input
您想要参数化您的查询。
with ['casino', 'restaurant', 'university'] as input
match (e:Event)<-[r:has]-(city:City)
where e.name in input
with city, count(r) as eventCount, sum(r.weight) as weightSum
return city, eventCount, weightSum
order by eventCount desc, weightSum desc
limit 1