Skip to main content

How to create a query module in Python

Query modules can be implemented using the Python API provided by Memgraph. In this tutorial, we will learn how to develop a query module in Python on the example of the random walk algorithm.


There are three options for installing and working with Memgraph MAGE:

  1. Pulling the memgraph/memgraph-mage image: check the Docker Hubinstallation guide.
  2. Building a Docker image from the MAGE repository: check the Docker build installation guide.
  3. Building MAGE from source: check the Build from source on Linuxinstallation guide.

Developing a module


These steps are the same for every type of MAGE installation: Docker Hub, Docker build and Build from source on Linux.

Position yourself in the MAGE repository you cloned earlier. Specifically, go in the python subdirectory and create a new file called

└── mage

For this part, we will import mgp, Memgraph's internal data structure module. Among others, it contains definitions for Vertex and Edge data structures.


Install the mgp Python module so your editor can use typing annotations properly and suggest methods and classes it contains. You can install the module by running pip install mgp.

Here's the code for the random walk algorithm:

import mgp
import random

def get_path(
start: mgp.Vertex,
length: int = 10,
) -> mgp.Record(path=mgp.Path):
"""Generates a random path of length `length` or less starting
from the `start` vertex.

:param mgp.Vertex start: The starting node of the walk.
:param int length: The number of edges to traverse.
:return: Random path.
:rtype: mgp.Record(mgp.Path)
path = mgp.Path(start)
vertex = start
for _ in range(length):
edge = random.choice(list(vertex.out_edges))
vertex = edge.to_vertex
except IndexError:

return mgp.Record(path=path)

The get_path is decorated with the @mgp.read_proc decorator, which tells Memgraph it's a read procedure, meaning it won't make changes to the graph. The path is created from the start node, and edges are appended to it iteratively.

Importing, querying and testing a module

Now in order to import, query and test a module, check out the following page.

Feel free to create an issue or open a pull request on our GitHub repo to speed up the development.
Also, don't forget to throw us a star on GitHub. ⭐