-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathgraph-data-science.neo4j-browser-guide
2957 lines (2693 loc) · 107 KB
/
graph-data-science.neo4j-browser-guide
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
<style type="text/css" media="screen">
/*
.nodes-image {
margin:-100;
}
*/
@import url("//maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css");
.imageblock .content img, .image img {max-width: 100%;}
.deck h3, .deck h4 {display: block !important;margin-bottom:8px;margin-top:5px;}
.listingblock {margin:8px;}
.pull-bottom {position:relative;bottom:1em;}
.admonitionblock td.icon [class^="fa icon-"]{font-size:2.5em;text-shadow:1px 1px 2px rgba(0,0,0,.5);cursor:default}
.admonitionblock td.icon .icon-note:before{content:"\f05a";color:#19407c}
.admonitionblock td.icon .icon-tip:before{content:"\f0eb";text-shadow:1px 1px 2px rgba(155,155,0,.8);color:#111}
.admonitionblock td.icon .icon-warning:before{content:"\f071";color:#bf6900}
.admonitionblock td.icon .icon-caution:before{content:"\f06d";color:#bf3400}
.admonitionblock td.icon .icon-important:before{content:"\f06a";color:#bf0000}
.admonitionblock.note.speaker { display:none; }
</style>
<style type="text/css" media="screen">
/* #editor.maximize-editor .CodeMirror-code { font-size:24px; line-height:26px; } */
</style>
<article class="guide" ng-controller="AdLibDataController">
<carousel class="deck container-fluid">
<!--slide class="row-fluid">
<div class="col-sm-3">
<h3>Graph Algorithms</h3>
<p class="lead">Information</p>
<!dl>
</dl>
</div>
<div class="col-sm-9">
<figure>
<img style="width:300px" src=""/>
</figure>
</div>
</slide-->
<h4>Graph Algorithms</h4>
<slide class="row-fluid">
<div class="col-sm-12">
<h3>Neo4j Graph Data Science</h3>
<br/>
<div>
<div class="paragraph">
<p>The Neo4j Graph Data Science (GDS) library contains a set of graph algorithms, exposed through Cypher procedures.
Graph algorithms provide insights into the graph structure and elements, for example, by computing centrality and similarity scores, and detecting communities.
The GDS library is divided into three tiers of maturity: product, beta and alpha.</p>
</div>
<div class="paragraph">
<p>This guide follows the ordinary workflow for running the product tier algorithms: PageRank, Label Propagation, Weakly Connected Components, Louvain, and Node Similarity.</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Estimate memory usage for your graph and the algorithm you want to run.</p>
</li>
<li>
<p>Create a graph and manage created graphs.</p>
</li>
<li>
<p>Configure the algorithm to suit your needs and run it in one of the supported modes: stream, write, and stats.</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>For more resources, see <a href="https://neo4j.com/developer/graph-data-science/" target="_blank">the developer guides</a>.</p>
</div>
<div class="paragraph">
<p>The official Graph Data Science (GDS) library documentation can be found <a href="https://neo4j.com/docs/graph-data-science/current/" target="_blank">here</a>.</p>
</div>
</div>
</div>
</slide>
<slide class="row-fluid">
<div class="col-sm-12">
<h3>The example dataset</h3>
<br/>
<div>
<div class="imageblock" style="float: right;">
<div class="content">
<img src="https://upload.wikimedia.org/wikipedia/en/2/24/AStormOfSwords.jpg" alt="AStormOfSwords" width="150">
</div>
</div>
<div class="paragraph">
<p>Before you can run any of the algorithms, you need to import your data in Neo4j.<br>
The example dataset used to demonstrate the GDS library is based on the Game of Thrones fantasy saga.
You may recognize it from the blogs, events, and sandbox.
However, both data and queries are different enough from previous installments that it merits your attention.
 <br>
 <br>
 <br></p>
</div>
<h4>Attribution</h4>
<div class="paragraph">
<p>The dataset is partly based on the following works:</p>
</div>
<div class="paragraph">
<p><em><a href="https://networkofthrones.wordpress.com/" target="_blank">Network of Thrones, A Song of Math and Westeros</a>, research by Dr. Andrew Beveridge.</em><br>
<em><a href="https://www.macalester.edu/~abeverid/index.html" target="_blank">A. Beveridge and J. Shan, "Network of Thrones," Math Horizons Magazine , Vol. 23, No. 4 (2016), pp. 18-22</a></em><br>
<em><a href="https://www.kaggle.com/mylesoneill/game-of-thrones">Game of Thrones, Explore deaths and battles from this fantasy world</a>, by Myles O’Neill, <a href="https://www.kaggle.com/" target="_blank">https://www.kaggle.com/</a></em><br>
<em><a href="https://github.com/tomasonjo/neo4j-game-of-thrones" target="_blank">Game of Thrones</a>, by Tomaz Bratanic, GitHub repository.</em></p>
</div>
</div>
</div>
</slide>
<slide class="row-fluid">
<div class="col-sm-12">
<h3>Graph of character interactions.. and more</h3>
<br/>
<div>
<div class="paragraph">
<p>The graph contains <code>:Person</code> nodes, representing the characters, and <code>:INTERACTS</code> relationships, representing the characters' interactions.
An interaction occurs each time two characters' names (or nicknames) <strong>appear within 15 words of one another</strong> in the book text.
For more information about the data extraction process, see <em><a href="https://networkofthrones.wordpress.com/from-book-to-network/" target="_blank">Network of Thrones, A Song of Math and Westeros</a>, research by Dr. Andrew Beveridge.</em></p>
</div>
<div class="paragraph">
<p>The <code>(:Person)-[:INTERACTS]→(:Person)</code> graph is enriched with data on houses, battles, commanders, kings, knights, regions, locations, and deaths.</p>
</div>
<div class="paragraph">
<p>Now, let’s import the data.</p>
</div>
</div>
</div>
</slide>
<slide class="row-fluid">
<div class="col-sm-12">
<h3>Data ingestion</h3>
<br/>
<div>
<div class="listingblock">
<div class="title">Enable <code>multi statement queries</code></div>
<div class="content">
<pre mode="cypher" class="highlight pre-scrollable programlisting cm-s-neo code runnable standalone-example ng-binding"><!--code-->:config "enableMultiStatementMode":true<!--/code--></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Create unique constraints on the names of the nodes <code>:Location</code>, <code>:Region</code>, <code>:Battle</code>, <code>:Person</code>, and <code>:House</code>. This ensures your data integrity and improves performance.</div>
<div class="content">
<pre mode="cypher" class="highlight pre-scrollable programlisting cm-s-neo code runnable standalone-example ng-binding" data-lang="cypher" lang="cypher"><!--code class="cypher language-cypher"-->CREATE CONSTRAINT IF NOT EXISTS FOR (n:Location) REQUIRE (n.name) IS UNIQUE;
CREATE CONSTRAINT IF NOT EXISTS FOR (n:Region) REQUIRE (n.name) IS UNIQUE;
CREATE CONSTRAINT IF NOT EXISTS FOR (n:Battle) REQUIRE (n.name) IS UNIQUE;
CREATE CONSTRAINT IF NOT EXISTS FOR (n:Person) REQUIRE (n.name) IS UNIQUE;
CREATE CONSTRAINT IF NOT EXISTS FOR (n:House) REQUIRE (n.name) IS UNIQUE;<!--/code--></pre>
</div>
</div>
<div class="listingblock">
<div class="title">Then, ingest the data.</div>
<div class="content">
<pre mode="cypher" class="highlight pre-scrollable programlisting cm-s-neo code runnable standalone-example ng-binding" data-lang="cypher" lang="cypher"><!--code class="cypher language-cypher"-->LOAD CSV WITH HEADERS FROM 'https://s3.eu-north-1.amazonaws.com/com.neo4j.gds.browser-guide/data/battles.csv' AS row
MERGE (b:Battle {name: row.name})
ON CREATE SET b.year = toInteger(row.year),
b.summer = row.summer,
b.major_death = row.major_death,
b.major_capture = row.major_capture,
b.note = row.note,
b.battle_type = row.battle_type,
b.attacker_size = toInteger(row.attacker_size),
b.defender_size = toInteger(row.defender_size);
LOAD CSV WITH HEADERS FROM 'https://s3.eu-north-1.amazonaws.com/com.neo4j.gds.browser-guide/data/battles.csv' AS row
// Because there is only attacker_outcome in the data, do a CASE statement for defender_outcome.
WITH row,
CASE WHEN row.attacker_outcome = 'win' THEN 'loss'
ELSE 'win'
END AS defender_outcome
// Match the battle
MATCH (b:Battle {name: row.name})
// All battles have at least one attacker, so you don't have to use FOREACH.
MERGE (attacker1:House {name: row.attacker_1})
MERGE (attacker1)-[a1:ATTACKER]->(b)
ON CREATE SET a1.outcome = row.attacker_outcome
// Use FOREACH to skip the null values.
FOREACH
(ignoreMe IN CASE WHEN row.defender_1 IS NOT NULL THEN [1]
ELSE []
END |
MERGE (defender1:House {name: row.defender_1})
MERGE (defender1)-[d1:DEFENDER]->(b)
ON CREATE SET d1.outcome = defender_outcome
)
FOREACH
(ignoreMe IN CASE WHEN row.defender_2 IS NOT NULL THEN [1]
ELSE []
END |
MERGE (defender2:House {name: row.defender_2})
MERGE (defender2)-[d2:DEFENDER]->(b)
ON CREATE SET d2.outcome = defender_outcome
)
FOREACH
(ignoreMe IN CASE WHEN row.attacker_2 IS NOT NULL THEN [1]
ELSE []
END |
MERGE (attacker2:House {name: row.attacker_2})
MERGE (attacker2)-[a2:ATTACKER]->(b)
ON CREATE SET a2.outcome = row.attacker_outcome
)
FOREACH
(ignoreMe IN CASE WHEN row.attacker_3 IS NOT NULL THEN [1]
ELSE []
END |
MERGE (attacker2:House {name: row.attacker_3})
MERGE (attacker3)-[a3:ATTACKER]->(b)
ON CREATE SET a3.outcome = row.attacker_outcome
)
FOREACH
(ignoreMe IN CASE WHEN row.attacker_4 IS NOT NULL THEN [1]
ELSE []
END |
MERGE (attacker4:House {name: row.attacker_4})
MERGE (attacker4)-[a4:ATTACKER]->(b)
ON CREATE SET a4.outcome = row.attacker_outcome
);
LOAD CSV WITH HEADERS FROM
'https://s3.eu-north-1.amazonaws.com/com.neo4j.gds.browser-guide/data/battles.csv'
AS row
MATCH (b:Battle {name: row.name})
// Use coalesce to replace the null values with "Unknown".
MERGE (location:Location {name: coalesce(row.location, 'Unknown')})
MERGE (b)-[:IS_IN]->(location)
MERGE (region:Region {name: row.region})
MERGE (location)-[:IS_IN]->(region);
LOAD CSV WITH HEADERS FROM 'https://s3.eu-north-1.amazonaws.com/com.neo4j.gds.browser-guide/data/battles.csv' AS row
// Split the columns that may contain more than one person.
WITH row,
split(row.attacker_commander, ',') AS att_commanders,
split(row.defender_commander, ',') AS def_commanders,
split(row.attacker_king, '/') AS att_kings,
split(row.defender_king, '/') AS def_kings,
row.attacker_outcome AS att_outcome,
CASE WHEN row.attacker_outcome = 'win' THEN 'loss'
ELSE 'win'
END AS def_outcome
MATCH (b:Battle {name: row.name})
UNWIND att_commanders AS att_commander
MERGE (p:Person {name: trim(att_commander)})
MERGE (p)-[ac:ATTACKER_COMMANDER]->(b)
ON CREATE SET ac.outcome = att_outcome
// To end the unwind and correct cardinality(number of rows), use any aggregation function ( e.g. count(*)).
WITH b, def_commanders, def_kings, att_kings, att_outcome, def_outcome,
COUNT(*) AS c1
UNWIND def_commanders AS def_commander
MERGE (p:Person {name: trim(def_commander)})
MERGE (p)-[dc:DEFENDER_COMMANDER]->(b)
ON CREATE SET dc.outcome = def_outcome
// Reset cardinality with an aggregation function (end the unwind).
WITH b, def_kings, att_kings, att_outcome, def_outcome, COUNT(*) AS c2
UNWIND def_kings AS def_king
MERGE (p:Person {name: trim(def_king)})
MERGE (p)-[dk:DEFENDER_KING]->(b)
ON CREATE SET dk.outcome = def_outcome
// Reset cardinality with an aggregation function (end the unwind).
WITH b, att_kings, att_outcome, COUNT(*) AS c3
UNWIND att_kings AS att_king
MERGE (p:Person {name: trim(att_king)})
MERGE (p)-[ak:ATTACKER_KING]->(b)
ON CREATE SET ak.outcome = att_outcome;
LOAD CSV WITH HEADERS FROM
'https://s3.eu-north-1.amazonaws.com/com.neo4j.gds.browser-guide/data/character-deaths.csv'
AS row
WITH row,
CASE WHEN row.Nobility = '1' THEN 'Noble'
ELSE 'Commoner'
END AS status_value
// Remove House for better linking.
MERGE (house:House {name: replace(row.Allegiances, 'House ', '')})
MERGE (person:Person {name: row.Name})
SET person.gender = CASE WHEN row.Gender = '1' THEN 'male'
ELSE 'female'
END,
person.book_intro_chapter = row.`Book Intro Chapter`,
person.book_death_chapter = row.`Death Chapter`,
person.book_of_death = row.`Book of Death`,
person.death_year = toInteger(row.`Death Year`)
MERGE (person)-[:BELONGS_TO]->(house)
MERGE (status:Status {name: status_value})
MERGE (person)-[:HAS_STATUS]->(status)
// Use FOREACH to skip the null values.
FOREACH
(ignoreMe IN CASE WHEN row.GoT = '1' THEN [1]
ELSE []
END |
MERGE (book1:Book {sequence: 1})
ON CREATE SET book1.name = 'Game of thrones'
MERGE (person)-[:APPEARED_IN]->(book1)
)
FOREACH
(ignoreMe IN CASE WHEN row.CoK = '1' THEN [1]
ELSE []
END |
MERGE (book2:Book {sequence: 2})
ON CREATE SET book2.name = 'Clash of kings'
MERGE (person)-[:APPEARED_IN]->(book2)
)
FOREACH
(ignoreMe IN CASE WHEN row.SoS = '1' THEN [1]
ELSE []
END |
MERGE (book3:Book {sequence: 3})
ON CREATE SET book3.name = 'Storm of swords'
MERGE (person)-[:APPEARED_IN]->(book3)
)
FOREACH
(ignoreMe IN CASE WHEN row.FfC = '1' THEN [1]
ELSE []
END |
MERGE (book4:Book {sequence: 4})
ON CREATE SET book4.name = 'Feast for crows'
MERGE (person)-[:APPEARED_IN]->(book4)
)
FOREACH
(ignoreMe IN CASE WHEN row.DwD = '1' THEN [1]
ELSE []
END |
MERGE (book5:Book {sequence: 5})
ON CREATE SET book5.name = 'Dance with dragons'
MERGE (person)-[:APPEARED_IN]->(book5)
)
FOREACH
(ignoreMe IN CASE WHEN row.`Book of Death` IS NOT NULL THEN [1]
ELSE []
END |
MERGE (book:Book {sequence: toInteger(row.`Book of Death`)})
MERGE (person)-[:DIED_IN]->(book)
);
LOAD CSV WITH HEADERS FROM
'https://s3.eu-north-1.amazonaws.com/com.neo4j.gds.browser-guide/data/character-predictions.csv'
AS row
MERGE (p:Person {name: row.name})
// Set properties on the person node.
SET p.title = row.title,
p.death_year = toInteger(row.DateoFdeath),
p.birth_year = toInteger(row.dateOfBirth),
p.age = toInteger(row.age),
p.gender = CASE WHEN row.male = '1' THEN 'male'
ELSE 'female'
END
// Use FOREACH to skip the null values.
FOREACH
(ignoreMe IN CASE WHEN row.mother IS NOT NULL THEN [1]
ELSE []
END |
MERGE (mother:Person {name: row.mother})
MERGE (p)-[:RELATED_TO {name: 'mother'}]->(mother)
)
FOREACH
(ignoreMe IN CASE WHEN row.spouse IS NOT NULL THEN [1]
ELSE []
END |
MERGE (spouse:Person {name: row.spouse})
MERGE (p)-[:RELATED_TO {name: 'spouse'}]->(spouse)
)
FOREACH
(ignoreMe IN CASE WHEN row.father IS NOT NULL THEN [1]
ELSE []
END |
MERGE (father:Person {name: row.father})
MERGE (p)-[:RELATED_TO {name: 'father'}]->(father)
)
FOREACH
(ignoreMe IN CASE WHEN row.heir IS NOT NULL THEN [1]
ELSE []
END |
MERGE (heir:Person {name: row.heir})
MERGE (p)-[:RELATED_TO {name: 'heir'}]->(heir)
)
// Remove "House " from the value for better linking.
FOREACH
(ignoreMe IN CASE WHEN row.house IS NOT NULL THEN [1]
ELSE []
END |
MERGE (house:House {name: replace(row.house, 'House ', '')})
MERGE (p)-[:BELONGS_TO]->(house)
);
LOAD CSV WITH HEADERS FROM
'https://s3.eu-north-1.amazonaws.com/com.neo4j.gds.browser-guide/data/character-predictions.csv'
AS row
MERGE (p:Person {name: row.name})
// Use FOREACH to skip the null values. Lower row.culture for better linking.
FOREACH
(ignoreMe IN CASE WHEN row.culture IS NOT NULL THEN [1]
ELSE []
END |
MERGE (culture:Culture {name: toLower(row.culture)})
MERGE (p)-[:MEMBER_OF_CULTURE]->(culture)
)
FOREACH
(ignoreMe IN CASE WHEN row.book1 = '1' THEN [1]
ELSE []
END |
MERGE (book:Book {sequence: 1})
MERGE (p)-[:APPEARED_IN]->(book)
)
FOREACH
(ignoreMe IN CASE WHEN row.book2 = '1' THEN [1]
ELSE []
END |
MERGE (book:Book {sequence: 2})
MERGE (p)-[:APPEARED_IN]->(book)
)
FOREACH
(ignoreMe IN CASE WHEN row.book3 = '1' THEN [1]
ELSE []
END |
MERGE (book:Book {sequence: 3})
MERGE (p)-[:APPEARED_IN]->(book)
)
FOREACH
(ignoreMe IN CASE WHEN row.book4 = '1' THEN [1]
ELSE []
END |
MERGE (book:Book {sequence: 4})
MERGE (p)-[:APPEARED_IN]->(book)
)
FOREACH
(ignoreMe IN CASE WHEN row.book5 = '1' THEN [1]
ELSE []
END |
MERGE (book:Book {sequence: 5})
MERGE (p)-[:APPEARED_IN]->(book)
);
LOAD CSV WITH HEADERS FROM 'https://s3.eu-north-1.amazonaws.com/com.neo4j.gds.browser-guide/data/character-predictions.csv' AS row
WITH row,
CASE WHEN row.isAlive = '0' THEN [1]
ELSE []
END AS dead_person,
CASE WHEN row.isAliveMother = '0' THEN [1]
ELSE []
END AS dead_mother,
CASE WHEN row.isAliveFather = '0' THEN [1]
ELSE []
END AS dead_father,
CASE WHEN row.isAliveHeir = '0' THEN [1]
ELSE []
END AS dead_heir,
CASE WHEN row.isAliveSpouse = '0' THEN [1]
ELSE []
END AS dead_spouse
MATCH (p:Person {name: row.name})
// Use OPTIONAL MATCH (mother:Person {name: row.mother}) not to stop the query if the Person is not found.
OPTIONAL MATCH (mother:Person {name: row.mother})
OPTIONAL MATCH (father:Person {name: row.father})
OPTIONAL MATCH (heir:Person {name: row.heir})
OPTIONAL MATCH (spouse:Spouse {name: row.spouse})
// Set the label Dead to each dead person.
FOREACH (d IN dead_person |
SET p:Dead
)
FOREACH (d IN dead_mother |
SET mother:Dead
)
FOREACH (d IN dead_father |
SET father:Dead
)
FOREACH (d IN dead_heir |
SET heir:Dead
)
FOREACH (d IN dead_spouse |
SET spouse:Dead
);
MATCH (p:Person) where p.death_year is not null
SET p:Dead;
MATCH (p:Person)-[:DEFENDER_KING|ATTACKER_KING]-()
SET p:King;
MATCH (p:Person) where toLower(p.title) contains "king"
SET p:King;
MATCH (p:Person) where p.title = "Ser"
SET p:Knight;
// Map the names coming from the different data sources.
:param [map] => {
RETURN
{
`Aemon Targaryen (Maester Aemon)`: 'Aemon Targaryen (son of Maekar I)',
`Arstan`: 'Barristan Selmy',
`Garin (orphan)`: 'Garin (Orphan)',
`Hareth (Moles Town)`: "Hareth (Mole's Town)",
`Jaqen Hghar`: "Jaqen H'ghar",
`Lommy Greenhands`: 'Lommy',
`Rattleshirt`: 'Lord of Bones',
`Thoros of Myr`: 'Thoros'
} AS map
};
LOAD CSV WITH HEADERS FROM 'https://raw.githubusercontent.com/mathbeveridge/asoiaf/2d8ded13eda5128ace5e3b995253d69e62bc4bf6/data/asoiaf-book1-edges.csv' AS row
WITH replace(row.Source, '-', ' ') AS srcName,
replace(row.Target, '-', ' ') AS tgtName,
toInteger(row.weight) AS weight
MERGE (src:Person {name: coalesce($map[srcName], srcName)})
MERGE (tgt:Person {name: coalesce($map[tgtName], tgtName)})
MERGE (src)-[i:INTERACTS {book: 1}]->(tgt)
ON CREATE SET i.weight = weight
ON MATCH SET i.weight = i.weight + weight
MERGE (src)-[r:INTERACTS_1]->(tgt)
ON CREATE SET r.weight = weight, r.book = 1;
LOAD CSV WITH HEADERS FROM 'https://raw.githubusercontent.com/mathbeveridge/asoiaf/2d8ded13eda5128ace5e3b995253d69e62bc4bf6/data/asoiaf-book2-edges.csv' AS row
WITH replace(row.Source, '-', ' ') AS srcName,
replace(row.Target, '-', ' ') AS tgtName,
toInteger(row.weight) AS weight
MERGE (src:Person {name: coalesce($map[srcName], srcName)})
MERGE (tgt:Person {name: coalesce($map[tgtName], tgtName)})
MERGE (src)-[i:INTERACTS {book: 2}]->(tgt)
ON CREATE SET i.weight = weight
ON MATCH SET i.weight = i.weight + weight
MERGE (src)-[r:INTERACTS_2]->(tgt)
ON CREATE SET r.weight = weight, r.book = 2;
LOAD CSV WITH HEADERS FROM 'https://raw.githubusercontent.com/mathbeveridge/asoiaf/2d8ded13eda5128ace5e3b995253d69e62bc4bf6/data/asoiaf-book3-edges.csv' AS row
WITH replace(row.Source, '-', ' ') AS srcName,
replace(row.Target, '-', ' ') AS tgtName,
toInteger(row.weight) AS weight
MERGE (src:Person {name: coalesce($map[srcName], srcName)})
MERGE (tgt:Person {name: coalesce($map[tgtName], tgtName)})
MERGE (src)-[i:INTERACTS {book: 3}]->(tgt)
ON CREATE SET i.weight = weight
ON MATCH SET i.weight = i.weight + weight
MERGE (src)-[r:INTERACTS_3]->(tgt)
ON CREATE SET r.weight = weight, r.book = 3;
LOAD CSV WITH HEADERS FROM 'https://raw.githubusercontent.com/mathbeveridge/asoiaf/2d8ded13eda5128ace5e3b995253d69e62bc4bf6/data/asoiaf-book4-edges.csv' AS row
WITH replace(row.Source, '-', ' ') AS srcName,
replace(row.Target, '-', ' ') AS tgtName,
toInteger(row.weight) AS weight
MERGE (src:Person {name: coalesce($map[srcName], srcName)})
MERGE (tgt:Person {name: coalesce($map[tgtName], tgtName)})
MERGE (src)-[i:INTERACTS {book: 4}]->(tgt)
ON CREATE SET i.weight = weight
ON MATCH SET i.weight = i.weight + weight
MERGE (src)-[r:INTERACTS_4]->(tgt)
ON CREATE SET r.weight = weight, r.book = 4;
LOAD CSV WITH HEADERS FROM 'https://raw.githubusercontent.com/mathbeveridge/asoiaf/2d8ded13eda5128ace5e3b995253d69e62bc4bf6/data/asoiaf-book5-edges.csv' AS row
WITH replace(row.Source, '-', ' ') AS srcName,
replace(row.Target, '-', ' ') AS tgtName,
toInteger(row.weight) AS weight
MERGE (src:Person {name: coalesce($map[srcName], srcName)})
MERGE (tgt:Person {name: coalesce($map[tgtName], tgtName)})
MERGE (src)-[i:INTERACTS {book: 5}]->(tgt)
ON CREATE SET i.weight = weight
ON MATCH SET i.weight = i.weight + weight
MERGE (src)-[r:INTERACTS_5]->(tgt)
ON CREATE SET r.weight = weight, r.book = 5;<!--/code--></pre>
</div>
</div>
</div>
</div>
</slide>
<slide class="row-fluid">
<div class="col-sm-12">
<h3>Data visualization</h3>
<br/>
<div>
<div class="paragraph">
<p>Let’s briefly explore the dataset before running some algorithms.</p>
</div>
<div class="paragraph">
<p>Run the following query to visualize the schema of your graph:</p>
</div>
<div class="listingblock">
<div class="content">
<pre mode="cypher" class="highlight pre-scrollable programlisting cm-s-neo code runnable standalone-example ng-binding" data-lang="cypher" lang="cypher"><!--code class="cypher language-cypher"-->CALL db.schema.visualization()<!--/code--></pre>
</div>
</div>
<div class="paragraph">
<p>The <code>:Dead</code>, <code>:King</code>, and <code>:Knight</code> labels all appear on <code>:Person</code> nodes.
You may find it useful to remove them from the visualization to make it easier to inspect.</p>
</div>
</div>
</div>
</slide>
<slide class="row-fluid">
<div class="col-sm-12">
<h3>Summary statistics</h3>
<br/>
<div>
<div class="paragraph">
<p>Calculate some simple statistics to see how data is distributed.
For example, find the minimum, maximum, average, and standard deviation of the number of interactions per character:</p>
</div>
<div class="listingblock">
<div class="content">
<pre mode="cypher" class="highlight pre-scrollable programlisting cm-s-neo code runnable standalone-example ng-binding" data-lang="cypher" lang="cypher"><!--code class="cypher language-cypher"-->MATCH (c:Person)-[:INTERACTS]->()
WITH c, count(*) AS num
RETURN min(num) AS min, max(num) AS max, avg(num) AS avg_interactions, stdev(num) AS stdev<!--/code--></pre>
</div>
</div>
<div class="paragraph">
<p>Calculate the same grouped by book:</p>
</div>
<div class="listingblock">
<div class="content">
<pre mode="cypher" class="highlight pre-scrollable programlisting cm-s-neo code runnable standalone-example ng-binding" data-lang="cypher" lang="cypher"><!--code class="cypher language-cypher"-->MATCH (c:Person)-[r:INTERACTS]->()
WITH r.book AS book, c, count(*) AS num
RETURN book, min(num) AS min, max(num) AS max, avg(num) AS avg_interactions, stdev(num) AS stdev
ORDER BY book<!--/code--></pre>
</div>
</div>
</div>
</div>
</slide>
<slide class="row-fluid">
<div class="col-sm-12">
<h3>Estimate memory usage: why?</h3>
<br/>
<div>
<div class="paragraph">
<p>Now that you have data and know something about its shape, you need to estimate the memory usage of your graph and algorithm(s), and to configure your Neo4j Server with a much larger heap size than for a transactional deployment.
Why?</p>
</div>
<div class="paragraph">
<p>Because, the graph algorithms run on an in-memory, heap-allocated projection of the Neo4j graph, which resides outside the main database.
This means that before you execute an algorithm, you must create (explicitly or implicitly) a projection of your graph in memory.</p>
</div>
<div class="paragraph">
<p>However, creating graphs and running algorithms on them can have a significant memory footprint.</p>
</div>
<div class="paragraph">
<p>Therefore, a good habit is always to estimate the amount of RAM you need and configure a large heap size before running a heavy memory workload.</p>
</div>
<div class="paragraph">
<p>In the following three chapters, you will be able to exercise memory estimation and explore its results.</p>
</div>
</div>
</div>
</slide>
<slide class="row-fluid">
<div class="col-sm-12">
<h3>Memory estimation: graphs</h3>
<br/>
<div>
<div class="paragraph">
<p>The GDS library offers a set of procedures that can help you estimate the memory needed to create a graph and run algorithms.</p>
</div>
<div class="paragraph">
<p>To estimate the required memory for a subset of your graph, for example, the <code>Person</code> nodes and <code>INTERACTS</code> relationships, call the following procedure.</p>
</div>
<div class="listingblock">
<div class="content">
<pre mode="cypher" class="highlight pre-scrollable programlisting cm-s-neo code runnable standalone-example ng-binding" data-lang="cypher" lang="cypher"><!--code class="cypher language-cypher"-->CALL gds.graph.project.estimate('Person', 'INTERACTS') YIELD nodeCount, relationshipCount, requiredMemory<!--/code--></pre>
</div>
</div>
<div class="paragraph">
<p>The result shows that the example graph is small.
So, you can create your projected graph and name it, for example, <code>got-interactions</code>.</p>
</div>
<div class="listingblock">
<div class="content">
<pre mode="cypher" class="highlight pre-scrollable programlisting cm-s-neo code runnable standalone-example ng-binding" data-lang="cypher" lang="cypher"><!--code class="cypher language-cypher"-->CALL gds.graph.project('got-interactions', 'Person', 'INTERACTS')<!--/code--></pre>
</div>
</div>
</div>
</div>
</slide>
<slide class="row-fluid">
<div class="col-sm-12">
<h3>Estimate memory usage: algorithms</h3>
<br/>
<div>
<div class="paragraph">
<p>To estimate the memory needed to execute an algorithm on your <code>got-interactions</code> graph, for example, Page Rank, call the following procedure.</p>
</div>
<div class="listingblock">
<div class="content">
<pre mode="cypher" class="highlight pre-scrollable programlisting cm-s-neo code runnable standalone-example ng-binding" data-lang="cypher" lang="cypher"><!--code class="cypher language-cypher"-->CALL gds.pageRank.stream.estimate('got-interactions', {}) YIELD requiredMemory<!--/code--></pre>
</div>
</div>
<div class="paragraph">
<p>This estimation considers only the algorithm execution, as the graph is already in-memory.</p>
</div>
</div>
</div>
</slide>
<slide class="row-fluid">
<div class="col-sm-12">
<h3>Estimate memory usage: details</h3>
<br/>
<div>
<div class="paragraph">
<p>If you want to look at the full details of the memory estimation, remove the <code>YIELD</code> clause.
The procedure returns a tree view and a map view of all the "components" with their memory estimates.</p>
</div>
<div class="listingblock">
<div class="content">
<pre mode="cypher" class="highlight pre-scrollable programlisting cm-s-neo code runnable standalone-example ng-binding" data-lang="cypher" lang="cypher"><!--code class="cypher language-cypher"-->CALL gds.pageRank.stream.estimate('got-interactions', {})<!--/code--></pre>
</div>
</div>
<div class="paragraph">
<p>As you see, the more detailed views contain estimates on the individual compute steps and the result data structures.</p>
</div>
<div class="paragraph">
<p>Now, you can filter the result to the top level components: graph and algorithm.</p>
</div>
<div class="listingblock">
<div class="content">
<pre mode="cypher" class="highlight pre-scrollable programlisting cm-s-neo code runnable standalone-example ng-binding" data-lang="cypher" lang="cypher"><!--code class="cypher language-cypher"-->CALL gds.pageRank.stream.estimate('got-interactions',{}) YIELD mapView
UNWIND [ x IN mapView.components | [x.name, x.memoryUsage] ] AS component
RETURN component[0] AS name, component[1] AS size<!--/code--></pre>
</div>
</div>
<div class="paragraph">
<p>For more details, see <em><a href="https://neo4j.com/docs/graph-data-science/current/common-usage/memory-estimation/" target="_blank">the Memory Estimation section in the GDS Manual</a></em>.</p>
</div>
</div>
</div>
</slide>
<slide class="row-fluid">
<div class="col-sm-12">
<h3>Memory estimation: cleanup</h3>
<br/>
<div>
<div class="paragraph">
<p>If you do not want to use the projected graph anymore, a good practice is to release it from the memory.</p>
</div>
<div class="listingblock">
<div class="content">
<pre mode="cypher" class="highlight pre-scrollable programlisting cm-s-neo code runnable standalone-example ng-binding" data-lang="cypher" lang="cypher"><!--code class="cypher language-cypher"-->CALL gds.graph.drop('got-interactions');<!--/code--></pre>
</div>
</div>
</div>
</div>
</slide>
<slide class="row-fluid">
<div class="col-sm-12">
<h3>Graph creation</h3>
<br/>
<div>
<div class="paragraph">
<p>The first stage of execution in GDS is always graph creation, but what does this mean?</p>
</div>
<div class="paragraph">
<p>To enable fast caching of the graph topology, containing only the relevant nodes, relationships, and weights, the GDS library operates on in-memory graphs that are created as projections of the Neo4j stored graph.</p>
</div>
<div class="paragraph">
<p>These projections may change the nature of the graph elements by any of the following:</p>
</div>
<div class="ulist">
<ul>
<li>
<p>Subgraphing</p>
</li>
<li>
<p>Renaming relationship types or node labels</p>
</li>
<li>
<p>Merging several relationship types or node labels</p>
</li>
<li>
<p>Altering relationship direction</p>
</li>
<li>
<p>Aggregating parallel relationships and their properties</p>
</li>
<li>
<p>Deriving relationships from larger patterns</p>
</li>
</ul>
</div>
<div class="paragraph">
<p>There are two ways of creating graphs – <em>explicit</em> and <em>implicit</em>.</p>
</div>
</div>
</div>
</slide>
<slide class="row-fluid">
<div class="col-sm-12">
<h3>Graph catalog</h3>
<br/>
<div>
<div class="paragraph">
<p>The typical workflow is to create the projected graph <em>explicitly</em> by giving it a name and storing it in the <em>graph catalog</em>.
This allows you to operate on the graph multiple times.</p>
</div>
<div class="paragraph">
<p>In the <em>Memory estimation</em> chapters, you calculated the memory needed for creating a small graph of interactions, called <code>got-interactions</code>.
If you have removed it from the memory, you can create it again.
Because each <code>INTERACTS</code> relationship is symmetric, you can even ignore its direction by creating your graph with an <code>UNDIRECTED</code> orientation.</p>
</div>
<div class="listingblock">
<div class="content">
<pre mode="cypher" class="highlight pre-scrollable programlisting cm-s-neo code runnable standalone-example ng-binding" data-lang="cypher" lang="cypher"><!--code class="cypher language-cypher"-->CALL gds.graph.project('got-interactions', 'Person', {
INTERACTS: {
orientation: 'UNDIRECTED'
}
})<!--/code--></pre>
</div>
</div>
</div>
</div>
</slide>
<slide class="row-fluid">
<div class="col-sm-12">
<h3>Graph catalog: standard creation and Cypher projection</h3>
<br/>
<div>
<div class="paragraph">
<p>The GDS library supports two approaches for loading projected graphs - <strong>standard creation</strong> (<code>gds.graph.project()</code>) and <strong>Cypher projection</strong> (<code>gds.graph.project.cypher()</code>).</p>
</div>
<div class="paragraph">
<p>In the <strong>standard creation</strong> approach, which you used to create your graph, you specify node labels and relationship types and project them onto the in-memory graph as labels and relationship types with new names.
You can further specify properties for each node label and relationship type.
For some use cases, this approach might be sufficient.
However, it is not possible to take only some nodes with a given label or only some relationships of a given type.
One way to work around it is by adding additional labels that define the desired subset of nodes that you want to project.</p>
</div>
<div class="paragraph">
<p>In the <strong>Cypher projection</strong> approach, you use Cypher queries to project nodes and relationships onto the in-memory graph.
Instead of specifying labels and relationship types, you define node-statements and relationship-statements.
In this way, you can leverage the expressivity of the Cypher language and describe your graph in a more sophisticated way.</p>
</div>
<div class="paragraph">
<p>It is important to note that the standard creation is orders of magnitude faster than the Cypher projection.
When designing a use case with Cypher projection at a production scale, make sure to measure the performance in advance.</p>
</div>
<div class="paragraph">
<p>Now, let’s try the Cypher projection and load the same graph with a new name, for example, <code>got-interactions-cypher</code>.</p>
</div>
</div>
</div>
</slide>
<slide class="row-fluid">
<div class="col-sm-12">
<h3>Graph catalog: Cypher projection</h3>
<br/>
<div>
<div class="paragraph">
<p>You specify two queries: one for the nodes and one for the relationships.
You need to return <code>id</code>, <code>source</code>, and <code>target</code> columns and can optionally return label, relationship type and property columns.</p>
</div>
<div class="listingblock">
<div class="content">
<pre mode="cypher" class="highlight pre-scrollable programlisting cm-s-neo code runnable standalone-example ng-binding" data-lang="cypher" lang="cypher"><!--code class="cypher language-cypher"-->CALL gds.graph.project.cypher(
'got-interactions-cypher',
'MATCH (n:Person) RETURN id(n) AS id',
'MATCH (s:Person)-[i:INTERACTS]->(t:Person) RETURN id(s) AS source, id(t) AS target, i.weight AS weight'
)<!--/code--></pre>
</div>
</div>
<div class="paragraph">
<p>The first query returns the node IDs; the second one returns the source and target IDs of the relationships, as well as one relationship property <code>weight</code>.
Here, you can use any pair of Cypher queries as long as they return the expected columns and field types.<br>
To aggregate relationships, standard Cypher features can be used, such as <code>DISTINCT</code>.
You can find more details about relationship aggregations <em><a href="https://neo4j.com/docs/graph-data-science/current/management-ops/cypher-projection/#cypher-projection-relationship-aggregation" target="_blank">here</a></em>.</p>
</div>
</div>
</div>
</slide>
<slide class="row-fluid">
<div class="col-sm-12">
<h3>Graph catalog: Cypher projection of virtual relationships</h3>
<br/>
<div>
<div class="paragraph">
<p>Another interesting feature of the Cypher graph projection is that it allows you to represent complex patterns by computing relationships that do not exist in the Neo4j stored graph.
This is especially useful when the algorithm you want to run supports only mono-partite graphs.<br>
For example, you can use the following query to create a graph with <code>Person</code> nodes connected with an (untyped) relationship if they belong to the same house.
The projected relationship does not exist in the stored graph.</p>
</div>
<div class="listingblock">
<div class="content">
<pre mode="cypher" class="highlight pre-scrollable programlisting cm-s-neo code runnable standalone-example ng-binding" data-lang="cypher" lang="cypher"><!--code class="cypher language-cypher"-->CALL gds.graph.project.cypher(
'same-house-graph',
'MATCH (n:Person) RETURN id(n) AS id',
'MATCH (p1:Person)-[:BELONGS_TO]-(:House)-[:BELONGS_TO]-(p2:Person) RETURN id(p1) AS source, id(p2) AS target'
)<!--/code--></pre>
</div>
</div>
</div>
</div>
</slide>
<slide class="row-fluid">
<div class="col-sm-12">
<h3>Graph catalog: listing</h3>
<br/>
<div>
<div class="paragraph">
<p>After you create your projected graph, you can try several useful queries to manage it.</p>
</div>
<div class="paragraph">
<p>You can list all information about it by using following procedure:</p>
</div>
<div class="listingblock">
<div class="content">
<pre mode="cypher" class="highlight pre-scrollable programlisting cm-s-neo code runnable standalone-example ng-binding" data-lang="cypher" lang="cypher"><!--code class="cypher language-cypher"-->CALL gds.graph.list('got-interactions-cypher')<!--/code--></pre>
</div>
</div>
<div class="paragraph">
<p>You can list the graphs you have loaded so far by using following procedure:</p>
</div>
<div class="listingblock">
<div class="content">
<pre mode="cypher" class="highlight pre-scrollable programlisting cm-s-neo code runnable standalone-example ng-binding" data-lang="cypher" lang="cypher"><!--code class="cypher language-cypher"-->CALL gds.graph.list()<!--/code--></pre>
</div>
</div>
</div>
</div>
</slide>
<slide class="row-fluid">
<div class="col-sm-12">
<h3>Graph catalog: existence</h3>
<br/>
<div>
<div class="paragraph">