Skip to main content

Explore Many-to-Many relationships

Exploring Many-to-Many Relationships in Neo4j

The first step will be to add a TagsMixin into workshop_b2/lab2/database/models.py.

info

This has already been completed, but we'll be going through the code.

If you search for TagMixin, you will find the following code:

class TagMixin:
tags: list[Tag] = Field(default_factory=list)

def add_tags(self, db: Driver, tags: list[Tag]):
"""Add tags to a node.

Args:
db (Driver): Neo4j driver instance.
tags (list[Tag]): List of tags to add.
"""
node_label = self.__class__.__name__.replace("Model", "").title()
node_short = node_label[0]
for tag in tags:
query = (
f"MATCH ({node_short}:{node_label}" + " {name: $name})"
"OPTIONAL MATCH (t:Tag {name: " + f'"{tag.name}"' + "})"
f"MERGE ({node_short})-[:TAGGED]->(t)"
)
db.execute_query(
query, {"name": self.name, "tags": [t.model_dump() for t in tags]}
)

The TagsMixin class gets added to the DeviceModel.

class DeviceModel(Device, TagMixin):

Next, the create method on the DeviceModel adds code to add tags if they're passed into the application.

if self.tags:
self.add_tags(db, self.tags)

# shown for placement purposes
return self.get(db)

Navigate to workshop_b2/models.py and uncomment the tags attribute in the Device class.

warning

This line will break Lab 1 and must be re-commented if you want to start Lab 1.

class Device(BaseModel):
name: str
manufacturer: str | None = None
status: DeviceStatus = DeviceStatus.ACTIVE
tags: list[Tag] = Field(default_factory=list)

Run the load command with the --tags option.

invoke lab2-load --tags

Navigate back to the local Neo4j UI.

Click on any of the tags and then click on the relationship icon.

neo4j-tag-relationship-1

Click on the relationship icon for one of the devices tied to the selected tag.

neo4j-tag-device-1

Now we can see that devices can have multiple tags and tags can have multiple devices.