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:
- Pulling the
memgraph/memgraph-mageimage: check the
Docker Hubinstallation guide.
- Building a Docker image from the MAGE repository: check the
Docker buildinstallation guide.
- 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
mgp Python module so your editor can use typing annotations
properly and suggest methods and classes it contains. You can install the module
pip install mgp.
Here's the code for the random walk algorithm:
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.
path = mgp.Path(start)
vertex = start
for _ in range(length):
edge = random.choice(list(vertex.out_edges))
vertex = edge.to_vertex
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
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. ⭐