Search code examples
memgraphdb

How can I create nodes in Memgraph directly from Python?


I have an application that uses Memgraph. At the moment, queries are written using Cypher. I'd like to move them to Python. What would be the equivalent of Cypher clauses CREATE (e.g.CREATE (:City {name: 'London'});) and MERGE (e.g. MERGE (:City {name: 'Dublin'});)?


Solution

  • First, you need to install GQLAlchemy. GQLAlchemy is a standalone Object Grap Mapper (OGM) for Python.

    For creating nodes, use the method node() after create():

    from gqlalchemy import Create
    
    query = Create().node(labels="City", name="London").execute()
    

    When you use the merge() method instead of create(), the node won't be created if it already exists, it will only be updated if the properties don't match:

    from gqlalchemy import Merge
    
    query = Merge().node(labels="City", name="Dublin").execute()