简体   繁体   English

Neo4j Cypher性能的可选匹配

[英]Neo4j Cypher Performance of Optional Match

I'm trying to write a query to count the total number of votes for an election grouped by the state in which they were cast. 我正在尝试编写一个查询,以计算按投票所属州分组的选举的总票数。 I'd like all states to be returned even if there are 0 votes. 我希望即使有0票,也能返回所有州。 The following query uses optional match to return all states regardless of whether or not any votes have been cast. 以下查询使用可选的match返回所有状态,而不管是否已投票。

MATCH (state:State)
OPTIONAL MATCH (state)<-[:FROM]-(:User)-[:CAST]->(vote:Vote)-[:FOR]->(:Election{id:'ABC123'})
RETURN state, count(vote)

returns 50 rows in in 3064ms . 在3064ms内返回50行

If I remove the optional match the query performs much better : 如果删除可选匹配项,查询的性能会更好:

MATCH (state:State),(state)<-[:FROM]-(:User)-[:CAST]->(vote:Vote)-[:FOR]->(:Election{id:'ABC123'})
RETURN state, count(*)

returns 49 rows in 406ms . 在406毫秒内返回49行

My questions are 我的问题是

  1. Why is there such a huge discrepancy in performance between the two queries ? 为什么两个查询之间的性能如此巨大的差异?

  2. Is there a better way to structure the query to improve performance and still meet the requirement? 有没有更好的方法来构造查询以提高性能并仍然满足要求?

What about using a Union statement?: 使用Union语句怎么办?:

MATCH (s:State) 比赛(状态:s)
RETURN s 返回
UNION MATCH (s:State)<-[:FROM]-(:User)-[:CAST]->(vote:Vote)-[:FOR]->(:Election{id:'ABC123'}) RETURN s, count(vote) UNION MATCH(s:State)<-[:FROM]-(:User)-[:CAST]->(vote:Vote)-[:FOR]->(:Election {id:'ABC123'})RETURN s ,计数(票)

I think your query may be taking so long due to the mechanics of the optional match vis a vis the count(vote) operation. 我认为由于对count(vote)操作进行可选匹配的机制,您的查询可能花费了很长时间。 I'm not sure if this will be faster, but it might be worth a try. 我不确定是否会更快,但是可能值得尝试。

Union Docs 联盟文件
Optional Match Docs 可选的比赛文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM