Running a Cypher Query With Parameters Through a Python Script

Madison Ostermann
The Startup
Published in
2 min readDec 13, 2020
Clean, minimal workspace setup with laptop displaying code in front of a window.

I’ve been working on a project for a few months now that has involved tying a Neo4j database to a Dash application, which ultimately comes down to being able to run Cypher queries through Python code.

The library Py2Neo has been incredibly useful for this; you can run Cypher queries as-is or use the Py2Neo functions to perform similar actions.
My personal preference is running Cypher queries as-is because I can simply copy and paste the code to and from the Neo4j browser.

Cypher Query in Neo4j Browser: 
MATCH (n:Person) RETURN n.name AS name
Cypher Query with Py2Neo:
graph.run("""MATCH (n:Person) RETURN n.name AS name""").data()

See how easy that is?

This article details Py2Neo further.

Sometimes we need to dynamically substitute parameters into a query though. For a class project earlier this semester, I was trying to add descriptions for people nodes in my database.

This involved iterating through the names of people nodes, grabbing the person’s description from the Wikipedia API, then assigning the description to the person node in question. Doing this requires substitution of the person’s name into a Cypher query; the following code is how this was done.

It’s a simple .format() substitution on the string containing the Cypher query — nothing fancy, but incredibly useful and easy!

I hope this short tutorial was useful. If you have any additional methods to accomplish the same goal, please comment and let’s share our knowledge!

By the way, here’s the larger project from which this was taken!

If you’d like to see how I’ve leveraged Py2Neo in an automated script that builds a Neo4j database, check out this article!

--

--

Madison Ostermann
The Startup

Data & Code Person | NASA | BS Computer Science & MS Analytics