CRUD Operations

How to access and modify Nodes and Edges

The Graphiti library uses 8 core classes to add data to your graph:

  • Node
  • EpisodicNode
  • EntityNode
  • Edge
  • EpisodicEdge
  • EntityEdge
  • CommunityNode
  • CommunityEdge

The generic Node and Edge classes are abstract base classes, and the other 4 classes inherit from them. Each of EpisodicNode, EntityNode, EpisodicEdge, and EntityEdge have fully supported CRUD operations.

The save method performs a find or create based on the uuid of the object, and will add or update any other data from the class to the graph. A driver must be provided to the save method. The Entity Node save method is shown below as a sample.

1 async def save(self, driver: AsyncDriver):
2 result = await driver.execute_query(
3 """
4 MERGE (n:Entity {uuid: $uuid})
5 SET n = {uuid: $uuid, name: $name, name_embedding: $name_embedding, summary: $summary, created_at: $created_at}
6 RETURN n.uuid AS uuid""",
7 uuid=self.uuid,
8 name=self.name,
9 summary=self.summary,
10 name_embedding=self.name_embedding,
11 created_at=self.created_at,
12 )
13
14 logger.info(f'Saved Node to neo4j: {self.uuid}')
15
16 return result

Graphiti also supports hard deleting nodes and edges using the delete method, which also requires a driver.

1 async def delete(self, driver: AsyncDriver):
2 result = await driver.execute_query(
3 """
4 MATCH (n:Entity {uuid: $uuid})
5 DETACH DELETE n
6 """,
7 uuid=self.uuid,
8 )
9
10 logger.info(f'Deleted Node: {self.uuid}')
11
12 return result

Finally, Graphiti also provides class methods to get nodes and edges by uuid. Note that because these are class methods they are called using the class rather than an instance of the class.

1 async def get_by_uuid(cls, driver: AsyncDriver, uuid: str):
2 records, _, _ = await driver.execute_query(
3 """
4 MATCH (n:Entity {uuid: $uuid})
5 RETURN
6 n.uuid As uuid,
7 n.name AS name,
8 n.created_at AS created_at,
9 n.summary AS summary
10 """,
11 uuid=uuid,
12 )
13
14 nodes: list[EntityNode] = []
15
16 for record in records:
17 nodes.append(
18 EntityNode(
19 uuid=record['uuid'],
20 name=record['name'],
21 labels=['Entity'],
22 created_at=record['created_at'].to_native(),
23 summary=record['summary'],
24 )
25 )
26
27 logger.info(f'Found Node: {uuid}')
28
29 return nodes[0]