Search code examples
memgraphdb

How can I manage Memgraph Docker instances using Python?


I'm developing Python based graph-based applications I want manage different Memgraph database server instances directly from Python.

Can this be done?


Solution

  • GQLAlchemy instance_runner module allows you to start, stop, connect and monitor Memgraph instances with directly from your Python scripts.

    First, perform all the necessary imports:

    from gqlalchemy.instance_runner import (
        DockerImage,
        MemgraphInstanceDocker
    )
    

    The following code will create a Memgraph instance, start it and return a connection object:

    memgraph_instance = MemgraphInstanceDocker(
        docker_image=DockerImage.MEMGRAPH, docker_image_tag="latest", host="0.0.0.0", port=7687
    )
    memgraph = memgraph_instance.start_and_connect(restart=False)
    

    Start querying the database with:

    memgraph.execute_and_fetch("RETURN 'Memgraph is running' AS result"))[0]["result"]
    

    You can pass configuration flags using a dictionary:

    config={"--log-level": "TRACE"}
    memgraph_instance = MemgraphInstanceDocker(config=config)
    

    To stop a Memgraph instance, call the stop() method:

    memgraph_instance.stop()
    

    To check if a Memgraph instance is running, call the is_running() method:

    memgraph_instance.is_running()