-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathadapter.py
More file actions
1614 lines (1286 loc) · 51.2 KB
/
adapter.py
File metadata and controls
1614 lines (1286 loc) · 51.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Neo4j Adapter for Graph Database"""
import json
import asyncio
from uuid import UUID
from textwrap import dedent
from neo4j import AsyncSession
from neo4j import AsyncGraphDatabase
from neo4j.exceptions import Neo4jError
from contextlib import asynccontextmanager
from typing import Optional, Any, List, Dict, Type, Tuple, Coroutine
from cognee.modules.observability import OtelStatusCode as StatusCode
from cognee.infrastructure.engine import DataPoint
from cognee.modules.engine.utils.generate_timestamp_datapoint import date_to_int
from cognee.tasks.temporal_graph.models import Timestamp
from cognee.shared.logging_utils import get_logger, ERROR
from cognee.infrastructure.databases.graph.graph_db_interface import (
GraphDBInterface,
)
from cognee.modules.storage.utils import JSONEncoder
from distributed.utils import override_distributed
from distributed.tasks.queued_add_nodes import queued_add_nodes
from distributed.tasks.queued_add_edges import queued_add_edges
from .neo4j_metrics_utils import (
get_avg_clustering,
get_edge_density,
get_num_connected_components,
get_shortest_path_lengths,
get_size_of_connected_components,
count_self_loops,
)
from .deadlock_retry import deadlock_retry
from cognee.modules.observability import new_span
from cognee.modules.observability.tracing import (
COGNEE_DB_SYSTEM,
COGNEE_DB_QUERY,
COGNEE_DB_ROW_COUNT,
redact_secrets,
)
logger = get_logger("Neo4jAdapter")
BASE_LABEL = "__Node__"
class Neo4jAdapter(GraphDBInterface):
"""
Adapter for interacting with a Neo4j graph database, implementing the GraphDBInterface.
This class provides methods for querying, adding, deleting nodes and edges, as well as
managing sessions and projecting graphs.
"""
def __init__(
self,
graph_database_url: str,
graph_database_username: Optional[str] = None,
graph_database_password: Optional[str] = None,
graph_database_name: Optional[str] = None,
driver: Optional[Any] = None,
):
# Only use auth if both username and password are provided
auth = None
if graph_database_username and graph_database_password:
auth = (graph_database_username, graph_database_password)
elif graph_database_username or graph_database_password:
logger = get_logger(__name__)
logger.warning("Neo4j credentials incomplete – falling back to anonymous connection.")
self.graph_database_name = graph_database_name
self.driver = driver or AsyncGraphDatabase.driver(
graph_database_url,
auth=auth,
max_connection_lifetime=120,
notifications_min_severity="OFF",
keep_alive=True,
)
async def initialize(self) -> None:
"""
Initializes the database: adds uniqueness constraint on id and performs indexing
"""
await self.query(
(f"CREATE CONSTRAINT IF NOT EXISTS FOR (n:`{BASE_LABEL}`) REQUIRE n.id IS UNIQUE;")
)
@asynccontextmanager
async def get_session(self) -> AsyncSession:
"""
Get a session for database operations.
"""
async with self.driver.session(database=self.graph_database_name) as session:
yield session
async def is_empty(self) -> bool:
query = """
RETURN EXISTS {
MATCH (n)
} AS node_exists;
"""
query_result = await self.query(query)
return not query_result[0]["node_exists"]
@deadlock_retry()
async def query(
self,
query: str,
params: Optional[Dict[str, Any]] = None,
) -> List[Dict[str, Any]]:
"""
Execute a Cypher query against the Neo4j database and return the result.
Parameters:
-----------
- query (str): A string containing the Cypher query to execute.
- params (Optional[Dict[str, Any]]): A dictionary of parameters to be passed to the
query. (default None)
Returns:
--------
- List[Dict[str, Any]]: A list of dictionaries representing the result of the query
execution.
"""
with new_span("cognee.db.graph.query") as otel_span:
otel_span.set_attribute(COGNEE_DB_SYSTEM, "neo4j")
otel_span.set_attribute(COGNEE_DB_QUERY, redact_secrets(query[:500]))
try:
async with self.get_session() as session:
result = await session.run(query, parameters=params)
data = await result.data()
otel_span.set_attribute(COGNEE_DB_ROW_COUNT, len(data))
return data
except Neo4jError as error:
otel_span.set_status(StatusCode.ERROR, str(error))
otel_span.record_exception(error)
logger.error("Neo4j query error: %s", error, exc_info=True)
raise error
async def has_node(self, node_id: str) -> bool:
"""
Check if a node with the specified ID exists in the database.
Parameters:
-----------
- node_id (str): The ID of the node to check for existence.
Returns:
--------
- bool: True if the node exists, otherwise False.
"""
results = self.query(
f"""
MATCH (n:`{BASE_LABEL}`)
WHERE n.id = $node_id
RETURN COUNT(n) > 0 AS node_exists
""",
{"node_id": node_id},
)
return results[0]["node_exists"] if len(results) > 0 else False
async def add_node(self, node: DataPoint):
"""
Add a new node to the database based on the provided DataPoint object.
Parameters:
-----------
- node (DataPoint): An instance of DataPoint representing the node to add.
Returns:
--------
The result of the query execution, typically the ID of the added node.
"""
serialized_properties = self.serialize_properties(node.model_dump())
query = dedent(
f"""MERGE (node: `{BASE_LABEL}`{{id: $node_id}})
ON CREATE SET node += $properties, node.updated_at = timestamp()
ON MATCH SET node += $properties, node.updated_at = timestamp()
WITH node, $node_label AS label
CALL apoc.create.addLabels(node, [label]) YIELD node AS labeledNode
RETURN ID(labeledNode) AS internal_id, labeledNode.id AS nodeId"""
)
params = {
"node_id": str(node.id),
"node_label": type(node).__name__,
"properties": serialized_properties,
}
return await self.query(query, params)
@override_distributed(queued_add_nodes)
async def add_nodes(self, nodes: list[DataPoint]) -> None:
"""
Add multiple nodes to the database in a single query.
Parameters:
-----------
- nodes (list[DataPoint]): A list of DataPoint instances representing the nodes to
add.
Returns:
--------
- None: None
"""
query = f"""
UNWIND $nodes AS node
MERGE (n: `{BASE_LABEL}`{{id: node.node_id}})
ON CREATE SET n += node.properties, n.updated_at = timestamp()
ON MATCH SET n += node.properties, n.updated_at = timestamp()
WITH n, node.label AS label
CALL apoc.create.addLabels(n, [label]) YIELD node AS labeledNode
RETURN ID(labeledNode) AS internal_id, labeledNode.id AS nodeId
"""
nodes = [
{
"node_id": str(node.id),
"label": type(node).__name__,
"properties": self.serialize_properties(dict(node)),
}
for node in nodes
]
results = await self.query(query, dict(nodes=nodes))
return results
async def extract_node(self, node_id: str):
"""
Retrieve a single node from the database by its ID.
Parameters:
-----------
- node_id (str): The ID of the node to retrieve.
Returns:
--------
The node represented as a dictionary, or None if it does not exist.
"""
results = await self.extract_nodes([node_id])
return results[0] if len(results) > 0 else None
async def extract_nodes(self, node_ids: List[str]):
"""
Retrieve multiple nodes from the database by their IDs.
Parameters:
-----------
- node_ids (List[str]): A list of IDs for the nodes to retrieve.
Returns:
--------
A list of nodes represented as dictionaries.
"""
query = f"""
UNWIND $node_ids AS id
MATCH (node: `{BASE_LABEL}`{{id: id}})
RETURN node"""
params = {"node_ids": node_ids}
results = await self.query(query, params)
return [result["node"] for result in results]
async def delete_node(self, node_id: str):
"""
Remove a node from the database identified by its ID.
Parameters:
-----------
- node_id (str): The ID of the node to delete.
Returns:
--------
The result of the query execution, typically indicating success or failure.
"""
query = f"MATCH (node: `{BASE_LABEL}`{{id: $node_id}}) DETACH DELETE node"
params = {"node_id": node_id}
return await self.query(query, params)
async def delete_nodes(self, node_ids: list[str]) -> None:
"""
Delete multiple nodes from the database using their IDs.
Parameters:
-----------
- node_ids (list[str]): A list of IDs of the nodes to delete.
Returns:
--------
- None: None
"""
query = f"""
UNWIND $node_ids AS id
MATCH (node: `{BASE_LABEL}`{{id: id}})
DETACH DELETE node"""
params = {"node_ids": node_ids}
return await self.query(query, params)
async def has_edge(self, from_node: UUID, to_node: UUID, edge_label: str) -> bool:
"""
Check if an edge exists between two nodes with the specified IDs and edge label.
Parameters:
-----------
- from_node (UUID): The ID of the node from which the edge originates.
- to_node (UUID): The ID of the node to which the edge points.
- edge_label (str): The label of the edge to check for existence.
Returns:
--------
- bool: True if the edge exists, otherwise False.
"""
query = f"""
MATCH (from_node: `{BASE_LABEL}`)-[:`{edge_label}`]->(to_node: `{BASE_LABEL}`)
WHERE from_node.id = $from_node_id AND to_node.id = $to_node_id
RETURN COUNT(relationship) > 0 AS edge_exists
"""
params = {
"from_node_id": str(from_node),
"to_node_id": str(to_node),
}
edge_exists = await self.query(query, params)
return edge_exists
async def has_edges(self, edges):
"""
Check if multiple edges exist based on provided edge criteria.
Parameters:
-----------
- edges: A list of edge specifications to check for existence.
Returns:
--------
A list of boolean values indicating the existence of each edge.
"""
query = """
UNWIND $edges AS edge
MATCH (a)-[r]->(b)
WHERE id(a) = edge.from_node AND id(b) = edge.to_node AND type(r) = edge.relationship_name
RETURN edge.from_node AS from_node, edge.to_node AS to_node, edge.relationship_name AS relationship_name, count(r) > 0 AS edge_exists
"""
try:
params = {
"edges": [
{
"from_node": str(edge[0]),
"to_node": str(edge[1]),
"relationship_name": edge[2],
}
for edge in edges
],
}
results = await self.query(query, params)
return [result["edge_exists"] for result in results]
except Neo4jError as error:
logger.error("Neo4j query error: %s", error, exc_info=True)
raise error
async def add_edge(
self,
from_node: UUID,
to_node: UUID,
relationship_name: str,
edge_properties: Optional[Dict[str, Any]] = {},
):
"""
Create a new edge between two nodes with specified properties.
Parameters:
-----------
- from_node (UUID): The ID of the source node of the edge.
- to_node (UUID): The ID of the target node of the edge.
- relationship_name (str): The type/label of the edge to create.
- edge_properties (Optional[Dict[str, Any]]): A dictionary of properties to assign
to the edge. (default {})
Returns:
--------
The result of the query execution, typically indicating the created edge.
"""
serialized_properties = self.serialize_properties(edge_properties)
query = dedent(
f"""\
MATCH (from_node :`{BASE_LABEL}`{{id: $from_node}}),
(to_node :`{BASE_LABEL}`{{id: $to_node}})
MERGE (from_node)-[r:`{relationship_name}`]->(to_node)
ON CREATE SET r += $properties, r.updated_at = timestamp()
ON MATCH SET r += $properties, r.updated_at = timestamp()
RETURN r
"""
)
params = {
"from_node": str(from_node),
"to_node": str(to_node),
"relationship_name": relationship_name,
"properties": serialized_properties,
}
return await self.query(query, params)
def _flatten_edge_properties(self, properties: Dict[str, Any]) -> Dict[str, Any]:
"""
Flatten edge properties to handle nested dictionaries like weights.
Neo4j doesn't support nested dictionaries as property values, so we need to
flatten the 'weights' dictionary into individual properties with prefixes.
Args:
properties: Dictionary of edge properties that may contain nested dicts
Returns:
Flattened properties dictionary suitable for Neo4j storage
"""
flattened = {}
for key, value in properties.items():
if key == "weights" and isinstance(value, dict):
# Flatten weights dictionary into individual properties
for weight_name, weight_value in value.items():
flattened[f"weight_{weight_name}"] = weight_value
elif isinstance(value, dict):
# For other nested dictionaries, serialize as JSON string
flattened[f"{key}_json"] = json.dumps(value, cls=JSONEncoder)
elif isinstance(value, list):
# For lists, serialize as JSON string
flattened[f"{key}_json"] = json.dumps(value, cls=JSONEncoder)
else:
# Keep primitive types as-is
flattened[key] = value
return flattened
@override_distributed(queued_add_edges)
async def add_edges(self, edges: list[tuple[str, str, str, dict[str, Any]]]) -> None:
"""
Add multiple edges between nodes in a single query.
Parameters:
-----------
- edges (list[tuple[str, str, str, dict[str, Any]]]): A list of tuples where each
tuple contains edge details to add.
Returns:
--------
- None: None
"""
query = f"""
UNWIND $edges AS edge
MATCH (from_node: `{BASE_LABEL}`{{id: edge.from_node}})
MATCH (to_node: `{BASE_LABEL}`{{id: edge.to_node}})
CALL apoc.merge.relationship(
from_node,
edge.relationship_name,
{{
source_node_id: edge.from_node,
target_node_id: edge.to_node
}},
edge.properties,
to_node
) YIELD rel
RETURN rel"""
edges = [
{
"from_node": str(edge[0]),
"to_node": str(edge[1]),
"relationship_name": edge[2],
"properties": self._flatten_edge_properties(
{
**(edge[3] if edge[3] else {}),
"source_node_id": str(edge[0]),
"target_node_id": str(edge[1]),
}
),
}
for edge in edges
]
try:
results = await self.query(query, dict(edges=edges))
return results
except Neo4jError as error:
logger.error("Neo4j query error: %s", error, exc_info=True)
raise error
async def get_edges(self, node_id: str):
"""
Retrieve all edges connected to a specified node.
Parameters:
-----------
- node_id (str): The ID of the node for which edges are retrieved.
Returns:
--------
A list of edges connecting to the specified node, represented as tuples of details.
"""
query = f"""
MATCH (n: `{BASE_LABEL}`{{id: $node_id}})-[r]-(m)
RETURN n, r, m
"""
results = await self.query(query, dict(node_id=node_id))
return [
(result["n"]["id"], result["m"]["id"], {"relationship_name": result["r"][1]})
for result in results
]
async def get_disconnected_nodes(self) -> list[str]:
"""
Find and return nodes that are not connected to any other nodes in the graph.
Returns:
--------
- list[str]: A list of IDs of disconnected nodes.
"""
# return await self.query(
# "MATCH (node) WHERE NOT (node)<-[:*]-() RETURN node.id as id",
# )
query = """
// Step 1: Collect all nodes
MATCH (n)
WITH COLLECT(n) AS nodes
// Step 2: Find all connected components
WITH nodes
CALL {
WITH nodes
UNWIND nodes AS startNode
MATCH path = (startNode)-[*]-(connectedNode)
WITH startNode, COLLECT(DISTINCT connectedNode) AS component
RETURN component
}
// Step 3: Aggregate components
WITH COLLECT(component) AS components
// Step 4: Identify the largest connected component
UNWIND components AS component
WITH component
ORDER BY SIZE(component) DESC
LIMIT 1
WITH component AS largestComponent
// Step 5: Find nodes not in the largest connected component
MATCH (n)
WHERE NOT n IN largestComponent
RETURN COLLECT(ID(n)) AS ids
"""
results = await self.query(query)
return results[0]["ids"] if len(results) > 0 else []
async def get_predecessors(self, node_id: str, edge_label: str = None) -> list[str]:
"""
Retrieve the predecessor nodes of a specified node based on an optional edge label.
Parameters:
-----------
- node_id (str): The ID of the node whose predecessors are to be retrieved.
- edge_label (str): Optional edge label to filter predecessors. (default None)
Returns:
--------
- list[str]: A list of predecessor node IDs.
"""
if edge_label is not None:
query = f"""
MATCH (node: `{BASE_LABEL}`)<-[r:`{edge_label}`]-(predecessor)
WHERE node.id = $node_id
RETURN predecessor
"""
results = await self.query(
query,
dict(
node_id=node_id,
),
)
return [result["predecessor"] for result in results]
else:
query = f"""
MATCH (node: `{BASE_LABEL}`)<-[r]-(predecessor)
WHERE node.id = $node_id
RETURN predecessor
"""
results = await self.query(
query,
dict(
node_id=node_id,
),
)
return [result["predecessor"] for result in results]
async def get_successors(self, node_id: str, edge_label: str = None) -> list[str]:
"""
Retrieve the successor nodes of a specified node based on an optional edge label.
Parameters:
-----------
- node_id (str): The ID of the node whose successors are to be retrieved.
- edge_label (str): Optional edge label to filter successors. (default None)
Returns:
--------
- list[str]: A list of successor node IDs.
"""
if edge_label is not None:
query = f"""
MATCH (node: `{BASE_LABEL}`)-[r:`{edge_label}`]->(successor)
WHERE node.id = $node_id
RETURN successor
"""
results = await self.query(
query,
dict(
node_id=node_id,
edge_label=edge_label,
),
)
return [result["successor"] for result in results]
else:
query = f"""
MATCH (node: `{BASE_LABEL}`)-[r]->(successor)
WHERE node.id = $node_id
RETURN successor
"""
results = await self.query(
query,
dict(
node_id=node_id,
),
)
return [result["successor"] for result in results]
async def get_neighbors(self, node_id: str) -> List[Dict[str, Any]]:
"""
Get all neighbors of a specified node, including all directly connected nodes.
This method retrieves all neighboring nodes connected to a specified node and returns
their properties as a list of dictionaries. It may return an empty list if no neighbors exist or an
error occurs.
Parameters:
-----------
- node_id (str): The ID of the node for which neighbors are retrieved.
Returns:
--------
- List[Dict[str, Any]]: A list of neighboring nodes represented as dictionaries.
"""
query = f"""
MATCH (n: `{BASE_LABEL}` {{id: $node_id}})--(m: `{BASE_LABEL}`)
RETURN DISTINCT properties(m) AS properties
"""
try:
result = await self.query(query, {"node_id": node_id})
return [row["properties"] for row in result] if result else []
except Exception as exc:
logger.error(f"Failed to get neighbors for node {node_id}: {exc}")
raise exc
async def get_node(self, node_id: str) -> Optional[Dict[str, Any]]:
"""
Retrieve a single node based on its ID.
Parameters:
-----------
- node_id (str): The ID of the node to retrieve.
Returns:
--------
- Optional[Dict[str, Any]]: The requested node as a dictionary, or None if it does
not exist.
"""
query = f"""
MATCH (node: `{BASE_LABEL}`{{id: $node_id}})
RETURN node
"""
results = await self.query(query, {"node_id": node_id})
return results[0]["node"] if results else None
async def get_nodes(self, node_ids: List[str]) -> List[Dict[str, Any]]:
"""
Retrieve multiple nodes based on their IDs.
Parameters:
-----------
- node_ids (List[str]): A list of node IDs to retrieve.
Returns:
--------
- List[Dict[str, Any]]: A list of nodes represented as dictionaries.
"""
query = f"""
UNWIND $node_ids AS id
MATCH (node:`{BASE_LABEL}` {{id: id}})
RETURN node
"""
results = await self.query(query, {"node_ids": node_ids})
return [result["node"] for result in results]
async def get_connections(self, node_id: UUID) -> list:
"""
Retrieve all connections (predecessors and successors) for a specified node.
Parameters:
-----------
- node_id (UUID): The ID of the node for which connections are retrieved.
Returns:
--------
- list: A list of connections represented as tuples of details.
"""
predecessors_query = f"""
MATCH (node:`{BASE_LABEL}`)<-[relation]-(neighbour)
WHERE node.id = $node_id
RETURN neighbour, relation, node
"""
successors_query = f"""
MATCH (node:`{BASE_LABEL}`)-[relation]->(neighbour)
WHERE node.id = $node_id
RETURN node, relation, neighbour
"""
predecessors, successors = await asyncio.gather(
self.query(predecessors_query, dict(node_id=str(node_id))),
self.query(successors_query, dict(node_id=str(node_id))),
)
connections = []
for neighbour in predecessors:
neighbour = neighbour["relation"]
connections.append((neighbour[0], {"relationship_name": neighbour[1]}, neighbour[2]))
for neighbour in successors:
neighbour = neighbour["relation"]
connections.append((neighbour[0], {"relationship_name": neighbour[1]}, neighbour[2]))
return connections
async def remove_connection_to_predecessors_of(
self, node_ids: list[str], edge_label: str
) -> None:
"""
Remove connections (edges) to all predecessors of specified nodes based on edge label.
Parameters:
-----------
- node_ids (list[str]): A list of IDs of nodes from which connections are to be
removed.
- edge_label (str): The label of the edges to remove.
Returns:
--------
- None: None
"""
# Not understanding
query = f"""
UNWIND $node_ids AS id
MATCH (node:`{id}`)-[r:{edge_label}]->(predecessor)
DELETE r;
"""
params = {"node_ids": node_ids}
return await self.query(query, params)
async def remove_connection_to_successors_of(
self, node_ids: list[str], edge_label: str
) -> None:
"""
Remove connections (edges) to all successors of specified nodes based on edge label.
Parameters:
-----------
- node_ids (list[str]): A list of IDs of nodes from which connections are to be
removed.
- edge_label (str): The label of the edges to remove.
Returns:
--------
- None: None
"""
# Not understanding
query = f"""
UNWIND $node_ids AS id
MATCH (node:`{id}`)<-[r:{edge_label}]-(successor)
DELETE r;
"""
params = {"node_ids": node_ids}
return await self.query(query, params)
async def delete_graph(self):
"""
Delete all nodes and edges from the graph database.
Returns:
--------
The result of the query execution, typically indicating success or failure.
"""
# query = """MATCH (node)
# DETACH DELETE node;"""
# return await self.query(query)
node_labels = await self.get_node_labels()
for label in node_labels:
query = f"""
MATCH (node:`{label}`)
DETACH DELETE node;
"""
await self.query(query)
def serialize_properties(self, properties=dict()):
"""
Convert properties of a node or edge into a serializable format suitable for storage.
Parameters:
-----------
- properties: A dictionary of properties to serialize, defaults to an empty
dictionary. (default dict())
Returns:
--------
A dictionary with serialized property values.
"""
serialized_properties = {}
for property_key, property_value in properties.items():
if isinstance(property_value, UUID):
serialized_properties[property_key] = str(property_value)
continue
if isinstance(property_value, dict):
serialized_properties[property_key] = json.dumps(property_value, cls=JSONEncoder)
continue
serialized_properties[property_key] = property_value
return serialized_properties
async def get_model_independent_graph_data(self):
"""
Retrieve the basic graph data without considering the model specifics, returning nodes
and edges.
Returns:
--------
A tuple of nodes and edges data.
"""
query_nodes = "MATCH (n) RETURN collect(n) AS nodes"
nodes = await self.query(query_nodes)
query_edges = "MATCH (n)-[r]->(m) RETURN collect([n, r, m]) AS elements"
edges = await self.query(query_edges)
return (nodes, edges)
async def get_graph_data(self):
"""
Retrieve comprehensive data about nodes and relationships within the graph.
Returns:
--------
A tuple containing two lists: nodes and edges with their properties.
"""
import time
start_time = time.time()
try:
# Retrieve nodes
query = "MATCH (n) RETURN ID(n) AS id, labels(n) AS labels, properties(n) AS properties"
result = await self.query(query)
nodes = []
for record in result:
nodes.append(
(
record["properties"]["id"],
record["properties"],
)
)
# Retrieve edges
query = """
MATCH (n)-[r]->(m)
RETURN ID(n) AS source, ID(m) AS target, TYPE(r) AS type, properties(r) AS properties
"""
result = await self.query(query)
edges = []
for record in result:
edges.append(
(
record["properties"]["source_node_id"],
record["properties"]["target_node_id"],
record["type"],
record["properties"],
)
)
retrieval_time = time.time() - start_time
logger.info(
f"Retrieved {len(nodes)} nodes and {len(edges)} edges in {retrieval_time:.2f} seconds"
)
return (nodes, edges)
except Exception as e:
logger.error(f"Error during graph data retrieval: {str(e)}")
raise
async def get_neighborhood(
self,
node_ids: List[str],
depth: int = 1,
edge_types: Optional[List[str]] = None,
) -> Tuple[List[Tuple[str, Dict[str, Any]]], List[Tuple[str, str, str, Dict[str, Any]]]]:
"""