The Startup
Published in

The Startup

Running a Cypher Query With Parameters Through a Python Script

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!

--

--

--

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +756K followers.

Recommended from Medium

Run It

Faster inter-service communication with streams

Create your own RaspberryPi MusicBox

GitHub Beginner

How to win in fantasy football

C++ pointers and references explained: tutorial with examples and code

Optimization & Modelling with Omer

Making of Vidhya.io

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Madison Gipson

Madison Gipson

Data Scientist & SWE | NASA | BS Computer Science & MBA Student

More from Medium

Install and run TensorFlow with Jupyter on Mac M1 pro: 2022 guide

CytOnda: using DASH Cytoscape for organizational network discovery

CytOnda Dashboard result

10 Features Your Streamlit ML App Can’t Do Without — Implemented

Build Your Voice Translation App with AWS S3, Transcribe, Polly, and DynamoDB