2017-02-18 51 views
2

我在的Neo4j下面的查詢其採用了UNION獲得來自Neo4j的聯合的結果平均值

MATCH (u:User {userId:'1'})-[dw:DIRECTOR_WEIGHT]->(d:Person)-[:DIRECTED]->(m:Movie) 
WITH m, avg(dw.weight) AS mean_dw, 0 AS mean_aw, 0 AS mean_gw 
WHERE m.title = 'Bambi' 
RETURN m.title, mean_dw, mean_aw, mean_gw, mean_dw + mean_aw + mean_gw AS total 

UNION 
MATCH (u:User {userId:'1'})-[aw:ACTOR_WEIGHT]->(a:Person)-[:ACTED_IN]->(m:Movie) 
WITH m, 0 AS mean_dw, avg(aw.weight) AS mean_aw, 0 AS mean_gw 
WHERE m.title = 'Bambi' 
RETURN m.title, mean_dw, mean_aw, mean_gw, mean_dw + mean_aw + mean_gw AS total 

UNION 
MATCH (u:User {userId:'1'})-[gw:GENRE_WEIGHT]->(g:Genre)<-[:GENRE]-(m:Movie) 
WITH m, 0 AS mean_dw, 0 AS mean_aw, avg(gw.weight) AS mean_gw 
WHERE m.title = 'Bambi' 
RETURN m.title, mean_dw, mean_aw, mean_gw, mean_dw + mean_aw + mean_gw AS total 

,得到以下結果:

╒═════════╤═══════════════╤════════════════╤═════════════════╤═════════════════╕ 
│"m.title"│"mean_dw"  │"mean_aw"  │"mean_gw"  │"total"   │ 
╞═════════╪═══════════════╪════════════════╪═════════════════╪═════════════════╡ 
│"Bambi" │7.2916666666667│"0"    │"0"    │7.2916666666667 │ 
├─────────┼───────────────┼────────────────┼─────────────────┼─────────────────┤ 
│"Bambi" │"0"   │0.45322110715442│"0"    │0.45322110715442 │ 
├─────────┼───────────────┼────────────────┼─────────────────┼─────────────────┤ 
│"Bambi" │"0"   │"0"    │9.289617486338933│9.289617486338933│ 
└─────────┴───────────────┴────────────────┴─────────────────┴─────────────────┘ 

我的問題是「總」不做我想讓它做的,因爲我只希望每部電影單總(三非零權,即合計:7.29 + 0.45 + 9.28), 但我不能找到一種方法,使用這種再返回的結果。也就是說,我想能夠說說得到的mean_dwmean_aw工會像

RETURN m.title, sum(total) 

RETURN m.title, mean_dw + mean_aw + mean_gw 

後,和mean_gw分別

回答

1

雖然工會後Cypher目前不支持處理,您可以在APOC程序中使用apoc.cypher.run()解決此問題。這會讓你在運行中執行聯合併產生聯合結果,從而讓你完成任何你想要的處理。

雖然看着你的查詢,你在每一個執行相同的操作,唯一的區別是關係遵循的比賽。還有三個獨立的平均列正在做,因爲你有興趣也越來越每個特定關係的體重平均爲均值,然後取所有這些手段的唯一的事了一些不必要的工作。

這應該讓我們削減了一些冗餘操作,並具有較窄的一系列變量的工作。

事情是這樣的:

MATCH (u:User {userId:'1'}), (m:Movie{title:'Bambi'}) 
CALL apoc.cypher.run(" 
MATCH (u)-[dw:DIRECTOR_WEIGHT]->()-[:DIRECTED]->(m) 
RETURN avg(dw.weight) as mean 
UNION ALL 
MATCH (u)-[aw:ACTOR_WEIGHT]->()-[:ACTED_IN]->(m) 
RETURN avg(aw.weight) AS mean 
UNION ALL 
MATCH (u)-[gw:GENRE_WEIGHT]->()<-[:GENRE]-(m) 
RETURN avg(gw.weight) AS mean 
", {u:u, m:m}) YIELD value 
RETURN m.title, SUM(value.mean) as total 

現在,所有的說,你不一定需要在所有使用工會。你可以使用與WITH連接的子查詢。

MATCH (u:User {userId:'1'}), (m:Movie{title:'Bambi'}) 
MATCH (u)-[dw:DIRECTOR_WEIGHT]->()-[:DIRECTED]->(m) 
WITH u, m, avg(dw.weight) as total 
MATCH (u)-[aw:ACTOR_WEIGHT]->()-[:ACTED_IN]->(m) 
WITH u, m, total + avg(aw.weight) AS total 
MATCH (u)-[gw:GENRE_WEIGHT]->()<-[:GENRE]-(m) 
WITH u, m, total + avg(gw.weight) AS total 
RETURN m.title, total 
+0

非常感謝你。第二版有效;第一個版本給出了一個不同的(和錯誤的)結果,但我無法從代碼中找出原因。有任何想法嗎? –

+0

沒有想法,對於樣本數據,這兩個查詢都爲我返回相同的結果。對於第一個查詢,你可能想'RETURN value'看到每次相加在一起之前的手段,看看是否符合你的期望。 – InverseFalcon