This example demonstrates how to use Memgraph triggers (both BEFORE COMMIT and AFTER COMMIT) with the Neo4j Python driver (neo4j) to simulate real-world data mutation and side-effects using concurrent transactions.
The script performs the following actions:
-
Connects to a running Memgraph instance using the Neo4j Python driver.
-
Creates a global node that serves as the target of trigger-generated relationships.
-
Creates a
BEFORE COMMITtrigger that automatically creates an edge from every newly created node to the global node. -
Uses two separate sessions to simulate concurrent transactions:
- One modifies the global node in a transaction that remains open.
- The other creates a node to test whether the trigger can access the global node (it can't if it's uncommitted).
-
Drops the
BEFORE COMMITtrigger, then repeats the same process with anAFTER COMMITtrigger. -
Validates the behavior of both trigger types by reading relationships created in the graph.
To run Memgraph Enterprise using Docker:
docker run -it --rm -p 7687:7687 memgraph/memgraph:3.2.0Install the required Python dependency with:
pip install neo4jYour requirements.txt should include:
neo4j
Make sure Memgraph is running, then execute:
python3 memgraph_trigger_demo.py-
BEFORE COMMIT triggers:
- Run inside the same transaction that caused the event.
- Cannot see changes made in uncommitted transactions (i.e., isolation applies).
-
AFTER COMMIT triggers:
- Run after the original transaction commits.
- Can access the full committed graph state.
This script showcases both trigger types and how transaction isolation affects their behavior.
memgraph_trigger_demo.py # Python script that sets up and tests triggers
requirements.txt # Python dependencies
README.md # This file
Tested with:
- Memgraph v3.2
- Neo4j Python Driver v5.16.0+
This example works with Memgraph Community Edition.
Reach out to us on the Memgraph Discord server — we’re happy to help!