为什么Cypher的查询速度更快?

Mik*_*378 2 neo4j graph-databases cypher

我刚刚阅读了Neo4j官方文档的这一页.
它显示了一种Cypher方式来专门检索朋友的朋友:

MATCH (joe { name: 'Joe' })-[:knows*2..2]-(friend_of_friend)
WHERE NOT (joe)-[:knows]-(friend_of_friend)
RETURN friend_of_friend.name, COUNT(*)
ORDER BY COUNT(*) DESC , friend_of_friend.name
Run Code Online (Sandbox Code Playgroud)

为什么以下方式更快?:

MATCH path = shortestPath((joe { name: 'Joe' })-[:KNOWS*..2]-(friend_of_friend))
WHERE length(path) = 2
WITH nodes(path)[-1] AS secondDegreeFriends //retrieving the friend_of_friend nodes
RETURN secondDegreeFriends._name, COUNT(*)
ORDER BY COUNT(*) DESC , secondDegreeFriends.name
Run Code Online (Sandbox Code Playgroud)

(对于第二个查询,33ms vs 22ms,两者都在图中的182个成员的上下文中)

Chr*_*sen 5

首先,如果没有一些测试数据,很难证明查询差异的某些方面.

我在这里看到一些观点:

  1. 在第一个查询中,您不使用标签和索引属性,因此整个模式匹配将导致遍历匹配器,这是一个全局图查找.

  2. 否定总是代价高昂,而对WHERE子句中的模式的否定是非常昂贵的.

我建议你使用PROFILE在shell中运行查询并检查执行计划结果.

  1. 未指定关系方向的模式的shortestPath具有更好的路径匹配算法.