FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
mage/python/export_util.py at main · memgraph/mage · GitHub
This repository was archived by the owner on Jan 23, 2026. It is now read-only.
memgraph
/
mage
Public archive
Notifications
You must be signed in to change notification settings
Fork
35
Star
331
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
mage
/
python
/
export_util.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
1282 lines (1054 loc) · 40.6 KB
Breadcrumbs
mage
/
python
/
export_util.py
Copy path
File metadata and controls
1282 lines (1054 loc) · 40.6 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
csv
import
io
import
json
as
js
import
mgp
import
gqlalchemy
import
os
from
dataclasses
import
dataclass
from
datetime
import
datetime
,
date
,
time
,
timedelta
from
gqlalchemy
import
Memgraph
from
math
import
floor
from
typing
import
Any
,
Dict
,
List
,
Union
from
mage
.
export_import_util
.
parameters
import
Parameter
HEADER_FILENAME
=
"header.csv"
@
dataclass
class
Node
:
id
:
int
labels
:
list
properties
:
dict
def
get_dict
(
self
)
->
dict
:
return
{
Parameter
.
ID
.
value
:
self
.
id
,
Parameter
.
LABELS
.
value
:
self
.
labels
,
Parameter
.
PROPERTIES
.
value
:
self
.
properties
,
Parameter
.
TYPE
.
value
:
Parameter
.
NODE
.
value
,
}
@
dataclass
class
Relationship
:
end
:
int
id
:
int
label
:
str
properties
:
dict
start
:
int
id
:
int
def
get_dict
(
self
)
->
dict
:
return
{
Parameter
.
END
.
value
:
self
.
end
,
Parameter
.
ID
.
value
:
self
.
id
,
Parameter
.
LABEL
.
value
:
self
.
label
,
Parameter
.
PROPERTIES
.
value
:
self
.
properties
,
Parameter
.
START
.
value
:
self
.
start
,
Parameter
.
TYPE
.
value
:
Parameter
.
RELATIONSHIP
.
value
,
}
@
dataclass
class
KeyObjectGraphML
:
name
:
str
is_for
:
str
type
:
str
type_is_list
:
bool
default_value
:
str
id
:
str
=
None
def
__init__
(
self
,
name
:
str
,
is_for
:
str
,
type
:
str
=
""
,
type_is_list
:
str
=
False
,
default_value
:
str
=
""
,
):
self
.
name
=
name
self
.
is_for
=
is_for
self
.
type
=
type
self
.
type_is_list
=
type_is_list
self
.
default_value
=
default_value
def
__hash__
(
self
):
return
hash
(
(
self
.
name
,
self
.
is_for
,
self
.
type
,
self
.
type_is_list
,
self
.
default_value
,
)
)
def
__eq__
(
self
,
other
):
if
not
isinstance
(
other
,
type
(
self
)):
return
NotImplemented
return
(
self
.
name
==
other
.
name
and
self
.
is_for
==
other
.
is_for
and
self
.
type
==
other
.
type
and
self
.
type_is_list
==
other
.
type_is_list
and
self
.
default_value
==
other
.
default_value
)
def
convert_to_isoformat
(
property
:
Union
[
None
,
str
,
bool
,
int
,
float
,
List
[
Any
],
Dict
[
str
,
Any
],
timedelta
,
time
,
datetime
,
date
,
]
):
if
isinstance
(
property
,
timedelta
):
return
Parameter
.
DURATION
.
value
+
str
(
property
)
+
")"
elif
isinstance
(
property
,
time
):
return
Parameter
.
LOCALTIME
.
value
+
property
.
isoformat
()
+
")"
elif
isinstance
(
property
,
datetime
):
return
Parameter
.
LOCALDATETIME
.
value
+
property
.
isoformat
()
+
")"
elif
isinstance
(
property
,
date
):
return
Parameter
.
DATE
.
value
+
property
.
isoformat
()
+
")"
else
:
return
property
def
to_duration_iso_format
(
value
:
timedelta
)
->
str
:
"""Converts timedelta to ISO-8601 duration: P<date>T<time>"""
date_parts
:
List
[
str
]
=
[]
time_parts
:
List
[
str
]
=
[]
if
value
.
days
!=
0
:
date_parts
.
append
(
f"
{
abs
(
value
.
days
)
}
D"
)
if
value
.
seconds
!=
0
or
value
.
microseconds
!=
0
:
abs_seconds
=
abs
(
value
.
seconds
)
hours
=
floor
(
abs_seconds
/
3600
)
minutes
=
floor
((
abs_seconds
-
hours
*
3600
)
/
60
)
seconds
=
abs_seconds
-
hours
*
3600
-
minutes
*
60
microseconds
=
value
.
microseconds
if
hours
>
0
:
time_parts
.
append
(
f"
{
hours
}
H"
)
if
minutes
>
0
:
time_parts
.
append
(
f"
{
minutes
}
M"
)
if
seconds
>
0
or
microseconds
>
0
:
microseconds_part
=
(
f".
{
abs
(
value
.
microseconds
)
}
"
if
value
.
microseconds
!=
0
else
""
)
time_parts
.
append
(
f"
{
seconds
}
{
microseconds_part
}
S"
)
date_duration_str
=
""
.
join
(
date_parts
)
time_duration_str
=
f'T
{
""
.
join
(
time_parts
)
}
'
if
time_parts
else
""
return
f"P
{
date_duration_str
}
{
time_duration_str
}
"
def
convert_to_cypher_format
(
property
:
Union
[
None
,
str
,
bool
,
int
,
float
,
List
[
Any
],
Dict
[
str
,
Any
],
timedelta
,
time
,
datetime
,
date
,
]
)
->
str
:
if
isinstance
(
property
,
timedelta
):
return
f"duration('
{
to_duration_iso_format
(
property
)
}
')"
elif
isinstance
(
property
,
time
):
return
f"localTime('
{
property
.
isoformat
()
}
')"
elif
isinstance
(
property
,
datetime
):
return
f"localDateTime('
{
property
.
isoformat
()
}
')"
elif
isinstance
(
property
,
date
):
return
f"date('
{
property
.
isoformat
()
}
')"
elif
isinstance
(
property
,
str
):
return
f"'
{
property
}
'"
elif
isinstance
(
property
,
tuple
):
# list
return
(
"["
+
", "
.
join
([
convert_to_cypher_format
(
item
)
for
item
in
property
])
+
"]"
)
elif
isinstance
(
property
,
dict
):
return
(
"{"
+
", "
.
join
(
[
f"
{
k
}
:
{
convert_to_cypher_format
(
v
)
}
"
for
k
,
v
in
property
.
items
()]
)
+
"}"
)
return
str
(
property
)
def
get_properties_cypher
(
object
,
write_properties
:
bool
)
->
dict
:
return
(
{
key
:
convert_to_cypher_format
(
object
.
properties
.
get
(
key
))
for
key
in
object
.
properties
.
keys
()
}
if
write_properties
else
{}
)
def
get_graph_for_cypher
(
ctx
:
mgp
.
ProcCtx
,
write_properties
:
bool
)
->
List
[
Union
[
Node
,
Relationship
]]:
nodes
=
list
()
relationships
=
list
()
for
vertex
in
ctx
.
graph
.
vertices
:
labels
=
[
label
.
name
for
label
in
vertex
.
labels
]
properties
=
get_properties_cypher
(
vertex
,
write_properties
)
nodes
.
append
(
Node
(
vertex
.
id
,
labels
,
properties
))
for
edge
in
vertex
.
out_edges
:
properties
=
get_properties_cypher
(
edge
,
write_properties
)
relationships
.
append
(
Relationship
(
edge
.
to_vertex
.
id
,
edge
.
id
,
edge
.
type
.
name
,
properties
,
edge
.
from_vertex
.
id
,
)
)
return
nodes
+
relationships
def
format_properties_cypher
(
properties
)
->
str
:
return
"{"
+
", "
.
join
([
f"
{
k
}
:
{
v
}
"
for
k
,
v
in
properties
.
items
()])
+
"}"
@
mgp
.
read_proc
def
cypher_all
(
ctx
:
mgp
.
ProcCtx
,
path
:
str
=
""
,
config
:
mgp
.
Map
=
{},
)
->
mgp
.
Record
(
path
=
str
,
data
=
str
):
"""Exports the graph in cypher with all the constraints, indexes and triggers.
Args:
context (mgp.ProcCtx): Reference to the context execution.
path (str): A path to the file where the query results will be exported. Defaults to an empty string.
config : mgp.Map
stream (bool) = False: Flag to export the graph data to a stream.
write_properties (bool) = True: Flag to keep node and relationship properties. By default set to true.
write_triggers (bool) = True: Flag to export graph triggers.
write_indexes (bool) = True: Flag to export indexes.
write_constraints (bool) = True: Flag to export constraints.
Returns:
path (str): A path to the file where the query results are exported. If path is not provided, the output will be an empty string.
data (str): A stream of query results in a cypher format.
Raises:
PermissionError: If you provided file path that you have no permissions to write at.
OSError: If the file can't be opened or written to.
"""
cypher
=
[]
memgraph
=
gqlalchemy
.
Memgraph
()
if
config
.
get
(
"write_triggers"
,
True
):
triggers
=
memgraph
.
execute_and_fetch
(
"SHOW TRIGGERS;"
)
for
trigger
in
triggers
:
cypher
.
append
(
f"CREATE TRIGGER
{
trigger
[
'trigger name'
]
}
ON
{
trigger
[
'event type'
]
}
{
trigger
[
'phase'
]
}
EXECUTE
{
trigger
[
'statement'
]
}
;"
)
cypher
.
append
(
""
)
if
config
.
get
(
"write_indexes"
,
True
):
constraints
=
memgraph
.
execute_and_fetch
(
"SHOW CONSTRAINT INFO;"
)
for
constraint
in
constraints
:
constraint_type
=
constraint
[
"constraint type"
]
if
constraint_type
==
"exists"
:
cypher
.
append
(
f"CREATE CONSTRAINT ON (n:
{
constraint
[
'label'
]
}
) ASSERT EXISTS (n.
{
constraint
[
'properties'
]
}
);"
)
elif
constraint_type
==
"unique"
:
properties
=
(
[
constraint
[
"properties"
]]
if
isinstance
(
constraint
[
"properties"
],
str
)
else
list
(
constraint
[
"properties"
])
)
cypher
.
append
(
f"CREATE CONSTRAINT ON (n:
{
constraint
[
'label'
]
}
) ASSERT
{
'n.'
+
', n.'
.
join
(
properties
)
}
IS UNIQUE;"
)
else
:
raise
ValueError
(
"Unknown constraint type."
)
cypher
.
append
(
""
)
if
config
.
get
(
"write_constraints"
,
True
):
indexes
=
memgraph
.
execute_and_fetch
(
"SHOW INDEX INFO;"
)
for
index
in
indexes
:
index_type
=
index
[
"index type"
]
if
index_type
==
"label"
:
cypher
.
append
(
f"CREATE INDEX ON :
{
index
[
'label'
]
}
;"
)
elif
index_type
==
"label+property"
:
cypher
.
append
(
f"CREATE INDEX ON :
{
index
[
'label'
]
}
(
{
index
[
'property'
]
}
);"
)
else
:
raise
ValueError
(
"Unknown index type."
)
cypher
.
append
(
""
)
graph
=
get_graph_for_cypher
(
ctx
,
config
.
get
(
"write_properties"
,
True
))
for
object
in
graph
:
if
isinstance
(
object
,
Node
):
object
.
labels
.
append
(
"_IMPORT_ID"
)
object
.
properties
[
"_IMPORT_ID"
]
=
object
.
id
properties_str
=
format_properties_cypher
(
object
.
properties
)
cypher
.
append
(
f"CREATE (n:
{
':'
.
join
(
object
.
labels
)
}
{
properties_str
}
);"
)
elif
isinstance
(
object
,
Relationship
):
properties_str
=
format_properties_cypher
(
object
.
properties
)
cypher
.
append
(
f"MATCH (n:_IMPORT_ID {{_IMPORT_ID:
{
object
.
start
}
}}) MATCH (m:_IMPORT_ID {{_IMPORT_ID:
{
object
.
end
}
}}) CREATE (n)-[:
{
object
.
label
}
{
properties_str
}
]->(m);"
)
cypher
.
append
(
"MATCH (n:_IMPORT_ID) REMOVE n:`_IMPORT_ID` REMOVE n._IMPORT_ID;"
)
if
path
:
try
:
with
open
(
path
,
"w"
)
as
f
:
f
.
write
(
"
\n
"
.
join
(
cypher
))
except
PermissionError
:
raise
PermissionError
(
"You don't have permissions to write into that file. Make sure to give the necessary permissions to user memgraph."
)
except
Exception
:
raise
OSError
(
"Could not open or write to the file."
)
return
mgp
.
Record
(
path
=
path
,
data
=
"
\n
"
.
join
(
cypher
)
if
config
.
get
(
"stream"
,
False
)
else
""
)
def
get_properties_json
(
object
,
write_properties
:
bool
):
return
(
{
key
:
convert_to_isoformat
(
object
.
properties
.
get
(
key
))
for
key
in
object
.
properties
.
keys
()
}
if
write_properties
else
{}
)
def
convert_to_isoformat_graphML
(
property
:
Union
[
None
,
str
,
bool
,
int
,
float
,
List
[
Any
],
Dict
[
str
,
Any
],
timedelta
,
time
,
datetime
,
date
,
]
):
if
isinstance
(
property
,
timedelta
):
return
to_duration_iso_format
(
property
)
if
isinstance
(
property
, (
time
,
date
,
datetime
)):
return
property
.
isoformat
()
else
:
return
property
def
get_graph
(
ctx
:
mgp
.
ProcCtx
,
write_properties
:
bool
)
->
List
[
Union
[
Node
,
Relationship
]]:
nodes
=
list
()
relationships
=
list
()
for
vertex
in
ctx
.
graph
.
vertices
:
labels
=
[
label
.
name
for
label
in
vertex
.
labels
]
properties
=
get_properties_json
(
vertex
,
write_properties
)
nodes
.
append
(
Node
(
vertex
.
id
,
labels
,
properties
).
get_dict
())
for
edge
in
vertex
.
out_edges
:
properties
=
get_properties_json
(
edge
,
write_properties
)
relationships
.
append
(
Relationship
(
edge
.
to_vertex
.
id
,
edge
.
id
,
edge
.
type
.
name
,
properties
,
edge
.
from_vertex
.
id
,
).
get_dict
()
)
return
nodes
+
relationships
def
get_graphML
(
ctx
:
mgp
.
ProcCtx
,
config
:
Union
[
mgp
.
Map
,
None
]
=
{
"graphML"
:
False
,
"leaveOutLabels"
:
False
,
"leaveOutProperties"
:
False
,
},
)
->
List
[
Union
[
Node
,
Relationship
]]:
"""
config : Map
- graphML: bool
- leaveOutLabels: bool
- leaveOutProperties: bool
"""
nodes
=
list
()
relationships
=
list
()
for
vertex
in
ctx
.
graph
.
vertices
:
labels
=
[]
properties
=
dict
()
if
not
config
.
get
(
"leaveOutLabels"
):
labels
=
[
label
.
name
for
label
in
vertex
.
labels
]
if
config
.
get
(
"graphML"
)
and
not
config
.
get
(
"leaveOutProperties"
):
properties
=
{
key
:
convert_to_isoformat_graphML
(
vertex
.
properties
.
get
(
key
))
for
key
in
vertex
.
properties
.
keys
()
}
elif
not
config
.
get
(
"leaveOutProperties"
):
properties
=
{
key
:
convert_to_isoformat
(
vertex
.
properties
.
get
(
key
))
for
key
in
vertex
.
properties
.
keys
()
}
nodes
.
append
(
Node
(
vertex
.
id
,
labels
,
properties
).
get_dict
())
for
edge
in
vertex
.
out_edges
:
if
not
config
.
get
(
"leaveOutProperties"
):
properties
=
{
key
:
convert_to_isoformat
(
edge
.
properties
.
get
(
key
))
for
key
in
edge
.
properties
.
keys
()
}
relationships
.
append
(
Relationship
(
edge
.
to_vertex
.
id
,
edge
.
id
,
edge
.
type
.
name
,
properties
,
edge
.
from_vertex
.
id
,
).
get_dict
()
)
return
nodes
+
relationships
def
get_graph_from_list
(
graph_vertices
:
list
,
graph_edges
:
list
,
write_properties
:
bool
)
->
List
[
Union
[
Node
,
Relationship
]]:
nodes
=
list
()
relationships
=
list
()
for
vertex
in
graph_vertices
:
labels
=
[
label
.
name
for
label
in
vertex
.
labels
]
properties
=
get_properties_json
(
vertex
,
write_properties
)
nodes
.
append
(
Node
(
vertex
.
id
,
labels
,
properties
).
get_dict
())
for
edge
in
graph_edges
:
properties
=
get_properties_json
(
edge
,
write_properties
)
relationships
.
append
(
Relationship
(
edge
.
to_vertex
.
id
,
edge
.
id
,
edge
.
type
.
name
,
properties
,
edge
.
from_vertex
.
id
,
).
get_dict
()
)
return
nodes
+
relationships
def
get_graph_info_from_lists
(
node_list
:
List
[
mgp
.
Vertex
],
relationship_list
:
List
[
mgp
.
Edge
]
):
graph
=
list
()
all_node_properties
=
list
()
all_node_prop_set
=
set
()
all_relationship_properties
=
list
()
all_relationship_prop_set
=
set
()
for
node
in
node_list
:
for
prop
in
node
.
properties
:
if
prop
not
in
all_node_prop_set
:
all_node_properties
.
append
(
prop
)
all_node_prop_set
.
add
(
prop
)
graph
.
append
(
Node
(
node
.
id
,
node
.
labels
,
node
.
properties
))
all_node_properties
.
sort
()
for
relationship
in
relationship_list
:
for
prop
in
relationship
.
properties
:
if
prop
not
in
all_relationship_prop_set
:
all_relationship_properties
.
append
(
prop
)
all_relationship_prop_set
.
add
(
prop
)
graph
.
append
(
Relationship
(
relationship
.
to_vertex
.
id
,
relationship
.
id
,
relationship
.
type
.
name
,
relationship
.
properties
,
relationship
.
from_vertex
.
id
,
)
)
all_relationship_properties
.
sort
()
return
graph
,
all_node_properties
,
all_relationship_properties
def
json_dump_to_file
(
graph
:
List
[
Union
[
Node
,
Relationship
]],
path
:
str
):
try
:
with
open
(
path
,
"w"
)
as
outfile
:
js
.
dump
(
graph
,
outfile
,
indent
=
Parameter
.
STANDARD_INDENT
.
value
,
default
=
str
,
)
except
PermissionError
:
raise
PermissionError
(
"You don't have permissions to write into that file. Make sure to give the necessary permissions to user memgraph."
# noqa: E501
)
except
Exception
:
raise
OSError
(
"Could not open or write to the file."
)
@
mgp
.
read_proc
def
json
(
ctx
:
mgp
.
ProcCtx
,
path
:
str
=
""
,
config
:
mgp
.
Map
=
{}
)
->
mgp
.
Record
(
path
=
str
,
data
=
str
):
"""
Procedure to export the whole database to a JSON file.
Parameters:
context : mgp.ProcCtx
Reference to the context execution.
path : str = ""
Path to the JSON file containing the exported graph database.
config : mgp.Map
stream (bool) = False: Flag to export the graph data to a stream.
write_properties (bool) = True: Flag to keep node and relationship properties. By default set to true.
Returns:
path (str): A path to the file where the query results are exported. If path is not provided, the output will be an empty string.
data (str): A stream of query results in JSON format.
Raises:
PermissionError: If you provided file path that you have no permissions to write at.
OSError: If the file can't be opened or written to.
"""
graph
=
get_graph
(
ctx
,
config
.
get
(
"write_properties"
,
True
))
if
path
:
json_dump_to_file
(
graph
,
path
)
return
mgp
.
Record
(
path
=
path
,
data
=
js
.
dumps
(
graph
)
if
config
.
get
(
"stream"
,
False
)
else
""
,
)
@
mgp
.
read_proc
def
json_graph
(
ctx
:
mgp
.
ProcCtx
,
nodes
:
list
,
relationships
:
list
,
path
:
str
=
""
,
config
:
mgp
.
Map
=
{},
)
->
mgp
.
Record
(
path
=
str
,
data
=
str
):
"""
Procedure to export the given graph to a JSON file. The graph is given with a map that contains keys "nodes" and "relationships".
Parameters:
nodes : List[Node]
A list thats contains all nodes in the given graph.
relationships : List[Relationship]
A list that containts all the relationships in the given graph.
path : str
Path to the JSON file containing the exported graph database.
config : mgp.Map
stream (bool) = False: Flag to export the graph data to a stream.
write_properties (bool) = True: Flag to keep node and relationship properties. By default set to true.
Returns:
path (str): A path to the file where the query results are exported. If path is not provided, the output will be an empty string.
data (str): A stream of query results in JSON format.
Raises:
PermissionError: If you provided file path that you have no permissions to write at.
OSError: If the file can't be opened or written to.
"""
graph
=
get_graph_from_list
(
nodes
,
relationships
,
config
.
get
(
"write_properties"
,
True
)
)
if
path
:
json_dump_to_file
(
graph
,
path
)
return
mgp
.
Record
(
path
=
path
,
data
=
js
.
dumps
(
graph
)
if
config
.
get
(
"stream"
,
False
)
else
""
,
)
def
save_file
(
file_path
:
str
,
data_list
:
list
):
try
:
with
open
(
file_path
,
"w"
,
newline
=
""
,
encoding
=
"utf8"
,
)
as
f
:
writer
=
csv
.
writer
(
f
)
writer
.
writerows
(
data_list
)
except
PermissionError
:
raise
PermissionError
(
"You don't have permissions to write into that file. Make sure to give the necessary permissions to user memgraph."
# noqa: E501
)
except
csv
.
Error
as
e
:
raise
csv
.
Error
(
"Could not write to the file {}, stopped at line {}: {}"
.
format
(
file_path
,
writer
.
line_num
,
e
)
)
except
Exception
:
raise
OSError
(
"Could not open or write to the file."
)
def
csv_to_stream
(
data_list
:
list
,
delimiter
:
str
=
","
,
quoting_type
=
csv
.
QUOTE_NONNUMERIC
)
->
str
:
output
=
io
.
StringIO
()
try
:
writer
=
csv
.
writer
(
output
,
delimiter
=
delimiter
,
quoting
=
quoting_type
,
escapechar
=
"
\\
"
)
writer
.
writerows
(
data_list
)
except
csv
.
Error
as
e
:
raise
csv
.
Error
(
"Could not write a stream, stopped at line {}: {}"
.
format
(
writer
.
line_num
,
e
)
)
return
output
.
getvalue
()
def
csv_header
(
node_properties
:
List
[
str
],
relationship_properties
:
List
[
str
]
)
->
List
[
str
]:
"""
This function creates the header for csv file
"""
header
=
[
"_id"
,
"_labels"
]
for
prop
in
node_properties
:
header
.
append
(
prop
)
header
.
extend
([
"_start"
,
"_end"
,
"_type"
])
for
prop
in
relationship_properties
:
header
.
append
(
prop
)
return
[
header
]
def
process_properties
(
properties
:
Dict
[
str
,
mgp
.
Any
],
prop
:
str
,
write_list
:
List
[
mgp
.
Any
]
)
->
None
:
if
isinstance
(
properties
[
prop
], (
set
,
list
,
tuple
,
map
)):
write_list
.
append
(
js
.
dumps
(
properties
[
prop
]))
return
if
isinstance
(
properties
[
prop
],
timedelta
):
write_list
.
append
(
convert_to_isoformat
(
properties
[
prop
]))
return
write_list
.
append
(
properties
[
prop
])
def
csv_data_list
(
graph
:
List
[
Union
[
Node
,
Relationship
]],
node_properties
:
List
[
str
],
relationship_properties
:
List
[
str
],
)
->
List
[
mgp
.
Any
]:
"""
Function that parses graph into a data_list appropriate for csv writing
"""
data_list
=
[]
for
element
in
graph
:
write_list
=
[]
is_node
=
isinstance
(
element
,
Node
)
# processing id and labels part
if
is_node
:
write_list
.
extend
(
[
element
.
id
,
""
.
join
(
":"
+
label
.
name
for
label
in
element
.
labels
),
]
)
else
:
write_list
.
extend
([
""
,
""
])
# node_properties
for
prop
in
node_properties
:
if
prop
in
element
.
properties
and
is_node
:
process_properties
(
element
.
properties
,
prop
,
write_list
)
else
:
write_list
.
append
(
""
)
# relationship
if
is_node
:
# start, end, type
write_list
.
extend
([
""
,
""
,
""
])
else
:
# start, end, type
write_list
.
extend
([
element
.
start
,
element
.
end
,
element
.
label
])
# relationship properties
for
prop
in
relationship_properties
:
if
prop
in
element
.
properties
and
not
is_node
:
process_properties
(
element
.
properties
,
prop
,
write_list
)
else
:
write_list
.
append
(
""
)
data_list
.
append
(
write_list
)
return
data_list
def
check_config_valid
(
config
:
mgp
.
Any
,
type
:
mgp
.
Any
,
name
:
str
):
if
not
isinstance
(
config
,
type
):
raise
TypeError
(
"Config attribute {0} must be of type {1}"
.
format
(
name
,
type
))
def
csv_process_config
(
config
:
mgp
.
Map
):
delimiter
=
","
if
"delimiter"
in
config
:
check_config_valid
(
config
[
"delimiter"
],
str
,
"delimiter"
)
delimiter
=
config
[
"delimiter"
]
quoting_type
=
csv
.
QUOTE_ALL
if
"quotes"
in
config
:
check_config_valid
(
config
[
"quotes"
],
str
,
"quotes"
)
if
config
[
"quotes"
]
==
"none"
:
quoting_type
=
csv
.
QUOTE_NONE
elif
config
[
"quotes"
]
==
"ifNeeded"
:
quoting_type
=
csv
.
QUOTE_MINIMAL
separate_header
=
False
if
"separateHeader"
in
config
:
check_config_valid
(
config
[
"separateHeader"
],
bool
,
"separateHeader"
)
separate_header
=
config
[
"separateHeader"
]
stream
=
False
if
"stream"
in
config
:
check_config_valid
(
config
[
"stream"
],
bool
,
"stream"
)
stream
=
config
[
"stream"
]
return
delimiter
,
quoting_type
,
separate_header
,
stream
def
header_path
(
path
:
str
):
directory
,
filename
=
os
.
path
.
split
(
path
)
new_filename
=
HEADER_FILENAME
return
os
.
path
.
join
(
directory
,
new_filename
)
def
write_file
(
path
:
str
,
delimiter
:
str
,
quoting_type
:
str
,
data
:
mgp
.
Any
)
->
None
:
with
open
(
path
,
"w"
,
encoding
=
"utf-8"
)
as
file
:
writer
=
csv
.
writer
(
file
,
delimiter
=
delimiter
,
quoting
=
quoting_type
,
escapechar
=
"
\\
"
)
writer
.
writerows
(
data
)
@
mgp
.
read_proc
def
csv_graph
(
nodes_list
:
mgp
.
List
[
mgp
.
Vertex
],
relationships_list
:
mgp
.
List
[
mgp
.
Edge
],
path
:
str
=
""
,
config
:
mgp
.
Map
=
{},
)
->
mgp
.
Record
(
path
=
str
,
data
=
str
):
"""
Procedure to export the given graph to a csv file.
The graph is given with two lists, one for nodes,
and one for relationships.
Parameters
----------
nodes_list : List
A list containing nodes of the graph
relationships_list : List
A list containing relationships of the graph
path : str
Path to the JSON file containing the exported graph database.
config : mgp.Map
stream (bool) = False: Flag to export the graph data to a stream.
delimiter (string) = ,: Delimiter for csv file.
quotes (string) = always : Option which quoting type to use
separateHeader (bool) = False: Flag to separate header into another
csv file
"""
if
path
==
""
:
path
=
"exported_file.csv"
delimiter
,
quoting_type
,
separate_header
,
stream
=
csv_process_config
(
config
)
(
graph
,
node_properties
,
relationship_properties
,
)
=
get_graph_info_from_lists
(
nodes_list
,
relationships_list
)
data_list
=
csv_data_list
(
graph
,
node_properties
,
relationship_properties
)
header
=
csv_header
(
node_properties
,
relationship_properties
)
try
:
if
separate_header
:
if
not
stream
:
write_file
(
header_path
(
path
),
delimiter
,
quoting_type
,
header
)
else
:
data_list
=
header
+
data_list
if
stream
:
data
=
csv_to_stream
(
data_list
,
delimiter
,
quoting_type
)
return
mgp
.
Record
(
path
=
path
,
data
=
data
)
write_file
(
path
,
delimiter
,
quoting_type
,
data_list
)
except
PermissionError
:
raise
PermissionError
(
"You don't have permissions to write into that file."
"Make sure to give the necessary permissions to user memgraph."
)
except
Exception
:
raise
OSError
(
"Could not open or write to the file."
)
return
mgp
.
Record
(
path
=
path
,
data
=
""
,
)
@
mgp
.
read_proc
def
csv_query
(
context
:
mgp
.
ProcCtx
,
query
:
str
,
file_path
:
str
=
""
,
stream
:
bool
=
False
,
)
->
mgp
.
Record
(
file_path
=
str
,
data
=
str
):
"""
Procedure to export query results to a CSV file.
Args:
context (mgp.ProcCtx): Reference to the context execution.
query (str): A query from which the results will be
saved to a CSV file.
file_path (str, optional): A path to the CSV file where the query
results will be exported. Defaults to an empty string.
stream (bool, optional): A value which determines whether a
stream of query results in a CSV format will be returned.
Returns:
mgp.Record(
file_path (str): A path to the CSV file where the query results are
exported. If file_path is not provided, the output will be an
empty string.
data (str): A stream of query results in a CSV format.
)
Raises:
Exception: If neither file nor config are provided,
or if only config is provided with stream set to False.
Also if query yields no results or if the database is empty.
PermissionError: If you provided file path that you have
no permissions to write at.
csv.Error: If an error occurred while writing into stream or CSV file.
OSError: If the file can't be opened or written to.
"""
# noqa: E501
# file or config have to be provided
if
not
file_path
and
not
stream
:
raise
Exception
(
"Please provide file name and/or config."
)
# only config provided with stream set to false
if
not
file_path
and
not
stream
:
raise
Exception
(
"If you provided only stream value, it has to be set to True to get any results."
# noqa: E501
)
memgraph
=
Memgraph
()
results
=
list
(
memgraph
.
execute_and_fetch
(
query
))
# if query yields no result
if
not
len
(
results
):
raise
Exception
(
"Your query yields no results. Check if the database is empty or rewrite the provided query."
# noqa: E501
)
result_keys
=
list
(
results
[
0
])
data_list
=
[
result_keys
]
+
[
list
(
result
.
values
())
for
result
in
results
]
data
=
""
if
file_path
:
save_file
(
file_path
,
data_list
)
if
stream
:
data
=
csv_to_stream
(
data_list
)
return
mgp
.
Record
(
file_path
=
file_path
,
data
=
data
)
def
write_graphml_header
(
output
:
io
.
StringIO
):
output
.
write
(
'<?xml version="1.0" encoding="UTF-8"?>
\n
'
)
output
.
write
(
'<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
\n
'
# noqa: E501
)
def
translate_types
(
variable
:
Any
):
if
isinstance
(
variable
,
tuple
):
return
get_value_string
(
variable
)
if
isinstance
(
variable
,
str
):
return
"string"
if
isinstance
(
variable
,
bool
):
return
"boolean"
if
isinstance
(
variable
,
float
):
return
"float"
if
isinstance
(
variable
,
int
):
return
"int"
raise
Exception
(
"Property values can only be primitive types or arrays of primitive types."
# noqa: E501
)
def
check_if_elements_same_type
(
variable
:
List
[
Any
]):
if
not
isinstance
(
variable
, (
tuple
,
list
)):
return
list_type
=
type
(
variable
[
0
])
for
element
in
variable
:
if
not
isinstance
(
element
,
list_type
):
raise
Exception
(
"If property value is a list it must consist of same typed elements."
# noqa: E501
)
def
get_type_string
(
variable
:
Any
)
->
Union
[
str
,
List
[
Any
]]:
if
not
isinstance
(
variable
,
tuple
):
return
translate_types
(
variable
),
False
if
len
(
variable
)
==
0
:
return
"string"
,
True
check_if_elements_same_type
(
variable
)
return
translate_types
(
variable
[
0
]),
True
def
write_key_graphml
(
output
:
io
.
StringIO
,
working_key
:
KeyObjectGraphML
,
key_id_counter
:
int
,
config
:
mgp
.
Map
,
):
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL