neomodel Python OGM

6.1.0 · active · verified Thu Apr 16

neomodel is an Object Graph Mapper (OGM) for the Neo4j graph database, providing a Pythonic way to interact with Neo4j. It allows developers to define graph models using Python classes, making it easier to store, retrieve, and query data in a Neo4j database. The current version is 6.1.0, with major releases approximately annually and patch releases as needed.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to connect to a Neo4j database, define a `StructuredNode` model with properties and relationships, create and save nodes, establish relationships, and query the graph using neomodel. It uses environment variables for secure connection details.

import os
from neomodel import StructuredNode, StringProperty, IntegerProperty, RelationshipTo, db

# Configure connection to Neo4j
NEO4J_URL = os.environ.get('NEO4J_BOLT_URL', 'bolt://neo4j:password@localhost:7687')
db.set_connection(NEO4J_URL)

# Define a Node model
class Person(StructuredNode):
    uid = StringProperty(unique_index=True)
    name = StringProperty(index=True, required=True)
    age = IntegerProperty(index=True, default=0)

    # Define a relationship
    friends = RelationshipTo('Person', 'FRIENDS_WITH')

# Ensure labels and constraints are created in the database
Person.ensure_indexes()

# Create and save nodes
jim = Person(uid='jim001', name='Jim', age=32).save()
pam = Person(uid='pam001', name='Pam', age=30).save()

# Create a relationship
jim.friends.connect(pam)

# Retrieve and query
found_jim = Person.nodes.get(uid='jim001')
print(f"Found: {found_jim.name}, Age: {found_jim.age}")

# Get friends
print(f"{found_jim.name} is friends with:")
for friend in found_jim.friends.all():
    print(f"- {friend.name}")

# Clear database for example (use with caution in production)
# db.cypher_query("MATCH (n) DETACH DELETE n")
db.close_connection()

view raw JSON →