如何为Neo4j Python Driver的查询设置超时时间?
设置查询超时(10秒)的实现方案
针对你检测大图中两节点关系的场景,以下是主流图数据库的具体超时设置方法,以及客户端层面的兜底方案:
1. 数据库查询级超时设置
Neo4j
在Cypher查询中直接指定超时参数,单位支持s(秒)、ms(毫秒):
CYPHER timeout=10s MATCH (a:Node {id: $nodeId1})-[r]->(b:Node {id: $nodeId2}) RETURN EXISTS(r)
超时后查询会抛出QueryExecutionTimeoutException,捕获该异常即可判定为“大概率不存在关系”。
JanusGraph(Gremlin)
通过with('evaluationTimeout')设置超时,单位为毫秒:
g.V().has('id', nodeId1) .out() .has('id', nodeId2) .hasNext() .with('evaluationTimeout', 10000)
超时会触发TimeoutException,处理异常即可返回预设结论。
NebulaGraph
先设置客户端超时(单位毫秒),再执行查询:
SET client_timeout = 10000; MATCH (a:Node)-[r]->(b:Node) WHERE a.id == $nodeId1 AND b.id == $nodeId2 RETURN EXISTS(r);
超时后客户端会收到超时错误,以此作为判断依据。
2. 客户端层面兜底方案
如果数据库不支持查询级超时,可在业务代码中通过任务调度控制执行时间:
- Python:使用
timeout-decorator装饰查询函数
import timeout_decorator @timeout_decorator.timeout(10) def check_relationship(node_id1, node_id2): # 执行图查询逻辑 pass try: result = check_relationship(id1, id2) except timeout_decorator.TimeoutError: # 超时,判定为大概率无关系 pass
- Java:用
ExecutorService提交查询任务并设置超时
ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Boolean> future = executor.submit(() -> { // 执行图查询逻辑 return checkRelationship(nodeId1, nodeId2); }); try { Boolean result = future.get(10, TimeUnit.SECONDS); } catch (TimeoutException e) { // 超时处理,判定为大概率无关系 future.cancel(true); } finally { executor.shutdown(); }
内容的提问来源于stack exchange,提问作者Ambrose Leung
相关产品推荐
相关产品推荐

