-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathschema_neo4j_queries.py
More file actions
2203 lines (1766 loc) · 72.4 KB
/
schema_neo4j_queries.py
File metadata and controls
2203 lines (1766 loc) · 72.4 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
import neo4j
from neo4j.exceptions import TransactionError
from neo4j import Session as Neo4jSession
from schema.schema_constants import SchemaConstants, Neo4jRelationshipEnum
import logging
logger = logging.getLogger(__name__)
# The filed name of the single result record
record_field_name = 'result'
####################################################################################################
## Functions can be called by app.py, schema_manager.py, and schema_triggers.py
####################################################################################################
"""
Create a new entity node in neo4j
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
entity_type : str
One of the normalized entity types: Dataset, Collection, Sample, Donor
entity_data_dict : dict
The target Entity node to be created
superclass : str
The normalized entity superclass type if defined, None by default
Returns
-------
dict
A dictionary of newly created entity details returned from the Cypher query
"""
def create_entity(neo4j_driver, entity_type, entity_data_dict, superclass = None):
# Always define the Entity label in addition to the target `entity_type` label
labels = f':Entity:{entity_type}'
if superclass is not None:
labels = f':Entity:{entity_type}:{superclass}'
node_properties_map = build_properties_map(entity_data_dict)
query = (f"CREATE (e{labels}) "
f"SET e = {node_properties_map} "
f"RETURN e AS {record_field_name}")
logger.info("======create_entity() query======")
logger.debug(query)
try:
with neo4j_driver.session() as session:
entity_dict = {}
tx = session.begin_transaction()
result = tx.run(query)
record = result.single()
entity_node = record[record_field_name]
entity_dict = node_to_dict(entity_node)
tx.commit()
return entity_dict
except TransactionError as te:
msg = f"TransactionError from calling create_entity(): {te.value}"
# Log the full stack trace, prepend a line with our message
logger.exception(msg)
if tx.closed() == False:
logger.error("Failed to commit create_entity() transaction, rollback")
tx.rollback()
raise TransactionError(msg)
"""
Get target entity dict
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
uuid : str
The uuid of target entity
Returns
-------
dict
A dictionary of entity details returned from the Cypher query
"""
def get_entity(neo4j_driver, uuid):
result = {}
query = (f"MATCH (e:Entity) "
f"WHERE e.uuid = '{uuid}' "
f"RETURN e AS {record_field_name}")
logger.info("======get_entity() query======")
logger.debug(query)
with neo4j_driver.session() as session:
record = session.read_transaction(execute_readonly_tx, query)
if record and record[record_field_name]:
# Convert the neo4j node into Python dict
result = node_to_dict(record[record_field_name])
return result
"""
Given a list of UUIDs, return a dict mapping uuid -> entity_node
Only UUIDs present in Neo4j will be returned.
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
uuid_list : list of str
The uuids of target entities to retrieve from Neo4j
Returns
-------
dict
A dictionary of entity details returned from the Cypher query, keyed by
the uuid provided in uuid_list.
"""
def identify_existing_dataset_entities(neo4j_driver, dataset_uuid_list:list):
if not dataset_uuid_list:
return {}
query = """
MATCH (e:Entity)
WHERE e.uuid IN $param_uuids
AND e.entity_type='Dataset'
RETURN e.uuid AS uuid
"""
with neo4j_driver.session() as session:
results = session.run(query, param_uuids=dataset_uuid_list)
return [record["uuid"] for record in results]
"""
Get the uuids for each entity in a list that doesn't belong to a certain entity type. Uuids are ordered by type
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
direct_ancestor_uuids : list
List of the uuids to be filtered
entity_type : string
The entity to be excluded
Returns
-------
dict
A dictionary of entity uuids that don't pass the filter, grouped by entity_type
"""
def filter_ancestors_by_type(neo4j_driver, direct_ancestor_uuids, entity_type):
query = (f"MATCH (e:Entity) "
f"WHERE e.uuid in {direct_ancestor_uuids} AND toLower(e.entity_type) <> '{entity_type.lower()}' "
f"RETURN e.entity_type AS entity_type, collect(e.uuid) AS uuids")
logger.info("======filter_ancestors_by_type======")
logger.debug(query)
with neo4j_driver.session() as session:
records = session.run(query).data()
return records if records else None
"""
Get all children by uuid
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
uuid : str
The uuid of target entity
property_key : str
A target property key for result filtering
Returns
-------
dict
A list of unique child dictionaries returned from the Cypher query
"""
def get_children(neo4j_driver, uuid, property_key = None):
results = []
fields_to_omit = SchemaConstants.OMITTED_FIELDS
if property_key:
query = (f"MATCH (e:Entity)-[:ACTIVITY_INPUT]->(:Activity)-[:ACTIVITY_OUTPUT]->(child:Entity) "
# The target entity can't be a Lab
f"WHERE e.uuid='{uuid}' AND e.entity_type <> 'Lab' "
# COLLECT() returns a list
# apoc.coll.toSet() reruns a set containing unique nodes
f"RETURN apoc.coll.toSet(COLLECT(child.{property_key})) AS {record_field_name}")
else:
query = (f"MATCH (e:Entity)-[:ACTIVITY_INPUT]->(:Activity)-[:ACTIVITY_OUTPUT]->(child:Entity) "
# The target entity can't be a Lab
f"WHERE e.uuid='{uuid}' AND e.entity_type <> 'Lab' "
f"WITH COLLECT(DISTINCT child) AS uniqueChildren "
f"RETURN [a IN uniqueChildren | apoc.create.vNode(labels(a), apoc.map.removeKeys(properties(a), {fields_to_omit}))] AS {record_field_name}")
logger.info("======get_children() query======")
logger.debug(query)
with neo4j_driver.session() as session:
record = session.read_transaction(execute_readonly_tx, query)
if record and record[record_field_name]:
if property_key:
# Just return the list of property values from each entity node
results = record[record_field_name]
else:
# Convert the list of nodes to a list of dicts
results = nodes_to_dicts(record[record_field_name])
return results
"""
Get all parents by uuid
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
uuid : str
The uuid of target entity
property_key : str
A target property key for result filtering
Returns
-------
dict
A list of unique parent dictionaries returned from the Cypher query
"""
def get_parents(neo4j_driver, uuid, property_key = None):
results = []
fields_to_omit = SchemaConstants.OMITTED_FIELDS
if property_key:
query = (f"MATCH (e:Entity)<-[:ACTIVITY_OUTPUT]-(:Activity)<-[:ACTIVITY_INPUT]-(parent:Entity) "
# Filter out the Lab entities
f"WHERE e.uuid='{uuid}' AND parent.entity_type <> 'Lab' "
# COLLECT() returns a list
# apoc.coll.toSet() reruns a set containing unique nodes
f"RETURN apoc.coll.toSet(COLLECT(parent.{property_key})) AS {record_field_name}")
else:
query = (f"MATCH (e:Entity)<-[:ACTIVITY_OUTPUT]-(:Activity)<-[:ACTIVITY_INPUT]-(parent:Entity) "
# Filter out the Lab entities
f"WHERE e.uuid='{uuid}' AND parent.entity_type <> 'Lab' "
f"WITH COLLECT(DISTINCT parent) AS uniqueParents "
f"RETURN [a IN uniqueParents | apoc.create.vNode(labels(a), apoc.map.removeKeys(properties(a), {fields_to_omit}))] AS {record_field_name}")
logger.info("======get_parents() query======")
logger.debug(query)
with neo4j_driver.session() as session:
record = session.read_transaction(execute_readonly_tx, query)
if record and record[record_field_name]:
if property_key:
# Just return the list of property values from each entity node
results = record[record_field_name]
else:
# Convert the list of nodes to a list of dicts
results = nodes_to_dicts(record[record_field_name])
return results
"""
Get all siblings by uuid
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
uuid : str
The uuid of target entity
property_key : str
A target property key for result filtering
Returns
-------
dict
A list of unique sibling dictionaries returned from the Cypher query
"""
def get_siblings(neo4j_driver, uuid, property_key=None):
results = []
if property_key:
query = (f"MATCH (e:Entity)<-[:ACTIVITY_OUTPUT]-(:Activity)<-[:ACTIVITY_INPUT]-(parent:Entity) "
# filter out the Lab entities
f"WHERE e.uuid='{uuid}' AND parent.entity_type <> 'Lab' "
f"MATCH (sibling:Entity)<-[:ACTIVITY_OUTPUT]-(:Activity)<-[:ACTIVITY_INPUT]-(parent) "
f"WHERE sibling <> e "
# COLLECT() returns a list
# apoc.coll.toSet() returns a set containing unique nodes
f"RETURN apoc.coll.toSet(COLLECT(sibling.{property_key})) AS {record_field_name}")
else:
query = (f"MATCH (e:Entity)<-[:ACTIVITY_OUTPUT]-(:Activity)<-[:ACTIVITY_INPUT]-(parent:Entity) "
# filter out the Lab entities
f"WHERE e.uuid='{uuid}' AND parent.entity_type <> 'Lab' "
f"MATCH (sibling:Entity)<-[:ACTIVITY_OUTPUT]-(:Activity)<-[:ACTIVITY_INPUT]-(parent) "
f"WHERE sibling <> e "
# COLLECT() returns a list
# apoc.coll.toSet() returns a set containing unique nodes
f"RETURN apoc.coll.toSet(COLLECT(sibling)) AS {record_field_name}")
logger.info("======get_siblings() query======")
logger.debug(query)
with neo4j_driver.session() as session:
record = session.read_transaction(execute_readonly_tx, query)
if record and record[record_field_name]:
if property_key:
# Just return the list of property values from each entity node
results = record[record_field_name]
else:
# Convert the list of nodes to a list of dicts
results = nodes_to_dicts(record[record_field_name])
return results
"""
Get all tuplets by uuid
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
uuid : str
The uuid of target entity
property_key : str
A target property key for result filtering
Returns
-------
dict
A list of unique tuplet dictionaries returned from the Cypher query
"""
def get_tuplets(neo4j_driver, uuid, property_key=None):
results = []
if property_key:
query = (f"MATCH (e:Entity)<-[:ACTIVITY_OUTPUT]-(a:Activity)<-[:ACTIVITY_INPUT]-(parent:Entity) "
# filter out the Lab entities
f"WHERE e.uuid='{uuid}' AND parent.entity_type <> 'Lab' "
f"MATCH (tuplet:Entity)<-[:ACTIVITY_OUTPUT]-(a) "
f"WHERE tuplet <> e "
# COLLECT() returns a list
# apoc.coll.toSet() returns a set containing unique nodes
f"RETURN apoc.coll.toSet(COLLECT(tuplet.{property_key})) AS {record_field_name}")
else:
query = (f"MATCH (e:Entity)<-[:ACTIVITY_OUTPUT]-(a:Activity)<-[:ACTIVITY_INPUT]-(parent:Entity) "
# filter out the Lab entities
f"WHERE e.uuid='{uuid}' AND parent.entity_type <> 'Lab' "
f"MATCH (tuplet:Entity)<-[:ACTIVITY_OUTPUT]-(a:Activity) "
f"WHERE tuplet <> e "
# COLLECT() returns a list
# apoc.coll.toSet() returns a set containing unique nodes
f"RETURN apoc.coll.toSet(COLLECT(tuplet)) AS {record_field_name}")
logger.info("======get_tuplets() query======")
logger.debug(query)
with neo4j_driver.session() as session:
record = session.read_transaction(execute_readonly_tx, query)
if record and record[record_field_name]:
if property_key:
# Just return the list of property values from each entity node
results = record[record_field_name]
else:
# Convert the list of nodes to a list of dicts
results = nodes_to_dicts(record[record_field_name])
return results
"""
Get all ancestors by uuid
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
uuid : str
The uuid of target entity
property_key : str
A target property key for result filtering
Returns
-------
list
A list of unique ancestor dictionaries returned from the Cypher query
"""
def get_ancestors(neo4j_driver, uuid, property_key = None):
results = []
fields_to_omit = SchemaConstants.OMITTED_FIELDS
if property_key:
query = (f"MATCH (e:Entity)<-[:ACTIVITY_INPUT|ACTIVITY_OUTPUT*]-(ancestor:Entity) "
# Filter out the Lab entities
f"WHERE e.uuid='{uuid}' AND ancestor.entity_type <> 'Lab' "
# COLLECT() returns a list
# apoc.coll.toSet() reruns a set containing unique nodes
f"RETURN apoc.coll.toSet(COLLECT(ancestor.{property_key})) AS {record_field_name}")
else:
query = (f"MATCH (e:Entity)<-[:ACTIVITY_INPUT|ACTIVITY_OUTPUT*]-(ancestor:Entity) "
# Filter out the Lab entities
f"WHERE e.uuid='{uuid}' AND ancestor.entity_type <> 'Lab' "
f"WITH COLLECT(DISTINCT ancestor) AS uniqueAncestors "
f"RETURN [a IN uniqueAncestors | apoc.create.vNode(labels(a), apoc.map.removeKeys(properties(a), {fields_to_omit}))] AS {record_field_name}")
logger.info("======get_ancestors() query======")
logger.debug(query)
with neo4j_driver.session() as session:
record = session.read_transaction(execute_readonly_tx, query)
if record and record[record_field_name]:
if property_key:
# Just return the list of property values from each entity node
results = record[record_field_name]
else:
# Convert the list of nodes to a list of dicts
results = nodes_to_dicts(record[record_field_name])
return results
"""
Get all descendants by uuid
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
uuid : str
The uuid of target entity
property_key : str
A target property key for result filtering
Returns
-------
dict
A list of unique desendant dictionaries returned from the Cypher query
"""
def get_descendants(neo4j_driver, uuid, property_key = None):
results = []
fields_to_omit = SchemaConstants.OMITTED_FIELDS
if property_key:
query = (f"MATCH (e:Entity)-[:ACTIVITY_INPUT|ACTIVITY_OUTPUT*]->(descendant:Entity) "
# The target entity can't be a Lab
f"WHERE e.uuid='{uuid}' AND e.entity_type <> 'Lab' "
# COLLECT() returns a list
# apoc.coll.toSet() reruns a set containing unique nodes
f"RETURN apoc.coll.toSet(COLLECT(descendant.{property_key})) AS {record_field_name}")
else:
query = (f"MATCH (e:Entity)-[:ACTIVITY_INPUT|ACTIVITY_OUTPUT*]->(descendant:Entity) "
# The target entity can't be a Lab
f"WHERE e.uuid='{uuid}' AND e.entity_type <> 'Lab' "
f"WITH COLLECT(DISTINCT descendant) AS uniqueDescendants "
f"RETURN [a IN uniqueDescendants | apoc.create.vNode(labels(a), apoc.map.removeKeys(properties(a), {fields_to_omit}))] AS {record_field_name}")
logger.info("======get_descendants() query======")
logger.debug(query)
with neo4j_driver.session() as session:
record = session.read_transaction(execute_readonly_tx, query)
if record and record[record_field_name]:
if property_key:
# Just return the list of property values from each entity node
results = record[record_field_name]
else:
# Convert the list of nodes to a list of dicts
results = nodes_to_dicts(record[record_field_name])
return results
"""
Get all collections by uuid
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
uuid : str
The uuid of target entity
property_key : str
A target property key for result filtering
Returns
-------
list
A list of unique collection dictionaries returned from the Cypher query
"""
def get_collections(neo4j_driver, uuid, property_key = None):
results = []
if property_key:
query = (f"MATCH (c:Collection)<-[:IN_COLLECTION]-(ds:Dataset) "
f"WHERE ds.uuid='{uuid}' "
# COLLECT() returns a list
# apoc.coll.toSet() reruns a set containing unique nodes
f"RETURN apoc.coll.toSet(COLLECT(c.{property_key})) AS {record_field_name}")
else:
query = (f"MATCH (c:Collection)<-[:IN_COLLECTION]-(ds:Dataset) "
f"WHERE ds.uuid='{uuid}' "
# COLLECT() returns a list
# apoc.coll.toSet() reruns a set containing unique nodes
f"RETURN apoc.coll.toSet(COLLECT(c)) AS {record_field_name}")
logger.info("======get_collections() query======")
logger.debug(query)
with neo4j_driver.session() as session:
record = session.read_transaction(execute_readonly_tx, query)
if record and record[record_field_name]:
if property_key:
# Just return the list of property values from each entity node
results = record[record_field_name]
else:
# Convert the list of nodes to a list of dicts
results = nodes_to_dicts(record[record_field_name])
return results
"""
Get all uploads by uuid
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
uuid : str
The uuid of target entity
property_key : str
A target property key for result filtering
Returns
-------
list
A list of unique upload dictionaries returned from the Cypher query
"""
def get_uploads(neo4j_driver, uuid, property_key = None):
results = []
if property_key:
query = (f"MATCH (u:Upload)<-[:IN_UPLOAD]-(ds:Dataset) "
f"WHERE ds.uuid='{uuid}' "
# COLLECT() returns a list
# apoc.coll.toSet() reruns a set containing unique nodes
f"RETURN apoc.coll.toSet(COLLECT(u.{property_key})) AS {record_field_name}")
else:
query = (f"MATCH (u:Upload)<-[:IN_UPLOAD]-(ds:Dataset) "
f"WHERE ds.uuid='{uuid}' "
# COLLECT() returns a list
# apoc.coll.toSet() reruns a set containing unique nodes
f"RETURN apoc.coll.toSet(COLLECT(u)) AS {record_field_name}")
logger.info("======get_uploads() query======")
logger.debug(query)
with neo4j_driver.session() as session:
record = session.read_transaction(execute_readonly_tx, query)
if record and record[record_field_name]:
if property_key:
# Just return the list of property values from each entity node
results = record[record_field_name]
else:
# Convert the list of nodes to a list of dicts
results = nodes_to_dicts(record[record_field_name])
return results
"""
Get the direct ancestors uuids of a given dataset by uuid
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
uuid : str
The uuid of target entity
property_key : str
A target property key for result filtering
properties_to_exclude : list
A list of node properties to exclude from result
Returns
-------
list
A unique list of uuids of source entities
"""
def get_dataset_direct_ancestors(neo4j_driver, uuid, property_key = None, properties_to_exclude = []):
results = []
if property_key:
query = (f"MATCH (s:Entity)-[:ACTIVITY_INPUT]->(a:Activity)-[:ACTIVITY_OUTPUT]->(t:Dataset) "
f"WHERE t.uuid = '{uuid}' "
f"RETURN apoc.coll.toSet(COLLECT(s.{property_key})) AS {record_field_name}")
else:
if properties_to_exclude:
query = (f"MATCH (s:Entity)-[:ACTIVITY_INPUT]->(a:Activity)-[:ACTIVITY_OUTPUT]->(t:Dataset) "
f"WHERE t.uuid = '{uuid}' "
f"WITH apoc.coll.toSet(COLLECT(s)) AS uniqueDirectAncestors "
f"RETURN [a IN uniqueDirectAncestors | apoc.create.vNode(labels(a), apoc.map.removeKeys(properties(a), {properties_to_exclude}))] AS {record_field_name}")
else:
query = (f"MATCH (s:Entity)-[:ACTIVITY_INPUT]->(a:Activity)-[:ACTIVITY_OUTPUT]->(t:Dataset) "
f"WHERE t.uuid = '{uuid}' "
f"RETURN apoc.coll.toSet(COLLECT(s)) AS {record_field_name}")
logger.info("======get_dataset_direct_ancestors() query======")
logger.debug(query)
# Sessions will often be created and destroyed using a with block context
with neo4j_driver.session() as session:
record = session.read_transaction(execute_readonly_tx, query)
if record and record[record_field_name]:
if property_key:
# Just return the list of property values from each entity node
results = record[record_field_name]
else:
# Convert the list of nodes to a list of dicts
results = nodes_to_dicts(record[record_field_name])
return results
"""
For every Sample organ associated with the given dataset_uuid, retrieve the
organ information and organ Donor information for use in composing a title for the Dataset.
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
dataset_uuid : str
The UUID of a Dataset
Returns
-------
list : List containing the source metadata (string representation of a Python dict) of each Donor of an
organ Sample associated with the Dataset. Could also be an empty list [] if no match.
"""
def get_dataset_donor_organs_info(neo4j_driver, dataset_uuid):
with neo4j_driver.session() as session:
ds_donors_organs_query = ( f"MATCH (e:Dataset)<-[:ACTIVITY_INPUT|ACTIVITY_OUTPUT*]-(org:Sample)<-[:ACTIVITY_INPUT|ACTIVITY_OUTPUT*]-(d:Donor)"
f" WHERE e.uuid='{dataset_uuid}'"
f" AND org.sample_category IS NOT NULL"
f" AND org.sample_category='organ'"
f" AND org.organ IS NOT NULL"
f" RETURN apoc.coll.toSet(COLLECT({{donor_uuid: d.uuid"
f" , donor_metadata: d.metadata"
f" , organ_type: org.organ}})) AS donorOrganSet")
logger.info("======get_dataset_donor_organs_info() ds_donors_organs_query======")
logger.debug(ds_donors_organs_query)
with neo4j_driver.session() as session:
record = session.read_transaction(execute_readonly_tx
, ds_donors_organs_query)
return record['donorOrganSet'] if record and record['donorOrganSet'] else []
"""
Get entity type for a given uuid
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
entity_uuid : str
The uuid of target entity
Returns
-------
str
The entity_type string
"""
def get_entity_type(neo4j_driver, entity_uuid: str) -> str:
query: str = f"Match (ent {{uuid: '{entity_uuid}'}}) return ent.entity_type"
logger.info("======get_entity_type() query======")
logger.debug(query)
with neo4j_driver.session() as session:
record = session.read_transaction(execute_readonly_tx, query)
if record and len(record) == 1:
return record[0]
return None
"""
Get Activity.creation_action for a given collection
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
entity_uuid : str
The uuid of given entity
Returns
-------
str
The creation action string
"""
def get_entity_creation_action_activity(neo4j_driver, entity_uuid: str) -> str:
query: str = f"MATCH (ds:Dataset {{uuid:'{entity_uuid}'}})<-[:ACTIVITY_OUTPUT]-(a:Activity) RETURN a.creation_action"
logger.info("======get_entity_creation_action() query======")
logger.debug(query)
with neo4j_driver.session() as session:
record = session.read_transaction(execute_readonly_tx, query)
if record and len(record) == 1:
return record[0]
return None
"""
Create or recreate one or more linkages (via Activity nodes)
between the target entity node and the direct ancestor nodes in neo4j
Note: the size of direct_ancestor_uuids equals to that of activity_data_dict_list
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
entity_uuid : str
The uuid of target child entity
direct_ancestor_uuids : list
A list of uuids of direct ancestors
activity_data_dict : dict
A dict of activity properties to be created
"""
def link_entity_to_direct_ancestors(neo4j_driver, entity_uuid, direct_ancestor_uuids, activity_data_dict):
try:
with neo4j_driver.session() as session:
tx = session.begin_transaction()
# First delete all the old linkages and Activity node between this entity and its direct ancestors
_delete_activity_node_and_linkages_tx(tx, entity_uuid)
# Get the activity uuid
activity_uuid = activity_data_dict['uuid']
# Create the Acvitity node
create_activity_tx(tx, activity_data_dict)
# Create relationship from this Activity node to the target entity node
create_relationship_tx(tx, activity_uuid, entity_uuid, 'ACTIVITY_OUTPUT', '->')
# Create relationship from each ancestor entity node to this Activity node
create_outgoing_activity_relationships_tx(tx=tx
, source_node_uuids=direct_ancestor_uuids
, activity_node_uuid=activity_uuid)
tx.commit()
except TransactionError as te:
msg = "TransactionError from calling link_entity_to_direct_ancestors(): "
# Log the full stack trace, prepend a line with our message
logger.exception(msg)
if tx.closed() == False:
# Log the full stack trace, prepend a line with our message
logger.error("Failed to commit link_entity_to_direct_ancestors() transaction, rollback")
tx.rollback()
raise TransactionError(msg)
"""
Create linkages from new direct ancestors to an EXISTING activity node in neo4j.
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
entity_uuid : str
The uuid of target child entity
new_ancestor_uuid : str
The uuid of new direct ancestor to be linked
activity_uuid : str
The uuid of the existing activity node to link to
"""
def add_new_ancestors_to_existing_activity(neo4j_driver, new_ancestor_uuids, activity_uuid, create_activity, activity_data_dict, dataset_uuid):
try:
with neo4j_driver.session() as session:
tx = session.begin_transaction()
if create_activity:
create_activity_tx(tx, activity_data_dict)
create_relationship_tx(tx, activity_uuid, dataset_uuid, 'ACTIVITY_OUTPUT', '->')
create_outgoing_activity_relationships_tx(tx=tx
, source_node_uuids=new_ancestor_uuids
, activity_node_uuid=activity_uuid)
tx.commit()
except TransactionError as te:
msg = "TransactionError from calling add_new_ancestors_to_existing_activity(): "
logger.exception(msg)
if tx.closed() == False:
logger.error("Failed to commit add_new_ancestors_to_existing_activity() transaction, rollback")
tx.rollback()
raise TransactionError(msg)
"""
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
entity_uuid : str
The uuid of the target entity nodeget_paren
Returns
-------
str
The uuid of the direct ancestor Activity node
"""
def get_parent_activity_uuid_from_entity(neo4j_driver, entity_uuid):
query = """
MATCH (activity:Activity)-[:ACTIVITY_OUTPUT]->(entity:Entity {uuid: $entity_uuid})
RETURN activity.uuid AS activity_uuid
"""
with neo4j_driver.session() as session:
result = session.run(query, entity_uuid=entity_uuid)
record = result.single()
if record:
return record["activity_uuid"]
else:
return None
"""
Create or recreate linkage
between the publication node and the associated collection node in neo4j
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
entity_uuid : str
The uuid of the publication
associated_collection_uuid : str
the uuid of the associated collection
"""
def link_publication_to_associated_collection(neo4j_driver, entity_uuid, associated_collection_uuid):
try:
with neo4j_driver.session() as session:
tx = session.begin_transaction()
# First delete any old linkage between this publication and any associated_collection
_delete_publication_associated_collection_linkages_tx(tx, entity_uuid)
# Create relationship from this publication node to the associated collection node
create_relationship_tx(tx, entity_uuid, associated_collection_uuid, 'USES_DATA', '->')
tx.commit()
except TransactionError as te:
msg = "TransactionError from calling link_publication_to_associated_collection(): "
# Log the full stack trace, prepend a line with our message
logger.exception(msg)
if tx.closed() == False:
# Log the full stack trace, prepend a line with our message
logger.error("Failed to commit link_publication_to_associated_collection() transaction, rollback")
tx.rollback()
raise TransactionError(msg)
"""
Link a Collection to all the Datasets it should contain per the provided
argument. First, all existing linkages are deleted, then a link between
each entry of the dataset_uuid_list and collection_uuid is created in the
correction direction with an IN_COLLECTION relationship.
No Activity nodes are created in the relationship between a Collection and
its Datasets.
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
collection_uuid : str
The uuid of a Collection entity which is the target of an IN_COLLECTION relationship.
dataset_uuid_list : list of str
A list of uuids of Dataset entities which are the source of an IN_COLLECTION relationship.
"""
def link_collection_to_datasets(neo4j_driver, collection_uuid, dataset_uuid_list):
try:
with neo4j_driver.session() as session:
tx = session.begin_transaction()
# First delete all the old linkages between this Collection and its member Datasets
_delete_collection_linkages_tx(tx=tx
, uuid=collection_uuid)
_create_relationships_unwind_tx(tx=tx
, source_uuid_list=dataset_uuid_list
, target_uuid=collection_uuid
, relationship=Neo4jRelationshipEnum.IN_COLLECTION
, direction='->')
tx.commit()
except TransactionError as te:
msg = "TransactionError from calling link_collection_to_datasets(): "
# Log the full stack trace, prepend a line with our message
logger.exception(msg)
if tx.closed() == False:
# Log the full stack trace, prepend a line with our message
logger.error("Failed to commit link_collection_to_datasets() transaction, rollback")
tx.rollback()
raise TransactionError(msg)
"""
Create a revision linkage from the target entity node to the entity node
of the previous revision in neo4j
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
entity_uuid : str
The uuid of target entity
previous_revision_entity_uuid : str
The uuid of previous revision entity
"""
def link_entity_to_previous_revision(neo4j_driver, entity_uuid, previous_revision_entity_uuids):
try:
with neo4j_driver.session() as session:
tx = session.begin_transaction()
for previous_uuid in previous_revision_entity_uuids:
# Create relationship from ancestor entity node to this Activity node
create_relationship_tx(tx, entity_uuid, previous_uuid, 'REVISION_OF', '->')
tx.commit()
except TransactionError as te:
msg = "TransactionError from calling link_entity_to_previous_revision(): "
# Log the full stack trace, prepend a line with our message
logger.exception(msg)
if tx.closed() == False:
# Log the full stack trace, prepend a line with our message
logger.error("Failed to commit link_entity_to_previous_revision() transaction, rollback")
tx.rollback()
raise TransactionError(msg)
"""
Get the uuid of previous revision entity for a given entity
Parameters
----------
neo4j_driver : neo4j.Driver object
The neo4j database connection pool
uuid : str
The uuid of previous revision entity
Returns
-------
dict
The parent dict, can either be a Sample or Donor
"""
def get_previous_revision_uuid(neo4j_driver, uuid):
result = None
# Don't use [r:REVISION_OF] because
# Binding a variable length relationship pattern to a variable ('r') is deprecated
query = (f"MATCH (e:Entity)-[:REVISION_OF]->(previous_revision:Entity) "
f"WHERE e.uuid='{uuid}' "
f"RETURN previous_revision.uuid AS {record_field_name}")
logger.info("======get_previous_revision_uuid() query======")