2016-06-28 92 views
2

我正在處理圖數據庫並寫了一些Cypher查詢Cypher查詢中聯合後的結果(Neo4j)

e.g以下查詢是針對特定用戶的所有帖子和查詢的其他部分每個人喜歡的總量不計算

第一部分也類似。

查詢

match a=(p:FaceBookPost{auther_id:"1"})-[hv:HAVE_LIKE]-(l:FacebookLike) 
return COUNT(l.auther_id) as total, (l.auther_id) as authers order by total DESC 

UNION ALL 

match a=(p:FaceBookPost{auther_id:"1"})-[hv:HAVE_COMMENT]-(l:FacebookComment) 
return COUNT(l.auther_id) as total, (l.auther_id) as authers order by total DESC 

UNION ALL 

match a=(i:InstagramPost{person_id:"1"})-[il:INSTAGRAM_LIKE]-(l:InstagramLike) 
return COUNT(i.person_id) as total, (l.person_id) as authers order by total DESC 

UNION ALL 

match a=(i:InstagramPost{person_id:"1"})-[ic:INSTAGRAM_COMMENT]-(c:InstagramComment) 
return COUNT(c.person_id) as total, (c.person_id) as authers order by total DESC 

輸出地說:

| total | authers 
---+-------+--------- 
1 |  4 | author 1 
2 |  3 | author 2 
3 |  1 | author 3 
4 |  2 | author 1 
5 |  1 | author 2 
6 |  1 | author 3 
. |  . | ........ 
. |  . | ........ 
. |  . | ........ 

必出放:

| total | authers 
---+-------+--------- 
1 |  6 | author 1 
2 |  4 | author 2 
3 |  2 | author 3 

我已經嘗試了不同的方式和不同的查詢要求輸出。 但我無法得到任何解決方案。

Cypher中有任何方法可以獲得所需的輸出嗎?

回答

3

不幸的是,目前沒有辦法從UNION後處理結果。但是,有計劃加入 - 參見https://github.com/neo4j/neo4j/issues/2725#issuecomment-227973992

但是,在您的示例中,您可以設法避免完全需要UNION。這會更清楚地理解,並且更高效。

首先,有可能結合一些立即的MATCH條款:

MATCH (:FaceBookPost{auther_id:"1"})-[:HAVE_LIKE|:HAVE_COMMENT]-(l) 
RETURN COUNT(*) as total, (l.auther_id) as authers order by total DESC 

UNION ALL 

MATCH (:InstagramPost{person_id:"1"})-[:INSTAGRAM_LIKE|:INSTAGRAM_COMMENT]-(l) 
RETURN COUNT(*) as total, (l.person_id) as authers order by total DESC 

這是更好的,但仍需要一個UNION ALL因爲有兩個不同的起點 - 一個標記:FaceBookPost和一個:InstagramPost。如果您可以更新您的模型,以便這兩個模板共享一個附加標籤,例如:Post,那麼你可以減少它到一個單一的查詢。

更新模式:

MATCH (p:FaceBookPost) SET p:Post; 
MATCH (p:InstagramPost) SET p:Post; 

然後查詢:

MATCH (:Post{person_id:"1"})-[:HAVE_LIKE|:HAVE_COMMENT|:INSTAGRAM_LIKE|:INSTAGRAM_COMMENT]-(l) 
RETURN COUNT(*) as total, (l.person_id) as authers order by total DESC 

您可能還需要共享的關係類型,例如更換:HAVE_LIKE:INSTAGRAM_LIKE只有:LIKED(同上與更換註釋類型:COMMENTED)。

+0

正如你所說的更新模型在我的情況下是不可能的。 我也在將數據從RDMS遷移到圖形數據庫。 –

+1

我試圖看看在從RDBMS遷移之後是否可以找到更新模型的方法,因爲它可以簡化所有查詢。如果你不能這樣做,你需要後處理聯合的結果 - 直到鏈接的github問題得到解決。 –

+0

感謝您的回覆,但在我的情況下,建模不可能以這種方式進行。因爲我還必須添加twitter數據。 它們有完全不同的型號。 –