Search code examples
pythonmemgraphdb

Connecting to Memgraph graph database from Python


What do I need to have in place to connect to a running instance of Memgraph from Python?


Solution

  • To connect to Memgraph using Python you will need:

    • A running Memgraph instance. If you need to set up Memgraph, take a look at the Installation guide.
    • The GQLAlchemy client. A Memgraph OGM (Object Graph Mapper) for the Python programming language.

    Create a new Python script and add the following code to it: from gqlalchemy import Memgraph

    # Make a connection to the database
    memgraph = Memgraph(host='127.0.0.1', port=7687)
    
    # Delete all nodes and relationships
    query = "MATCH (n) DETACH DELETE n"
    
    # Execute the query
    memgraph.execute(query)
    
    # Create a node with the label FirstNode and message property with the value "Hello, World!"
    query = """CREATE (n:FirstNode)
               SET n.message = '{message}'
               RETURN 'Node '  + id(n) + ': ' + n.message AS result""".format(message="Hello, World!")
    
    # Execute the query
    results = memgraph.execute_and_fetch(query)
    
    # Print the first member
    print(list(results)[0]['result'])
    

    You can find detailed instructions in the Memgraph documentation.