Skip to content

Commit 260926c

Browse files
Add optional timeout argument to graph queries (#87)
* Add optional timeout argument to graph queries * Address PR comments
1 parent 387e86d commit 260926c

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,8 @@ result = redis_graph.query(query, params)
5151
# Print resultset
5252
result.pretty_print()
5353

54+
# Use query timeout to raise an exception if the query takes over 10 milliseconds
55+
result = redis_graph.query(query, params, timeout=10)
5456

5557
# Iterate through resultset
5658
for record in result.result_set:

redisgraph/graph.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -117,14 +117,19 @@ def build_params_header(self, params):
117117
params_header += str(key) + "=" + str(value) + " "
118118
return params_header
119119

120-
def query(self, q, params=None):
120+
def query(self, q, params=None, timeout=None):
121121
"""
122122
Executes a query against the graph.
123123
"""
124124
if params is not None:
125125
q = self.build_params_header(params) + q
126126

127-
response = self.redis_con.execute_command("GRAPH.QUERY", self.name, q, "--compact")
127+
command = ["GRAPH.QUERY", self.name, q, "--compact"]
128+
if timeout:
129+
if not isinstance(timeout, int):
130+
raise Exception("Timeout argument must be a positive integer")
131+
command += ["timeout", timeout]
132+
response = self.redis_con.execute_command(*command)
128133
return QueryResult(self, response)
129134

130135
def _execution_plan_to_string(self, plan):

test.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,5 +218,26 @@ def test_execution_plan(self):
218218

219219
redis_graph.delete()
220220

221+
def test_query_timeout(self):
222+
redis_graph = Graph('timeout', self.r)
223+
# Build a sample graph with 1000 nodes.
224+
redis_graph.query("UNWIND range(0,1000) as val CREATE ({v: val})")
225+
# Issue a long-running query with a 1-millisecond timeout.
226+
try:
227+
redis_graph.query("MATCH (a), (b), (c), (d) RETURN *", timeout=1)
228+
assert(False)
229+
except redis.exceptions.ResponseError as e:
230+
assert("Query timed out" in e.args)
231+
# Expecting an error.
232+
pass
233+
234+
try:
235+
redis_graph.query("RETURN 1", timeout="str")
236+
assert(False)
237+
except Exception as e:
238+
assert("Timeout argument must be a positive integer" in e.args)
239+
# Expecting an error.
240+
pass
241+
221242
if __name__ == '__main__':
222243
unittest.main()

0 commit comments

Comments
 (0)