or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

database.mdexceptions.mdindex.mdnodes.mdproperties.mdqueries.mdrelationships.md

relationships.mddocs/

0

# Relationship Management

1

2

Powerful relationship definition and traversal system in neomodel with cardinality constraints, supporting both simple connections and complex relationship models with properties. Includes both synchronous and asynchronous implementations.

3

4

## Capabilities

5

6

### Relationship Definition Classes

7

8

Classes for defining different types of relationships between nodes with cardinality and direction constraints.

9

10

```python { .api }

11

class Relationship:

12

"""

13

Basic relationship definition for synchronous operations.

14

15

Args:

16

cls_name (str): Target node class name

17

relation_type (str): Neo4j relationship type

18

**kwargs: Additional relationship configuration

19

"""

20

def __init__(self, cls_name, relation_type, **kwargs): ...

21

22

class RelationshipTo(Relationship):

23

"""

24

Outgoing relationship definition for synchronous operations.

25

26

Args:

27

cls_name (str): Target node class name

28

relation_type (str): Neo4j relationship type

29

cardinality (class, optional): Cardinality constraint class

30

model (class, optional): StructuredRel class for relationship properties

31

**kwargs: Additional relationship configuration

32

"""

33

def __init__(self, cls_name, relation_type, cardinality=None, model=None, **kwargs): ...

34

35

class RelationshipFrom(Relationship):

36

"""

37

Incoming relationship definition for synchronous operations.

38

39

Args:

40

cls_name (str): Source node class name

41

relation_type (str): Neo4j relationship type

42

cardinality (class, optional): Cardinality constraint class

43

model (class, optional): StructuredRel class for relationship properties

44

**kwargs: Additional relationship configuration

45

"""

46

def __init__(self, cls_name, relation_type, cardinality=None, model=None, **kwargs): ...

47

48

class RelationshipDefinition:

49

"""

50

Generic relationship configuration class for synchronous operations.

51

52

Args:

53

relation_type (str): Neo4j relationship type

54

cls_name (str): Target/source node class name

55

direction (int): Relationship direction (OUTGOING, INCOMING, EITHER)

56

**kwargs: Additional configuration

57

"""

58

def __init__(self, relation_type, cls_name, direction, **kwargs): ...

59

60

# Async relationship classes

61

class AsyncRelationship:

62

"""Basic relationship definition for asynchronous operations."""

63

def __init__(self, cls_name, relation_type, **kwargs): ...

64

65

class AsyncRelationshipTo(AsyncRelationship):

66

"""Outgoing relationship definition for asynchronous operations."""

67

def __init__(self, cls_name, relation_type, cardinality=None, model=None, **kwargs): ...

68

69

class AsyncRelationshipFrom(AsyncRelationship):

70

"""Incoming relationship definition for asynchronous operations."""

71

def __init__(self, cls_name, relation_type, cardinality=None, model=None, **kwargs): ...

72

73

class AsyncRelationshipDefinition:

74

"""Generic relationship configuration class for asynchronous operations."""

75

def __init__(self, relation_type, cls_name, direction, **kwargs): ...

76

```

77

78

### Structured Relationship Classes

79

80

Base classes for creating relationship models with properties.

81

82

```python { .api }

83

class StructuredRel:

84

"""

85

Base class for relationship models with properties in synchronous mode.

86

87

Provides property management and CRUD operations for relationships.

88

"""

89

90

def save(self):

91

"""

92

Save relationship properties to Neo4j database.

93

94

Returns:

95

self: The saved relationship instance

96

"""

97

98

def delete(self):

99

"""

100

Delete the relationship from Neo4j database.

101

102

Returns:

103

bool: True if deletion was successful

104

"""

105

106

class AsyncStructuredRel:

107

"""

108

Base class for relationship models with properties in asynchronous mode.

109

110

Provides async property management and CRUD operations for relationships.

111

"""

112

113

async def save(self):

114

"""

115

Asynchronously save relationship properties to Neo4j database.

116

117

Returns:

118

self: The saved relationship instance

119

"""

120

121

async def delete(self):

122

"""

123

Asynchronously delete the relationship from Neo4j database.

124

125

Returns:

126

bool: True if deletion was successful

127

"""

128

```

129

130

### Relationship Management Classes

131

132

Classes that handle relationship collections and operations on node instances.

133

134

```python { .api }

135

class RelationshipManager:

136

"""

137

Manages relationship collections for synchronous operations.

138

139

Provides methods for connecting, disconnecting, and querying relationships.

140

"""

141

142

def connect(self, node, properties=None):

143

"""

144

Create a relationship to another node.

145

146

Args:

147

node: Target node instance

148

properties (dict, optional): Relationship properties

149

150

Returns:

151

Relationship instance or bool

152

"""

153

154

def disconnect(self, node):

155

"""

156

Remove relationship to another node.

157

158

Args:

159

node: Target node instance

160

161

Returns:

162

bool: True if disconnection was successful

163

"""

164

165

def all(self):

166

"""

167

Get all related nodes.

168

169

Returns:

170

list: List of related node instances

171

"""

172

173

def get(self, **kwargs):

174

"""

175

Get a single related node matching criteria.

176

177

Args:

178

**kwargs: Filter criteria

179

180

Returns:

181

Node instance

182

"""

183

184

def filter(self, **kwargs):

185

"""

186

Filter related nodes by criteria.

187

188

Args:

189

**kwargs: Filter criteria

190

191

Returns:

192

NodeSet: Filtered node collection

193

"""

194

195

class AsyncRelationshipManager:

196

"""

197

Manages relationship collections for asynchronous operations.

198

"""

199

200

async def connect(self, node, properties=None):

201

"""Asynchronously create a relationship to another node."""

202

203

async def disconnect(self, node):

204

"""Asynchronously remove relationship to another node."""

205

206

async def all(self):

207

"""Asynchronously get all related nodes."""

208

209

async def get(self, **kwargs):

210

"""Asynchronously get a single related node matching criteria."""

211

212

async def filter(self, **kwargs):

213

"""Asynchronously filter related nodes by criteria."""

214

```

215

216

### Cardinality Classes

217

218

Classes that enforce relationship cardinality constraints.

219

220

```python { .api }

221

# Synchronous cardinality classes

222

class One:

223

"""

224

Exactly one relationship constraint.

225

226

Ensures that exactly one relationship of this type exists.

227

"""

228

229

class ZeroOrOne:

230

"""

231

Zero or one relationship constraint.

232

233

Allows at most one relationship of this type.

234

"""

235

236

class OneOrMore:

237

"""

238

One or more relationships constraint.

239

240

Requires at least one relationship of this type.

241

"""

242

243

class ZeroOrMore:

244

"""

245

Zero or more relationships constraint.

246

247

No limit on the number of relationships (default behavior).

248

"""

249

250

# Asynchronous cardinality classes

251

class AsyncOne:

252

"""Exactly one relationship constraint for async operations."""

253

254

class AsyncZeroOrOne:

255

"""Zero or one relationship constraint for async operations."""

256

257

class AsyncOneOrMore:

258

"""One or more relationships constraint for async operations."""

259

260

class AsyncZeroOrMore:

261

"""Zero or more relationships constraint for async operations."""

262

```

263

264

## Usage Examples

265

266

### Basic Relationship Definition

267

268

```python

269

from neomodel import (

270

StructuredNode, StringProperty, RelationshipTo,

271

RelationshipFrom, ZeroOrMore, One

272

)

273

274

class Person(StructuredNode):

275

name = StringProperty(required=True)

276

277

# Outgoing relationships

278

friends = RelationshipTo('Person', 'FRIENDS_WITH', cardinality=ZeroOrMore)

279

works_at = RelationshipTo('Company', 'WORKS_AT', cardinality=One)

280

281

# Incoming relationships

282

managed_by = RelationshipFrom('Person', 'MANAGES', cardinality=ZeroOrMore)

283

284

class Company(StructuredNode):

285

name = StringProperty(required=True)

286

287

# Employees working at this company

288

employees = RelationshipFrom('Person', 'WORKS_AT', cardinality=ZeroOrMore)

289

290

# Create nodes and relationships

291

alice = Person(name="Alice").save()

292

bob = Person(name="Bob").save()

293

company = Company(name="TechCorp").save()

294

295

# Connect nodes

296

alice.friends.connect(bob)

297

alice.works_at.connect(company)

298

```

299

300

### Relationship Properties

301

302

```python

303

from neomodel import (

304

StructuredNode, StructuredRel, StringProperty,

305

DateTimeProperty, RelationshipTo

306

)

307

308

class FriendshipRel(StructuredRel):

309

"""Relationship model with properties."""

310

since = DateTimeProperty(default_now=True)

311

strength = StringProperty(choices=['weak', 'strong'], default='weak')

312

313

class Person(StructuredNode):

314

name = StringProperty(required=True)

315

316

# Relationship with properties

317

friends = RelationshipTo(

318

'Person',

319

'FRIENDS_WITH',

320

model=FriendshipRel,

321

cardinality=ZeroOrMore

322

)

323

324

# Create friendship with properties

325

alice = Person(name="Alice").save()

326

bob = Person(name="Bob").save()

327

328

# Connect with relationship properties

329

friendship = alice.friends.connect(bob, {'strength': 'strong'})

330

friendship.since = datetime.now()

331

friendship.save()

332

```

333

334

### Async Relationship Operations

335

336

```python

337

from neomodel import (

338

AsyncStructuredNode, AsyncStructuredRel, StringProperty,

339

AsyncRelationshipTo, AsyncZeroOrMore

340

)

341

342

class AsyncFriendshipRel(AsyncStructuredRel):

343

strength = StringProperty(default='weak')

344

345

class AsyncPerson(AsyncStructuredNode):

346

name = StringProperty(required=True)

347

friends = AsyncRelationshipTo(

348

'AsyncPerson',

349

'FRIENDS_WITH',

350

model=AsyncFriendshipRel,

351

cardinality=AsyncZeroOrMore

352

)

353

354

async def create_friendship():

355

alice = await AsyncPerson(name="Alice").save()

356

bob = await AsyncPerson(name="Bob").save()

357

358

# Async relationship operations

359

await alice.friends.connect(bob, {'strength': 'strong'})

360

friends = await alice.friends.all()

361

362

return friends

363

```

364

365

### Relationship Traversal and Filtering

366

367

```python

368

# Query through relationships

369

alice_friends = alice.friends.all()

370

close_friends = alice.friends.filter(strength='strong')

371

work_colleagues = alice.works_at.get().employees.all()

372

373

# Disconnect relationships

374

alice.friends.disconnect(bob)

375

376

# Check if relationship exists

377

is_friend = bob in alice.friends.all()

378

379

# Get relationship properties

380

for friend in alice.friends.all():

381

rel = alice.friends.relationship(friend)

382

print(f"Friends since: {rel.since}")

383

```

384

385

### Complex Relationship Patterns

386

387

```python

388

from neomodel import OUTGOING, INCOMING, EITHER

389

390

class Person(StructuredNode):

391

name = StringProperty(required=True)

392

393

# Bidirectional relationship

394

knows = Relationship('Person', 'KNOWS', direction=EITHER)

395

396

# Self-referencing with different roles

397

manages = RelationshipTo('Person', 'MANAGES')

398

managed_by = RelationshipFrom('Person', 'MANAGES')

399

400

# Traverse in different directions

401

manager = person.managed_by.get()

402

subordinates = person.manages.all()

403

mutual_connections = person.knows.all()

404

```

405

406

## Types

407

408

```python { .api }

409

# Relationship direction constants

410

OUTGOING: int # Value: 1

411

INCOMING: int # Value: -1

412

EITHER: int # Value: 0

413

414

# Cardinality constraint types

415

CardinalityClass = Union[One, ZeroOrOne, OneOrMore, ZeroOrMore]

416

AsyncCardinalityClass = Union[AsyncOne, AsyncZeroOrOne, AsyncOneOrMore, AsyncZeroOrMore]

417

418

# Relationship operation return types

419

RelationshipInstance = Union[StructuredRel, AsyncStructuredRel]

420

ConnectionResult = Union[RelationshipInstance, bool]

421

```