Graph storage​ with Neo4J and 🐍 Python

Daniil Ekzarian
Reflash Programming Adventures
2 min readFeb 18, 2018

Recently I had time to try new stuff, so I decided to use Neo4J database.

Neo4J is a graph database, that means that you can store objects as graph nodes with associated data and have connections between those objects as graph edges.

OWXsS6PfkdM.jpg

Basic installation of Neo4J is pretty easy. Use this link to download and install Neo4J — Download.

Neo4J has lots of drivers to connect, written for different languages. We will use Python driver and I will show few simple functions.

First install neo4j package pip install neo4j-driver and import it in your python script - from neo4j.v1 import GraphDatabase, Driver.

To connect to the database:

This function can be used to connect to graph database, change username and pass to user credentials that you added to database previously.

​​​​127.0.0.1:7687 is default Neo4J address, so if you configured it differently, change it accordingly.

Now let's add a simplest node:

After creating a session with the database we run Cypher language query:

CREATE (a:Node {name:{name}})

This will create a node with type Node and a property name.

The second step is to create a connection between those with an edge:

Here we use a bit more complex query, so we'll try to understand it:

MATCH (n1:Node),(n2:Node) WHERE n1.name = {n1} AND n2.name = {n2} CREATE (n1)-[r:CONNECTED]->(n2)

First we find two nodes of type Node with names n1 and n2and then we create a labeled with CONNECTEDedge between those nodes.

I hope these examples will lead you to further research in a field of graph databases, because it is a very interesting topic.

Links

1 Neo4J download link - https://neo4j.com/download/other-releases/#releases

2 Cypher query language - https://neo4j.com/developer/cypher-query-language/

--

--