diff --git a/README.md b/README.md index ce45f25..3b51fc0 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,17 @@ result = redis_graph.query(query) # Print resultset result.pretty_print() +# Use parameters +params = {'purpose':"pleasure"} +query = """MATCH (p:person)-[v:visited {purpose:$purpose}]->(c:country) + RETURN p.name, p.age, v.purpose, c.name""" + +result = redis_graph.query(query, params) + +# Print resultset +result.pretty_print() + + # Iterate through resultset for record in result.result_set: person_name = record[0] diff --git a/redisgraph/graph.py b/redisgraph/graph.py index d006546..0d3f900 100644 --- a/redisgraph/graph.py +++ b/redisgraph/graph.py @@ -103,12 +103,30 @@ def flush(self): self.nodes = {} self.edges = [] - def query(self, q): + def build_params_header(self, params): + assert type(params) == dict + # Header starts with "CYPHER" + params_header = "CYPHER " + for key, value in params.items(): + # If value is string add quotation marks. + if type(value) == str: + value = quote_string(value) + # Value is None, replace with "null" string. + elif value is None: + value = "null" + params_header += str(key) + "=" + str(value) + " " + return params_header + + def query(self, q, params=None): """ Executes a query against the graph. """ + if params is not None: + q = self.build_params_header(params) + q + statistics = None result_set = None + response = self.redis_con.execute_command("GRAPH.QUERY", self.name, q, "--compact") return QueryResult(self, response) diff --git a/test.py b/test.py index 9a372f2..0d73ae9 100644 --- a/test.py +++ b/test.py @@ -94,6 +94,18 @@ def test_path(self): # All done, remove graph. redis_graph.delete() + def test_param(self): + redis_graph = Graph('params', self.r) + + params = [1, 2.3, "str", True, False, None, [0, 1, 2]] + query = "RETURN $param" + for param in params: + result = redis_graph.query(query, {'param': param}) + expected_results = [[param]] + self.assertEqual(expected_results, result.result_set) + + # All done, remove graph. + redis_graph.delete() if __name__ == '__main__': unittest.main()