Skip to content

Add optional timeout argument to graph queries #87

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 27, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ result = redis_graph.query(query, params)
# Print resultset
result.pretty_print()

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

# Iterate through resultset
for record in result.result_set:
Expand Down
9 changes: 7 additions & 2 deletions redisgraph/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,14 +117,19 @@ def build_params_header(self, params):
params_header += str(key) + "=" + str(value) + " "
return params_header

def query(self, q, params=None):
def query(self, q, params=None, timeout=None):
"""
Executes a query against the graph.
"""
if params is not None:
q = self.build_params_header(params) + q

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

def _execution_plan_to_string(self, plan):
Expand Down
21 changes: 21 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,5 +218,26 @@ def test_execution_plan(self):

redis_graph.delete()

def test_query_timeout(self):
redis_graph = Graph('timeout', self.r)
# Build a sample graph with 1000 nodes.
redis_graph.query("UNWIND range(0,1000) as val CREATE ({v: val})")
# Issue a long-running query with a 1-millisecond timeout.
try:
redis_graph.query("MATCH (a), (b), (c), (d) RETURN *", timeout=1)
assert(False)
except redis.exceptions.ResponseError as e:
assert("Query timed out" in e.args)
# Expecting an error.
pass

try:
redis_graph.query("RETURN 1", timeout="str")
assert(False)
except Exception as e:
assert("Timeout argument must be a positive integer" in e.args)
# Expecting an error.
pass

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove extra line

if __name__ == '__main__':
unittest.main()