An object mapper for the neo4j graph database.
npx @tessl/cli install tessl/pypi-neomodel@5.5.00
# Neomodel
1
2
An Object Graph Mapper (OGM) for the Neo4j graph database, built on the neo4j-python-driver. Neomodel provides familiar class-based model definitions with proper inheritance, a powerful query API, schema enforcement through cardinality restrictions, full transaction support, and both synchronous and asynchronous programming patterns.
3
4
## Package Information
5
6
- **Package Name**: neomodel
7
- **Language**: Python
8
- **Installation**: `pip install neomodel`
9
10
## Core Imports
11
12
```python
13
import neomodel
14
```
15
16
Common patterns for working with neomodel:
17
18
```python
19
from neomodel import (
20
StructuredNode, StringProperty, IntegerProperty,
21
RelationshipTo, config
22
)
23
```
24
25
For async operations:
26
27
```python
28
from neomodel import (
29
AsyncStructuredNode, AsyncRelationshipTo, adb
30
)
31
```
32
33
## Basic Usage
34
35
```python
36
from neomodel import (
37
StructuredNode, StringProperty, IntegerProperty,
38
RelationshipTo, config
39
)
40
41
# Configure database connection
42
config.DATABASE_URL = 'bolt://neo4j:password@localhost:7687'
43
44
# Define node models
45
class Person(StructuredNode):
46
name = StringProperty(unique_index=True, required=True)
47
age = IntegerProperty()
48
49
# Define relationships
50
friends = RelationshipTo('Person', 'FRIENDS_WITH')
51
52
class Movie(StructuredNode):
53
title = StringProperty(required=True)
54
year = IntegerProperty()
55
56
# Create and connect nodes
57
person = Person(name="Alice", age=30).save()
58
movie = Movie(title="The Matrix", year=1999).save()
59
60
# Query nodes
61
alice = Person.nodes.get(name="Alice")
62
matrix_movies = Movie.nodes.filter(title__contains="Matrix")
63
64
# Traverse relationships
65
alice_friends = alice.friends.all()
66
```
67
68
## Architecture
69
70
Neomodel uses a dual-architecture approach:
71
72
- **Synchronous API**: Traditional blocking operations using `StructuredNode`, `db`, and sync-specific classes
73
- **Asynchronous API**: Non-blocking operations using async/await with `AsyncStructuredNode`, `adb`, and async-specific classes
74
75
Key components:
76
77
- **Node Models**: StructuredNode base classes for defining graph entities
78
- **Property Types**: Typed properties with validation and index support
79
- **Relationship Management**: Cardinality-aware relationship definitions and traversal
80
- **Query System**: NodeSet and Traversal classes for complex graph queries
81
- **Database Interface**: Connection management and transaction support
82
83
## Capabilities
84
85
### Node Management
86
87
Core functionality for defining and working with graph nodes, including model definitions, CRUD operations, and property management for both synchronous and asynchronous contexts.
88
89
```python { .api }
90
class StructuredNode:
91
def save(self): ...
92
def delete(self): ...
93
def refresh(self): ...
94
@classmethod
95
def create(cls, **kwargs): ...
96
@classmethod
97
def get_or_create(cls, **kwargs): ...
98
99
class AsyncStructuredNode:
100
async def save(self): ...
101
async def delete(self): ...
102
async def refresh(self): ...
103
@classmethod
104
async def create(cls, **kwargs): ...
105
@classmethod
106
async def get_or_create(cls, **kwargs): ...
107
```
108
109
[Node Management](./nodes.md)
110
111
### Property Types
112
113
Comprehensive set of typed properties for node and relationship attributes, including basic types, specialized validation, date/time handling, and indexing support.
114
115
```python { .api }
116
class StringProperty:
117
def __init__(self, max_length=None, choices=None, **kwargs): ...
118
119
class IntegerProperty:
120
def __init__(self, **kwargs): ...
121
122
class DateTimeProperty:
123
def __init__(self, default_now=False, **kwargs): ...
124
125
class JSONProperty:
126
def __init__(self, **kwargs): ...
127
128
class UniqueIdProperty:
129
def __init__(self, **kwargs): ...
130
```
131
132
[Property Types](./properties.md)
133
134
### Relationship Management
135
136
Powerful relationship definition and traversal system with cardinality constraints, supporting both simple connections and complex relationship models with properties.
137
138
```python { .api }
139
class RelationshipTo:
140
def __init__(self, cls_name, relation_type, **kwargs): ...
141
142
class RelationshipFrom:
143
def __init__(self, cls_name, relation_type, **kwargs): ...
144
145
class StructuredRel:
146
def save(self): ...
147
def delete(self): ...
148
149
# Cardinality classes
150
class One: ...
151
class ZeroOrOne: ...
152
class OneOrMore: ...
153
class ZeroOrMore: ...
154
```
155
156
[Relationship Management](./relationships.md)
157
158
### Query and Traversal
159
160
Advanced querying capabilities including filtering, ordering, aggregation, and graph traversal operations with support for complex WHERE clauses and relationship navigation.
161
162
```python { .api }
163
class NodeSet:
164
def filter(self, **kwargs): ...
165
def get(self, **kwargs): ...
166
def all(self): ...
167
def order_by(self, *props): ...
168
def limit(self, count): ...
169
170
class Q:
171
def __init__(self, **kwargs): ...
172
def __and__(self, other): ...
173
def __or__(self, other): ...
174
175
class Traversal:
176
def traverse(self, *relationships): ...
177
```
178
179
[Query and Traversal](./queries.md)
180
181
### Database Operations
182
183
Database connection management, schema operations, transaction support, and administrative functions for maintaining Neo4j database state.
184
185
```python { .api }
186
# Database instances
187
db: Database # Sync database interface
188
adb: AsyncDatabase # Async database interface
189
190
# Utility functions
191
def clear_neo4j_database(): ...
192
def install_all_labels(): ...
193
def change_neo4j_password(new_password): ...
194
def drop_constraints(): ...
195
def drop_indexes(): ...
196
```
197
198
[Database Operations](./database.md)
199
200
### Exception Handling
201
202
Comprehensive exception classes for error handling in neomodel operations, providing detailed information about various error conditions during database operations, model definitions, and data validation.
203
204
```python { .api }
205
# Base exceptions
206
class NeomodelException(Exception): ...
207
class DoesNotExist(NeomodelException): ...
208
class MultipleNodesReturned(ValueError, NeomodelException): ...
209
210
# Property exceptions
211
class RequiredProperty(NeomodelException): ...
212
class UniqueProperty(ConstraintValidationFailed): ...
213
class InflateError(ValueError, NeomodelException): ...
214
class DeflateError(ValueError, NeomodelException): ...
215
216
# Cardinality exceptions
217
class CardinalityViolation(NeomodelException): ...
218
class AttemptedCardinalityViolation(NeomodelException): ...
219
220
# Model definition exceptions
221
class NodeClassNotDefined(ModelDefinitionException): ...
222
class RelationshipClassNotDefined(ModelDefinitionException): ...
223
```
224
225
[Exception Handling](./exceptions.md)
226
227
## Configuration
228
229
```python { .api }
230
# Core configuration variables
231
DATABASE_URL: str # Neo4j connection URL (default: "bolt://neo4j:foobarbaz@localhost:7687")
232
DATABASE_NAME: str # Specific database name for multi-database instances
233
DRIVER: object # Custom Neo4j driver instance
234
FORCE_TIMEZONE: bool # Force timezone handling (default: False)
235
236
# Connection configuration options
237
CONNECTION_ACQUISITION_TIMEOUT: float # Timeout for acquiring connections (default: 60.0)
238
CONNECTION_TIMEOUT: float # Connection timeout in seconds (default: 30.0)
239
ENCRYPTED: bool # Enable encrypted connection (default: False)
240
KEEP_ALIVE: bool # Enable connection keep-alive (default: True)
241
MAX_CONNECTION_LIFETIME: int # Maximum connection lifetime in seconds (default: 3600)
242
MAX_CONNECTION_POOL_SIZE: int # Maximum connection pool size (default: 100)
243
MAX_TRANSACTION_RETRY_TIME: float # Maximum transaction retry time (default: 30.0)
244
RESOLVER: object # Custom address resolver (default: None)
245
TRUSTED_CERTIFICATES: object # Certificate trust configuration
246
USER_AGENT: str # User agent string for driver connections
247
```
248
249
Configuration is handled through the `neomodel.config` module, allowing connection URL specification, custom driver instances, and comprehensive connection tuning options. All connection parameters correspond to Neo4j Python driver configuration options.
250
251
## Command-Line Tools
252
253
Neomodel provides several CLI scripts for database management, schema operations, and development utilities.
254
255
```bash
256
# Install database indexes and constraints for model schemas
257
neomodel_install_labels someapp.models
258
259
# Remove all indexes and constraints from database
260
neomodel_remove_labels
261
262
# Inspect existing database and generate Python model definitions
263
neomodel_inspect_database --write-to models.py
264
265
# Generate database diagram in PlantUML or Arrows.app format
266
neomodel_generate_diagram --file-type puml --write-to-dir diagrams/
267
```
268
269
**Available Scripts:**
270
- `neomodel_install_labels` - Setup indexes and constraints for neomodel schemas
271
- `neomodel_remove_labels` - Drop all indexes and constraints from database
272
- `neomodel_inspect_database` - Inspect database schema and generate model definitions
273
- `neomodel_generate_diagram` - Generate database visualization diagrams
274
275
All scripts support `--db` parameter for custom Neo4j connection URLs and will use `NEO4J_BOLT_URL` environment variable as fallback.
276
277
## Data Integration
278
279
Neomodel provides integration utilities for converting query results to popular data science libraries.
280
281
```python { .api }
282
# NumPy integration (requires numpy package)
283
from neomodel.integration.numpy import to_ndarray
284
285
def to_ndarray(query_results: tuple, dtype=None, order="K"):
286
"""
287
Convert cypher query results to numpy ndarray.
288
289
Args:
290
query_results (tuple): Results from db.cypher_query()
291
dtype: Optional numpy data type
292
order (str): Array ordering ('K', 'C', 'F', 'A')
293
294
Returns:
295
numpy.ndarray: Query results as numpy array
296
"""
297
298
# Pandas integration (requires pandas package)
299
from neomodel.integration.pandas import to_dataframe, to_series
300
301
def to_dataframe(query_results: tuple, index=None, dtype=None):
302
"""
303
Convert cypher query results to pandas DataFrame.
304
305
Args:
306
query_results (tuple): Results from db.cypher_query()
307
index: Optional row index for DataFrame
308
dtype: Optional pandas data type
309
310
Returns:
311
pandas.DataFrame: Query results as DataFrame
312
"""
313
314
def to_series(query_results: tuple, field=0, index=None, dtype=None):
315
"""
316
Convert cypher query results to pandas Series.
317
318
Args:
319
query_results (tuple): Results from db.cypher_query()
320
field (int): Column index to extract (default: 0)
321
index: Optional row index for Series
322
dtype: Optional pandas data type
323
324
Returns:
325
pandas.Series: Single column as Series
326
"""
327
```
328
329
### Integration Usage Example
330
331
```python
332
from neomodel import db
333
from neomodel.integration.pandas import to_dataframe
334
from neomodel.integration.numpy import to_ndarray
335
336
# Execute cypher query
337
results = db.cypher_query("MATCH (u:User) RETURN u.name AS name, u.age AS age")
338
339
# Convert to pandas DataFrame
340
df = to_dataframe(results)
341
print(df)
342
# name age
343
# 0 Alice 30
344
# 1 Bob 25
345
346
# Convert to numpy array
347
arr = to_ndarray(results)
348
print(arr)
349
# [['Alice' 30]
350
# ['Bob' 25]]
351
```
352
353
## Types
354
355
```python { .api }
356
# Direction constants
357
OUTGOING: int # Value: 1
358
INCOMING: int # Value: -1
359
EITHER: int # Value: 0
360
361
# Base classes
362
class NeomodelException(Exception): ...
363
class DoesNotExist(NeomodelException): ...
364
class RequiredProperty(ValueError): ...
365
class UniqueProperty(ValueError): ...
366
```