-
Notifications
You must be signed in to change notification settings - Fork 211
/
Copy pathDataFrameSamples.cs
1938 lines (1638 loc) · 81.4 KB
/
DataFrameSamples.cs
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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.Spark.CSharp.Core;
using Microsoft.Spark.CSharp.Proxy;
using Microsoft.Spark.CSharp.Sql;
using NUnit.Framework;
namespace Microsoft.Spark.CSharp.Samples
{
class DataFrameSamples
{
internal const string PeopleJson = @"people.json";
internal const string OrderJson = @"order.json";
internal const string RequestsLog = @"requestslog.txt";
internal const string MetricsLog = @"metricslog.txt";
internal const string CSVTestLog = @"csvtestlog.txt";
private static SqlContext sqlContext;
private static SqlContext GetSqlContext()
{
return sqlContext ?? (sqlContext = new SqlContext(SparkCLRSamples.SparkContext));
}
/// <summary>
/// Sample to show schema of DataFrame
/// </summary>
[Sample]
internal static void DFShowSchemaSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
peopleDataFrame.Explain(true);
peopleDataFrame.ShowSchema();
}
/// <summary>
/// Sample to get schema of DataFrame in json format
/// </summary>
[Sample]
internal static void DFGetSchemaJsonSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
string json = peopleDataFrame.Schema.Json;
Console.WriteLine("schema in json format: {0}", json);
}
/// <summary>
/// Sample to run collect for DataFrame
/// </summary>
[Sample]
internal static void DFCollectSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var rows = peopleDataFrame.Collect().ToArray();
Console.WriteLine("peopleDataFrame:");
int i = 0;
foreach (var row in rows)
{
if (i == 0)
{
Console.WriteLine("schema: {0}", row.GetSchema());
}
// output the whole row as a string
Console.WriteLine(row);
// output each field of the row, including fields in subrow
string id = row.GetAs<string>("id");
string name = row.GetAs<string>("name");
int age = row.GetAs<int>("age");
Console.Write("id: {0}, name: {1}, age: {2}", id, name, age);
Row address = row.GetAs<Row>("address");
if (address != null)
{
string city = address.GetAs<string>("city");
string state = address.GetAs<string>("state");
Console.WriteLine(", state: {0}, city: {1}", state, city);
}
else
{
Console.WriteLine();
}
i++;
}
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.AreEqual(4, rows.Length);
}
}
/// <summary>
/// Sample to register a DataFrame as temptable and run queries
/// </summary>
[Sample]
internal static void DFRegisterTableSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
peopleDataFrame.RegisterTempTable("people");
var nameFilteredDataFrame = GetSqlContext().Sql("SELECT name, address.city, address.state FROM people where name='Bill'");
var countDataFrame = GetSqlContext().Sql("SELECT count(name) FROM people where name='Bill'");
var maxAgeDataFrame = GetSqlContext().Sql("SELECT max(age) FROM people where name='Bill'");
long maxAgeDataFrameRowsCount = maxAgeDataFrame.Count();
long nameFilteredDataFrameRowsCount = nameFilteredDataFrame.Count();
long countDataFrameRowsCount = countDataFrame.Count();
Console.WriteLine("nameFilteredDataFrameRowsCount={0}, maxAgeDataFrameRowsCount={1}, countDataFrameRowsCount={2}", nameFilteredDataFrameRowsCount, maxAgeDataFrameRowsCount, countDataFrameRowsCount);
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.AreEqual(1, maxAgeDataFrameRowsCount);
Assert.AreEqual(2, nameFilteredDataFrameRowsCount);
Assert.AreEqual(1, countDataFrameRowsCount);
}
}
/// <summary>
/// Sample to load a text file as dataframe
/// </summary>
[Sample]
internal static void DFTextFileLoadDataFrameSample()
{
var requestsSchema = new StructType(new List<StructField>
{
new StructField("guid", new StringType(), false),
new StructField("datacenter", new StringType(), false),
new StructField("abtestid", new StringType(), false),
new StructField("traffictype", new StringType(), false),
});
var requestsDateFrame = GetSqlContext().TextFile(SparkCLRSamples.Configuration.GetInputDataPath(RequestsLog), requestsSchema);
requestsDateFrame.RegisterTempTable("requests");
var guidFilteredDataFrame = GetSqlContext().Sql("SELECT guid, datacenter FROM requests where guid = '4628deca-139d-4121-b540-8341b9c05c2a'");
guidFilteredDataFrame.Show();
requestsDateFrame.ShowSchema();
requestsDateFrame.Show();
var count = requestsDateFrame.Count();
guidFilteredDataFrame.ShowSchema();
guidFilteredDataFrame.Show();
var filteredCount = guidFilteredDataFrame.Count();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.AreEqual(10, count);
Assert.AreEqual(1, filteredCount);
}
}
/// <summary>
/// Sample to load two text files and join them using temptable constructs
/// </summary>
[Sample]
internal static void DFTextFileJoinTempTableSample()
{
var requestsDataFrame = GetSqlContext().TextFile(SparkCLRSamples.Configuration.GetInputDataPath(RequestsLog));
requestsDataFrame.ShowSchema();
var metricsDateFrame = GetSqlContext().TextFile(SparkCLRSamples.Configuration.GetInputDataPath(MetricsLog));
metricsDateFrame.ShowSchema();
requestsDataFrame.RegisterTempTable("requests");
metricsDateFrame.RegisterTempTable("metrics");
//C0 - guid in requests DF, C3 - guid in metrics DF
var join = GetSqlContext().Sql(
"SELECT joinedtable.datacenter, max(joinedtable.latency) maxlatency, avg(joinedtable.latency) avglatency " +
"FROM (SELECT a._c1 as datacenter, b._c6 as latency from requests a JOIN metrics b ON a._c0 = b._c3) joinedtable " +
"GROUP BY datacenter");
join.ShowSchema();
join.Show();
var count = join.Count();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.AreEqual(4, count);
}
}
/// <summary>
/// Sample to load two text files and join them using DataFrame DSL
/// </summary>
[Sample]
internal static void DFTextFileJoinTableDSLSample()
{
//C0 - guid, C1 - datacenter
var requestsDataFrame = GetSqlContext().TextFile(SparkCLRSamples.Configuration.GetInputDataPath(RequestsLog)).Select("_c0", "_c1");
//C3 - guid, C6 - latency
var metricsDateFrame = GetSqlContext().TextFile(SparkCLRSamples.Configuration.GetInputDataPath(MetricsLog), ",", false, true).Select("_c3", "_c6"); //override delimiter, hasHeader & inferSchema
var joinDataFrame = requestsDataFrame.Join(metricsDateFrame, requestsDataFrame["_c0"] == metricsDateFrame["_c3"]).GroupBy("_c1");
var maxLatencyByDcDataFrame = joinDataFrame.Agg(new Dictionary<string, string> { { "_c6", "max" } });
var avgLatencyByDcDataFrame = joinDataFrame.Agg(new Dictionary<string, string> { { "_c6", "avg" } });
maxLatencyByDcDataFrame.ShowSchema();
maxLatencyByDcDataFrame.Show();
avgLatencyByDcDataFrame.ShowSchema();
avgLatencyByDcDataFrame.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
CollectionAssert.AreEquivalent(new[] { "_c1", "max(_c6)" }, maxLatencyByDcDataFrame.Schema.Fields.Select(f => f.Name).ToArray());
CollectionAssert.AreEquivalent(new[] { "iowa", "texas", "singapore", "ireland" }, maxLatencyByDcDataFrame.Collect().Select(row => row.Get("_c1")).ToArray());
CollectionAssert.AreEquivalent(new[] { "_c1", "avg(_c6)" }, avgLatencyByDcDataFrame.Schema.Fields.Select(f => f.Name).ToArray());
CollectionAssert.AreEquivalent(new[] { "iowa", "texas", "singapore", "ireland" }, avgLatencyByDcDataFrame.Collect().Select(row => row.Get("_c1")).ToArray());
}
}
/// <summary>
/// Sample to iterate on the schema of DataFrame
/// </summary>
[Sample]
internal static void DFSchemaSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var peopleDataFrameSchema = peopleDataFrame.Schema;
var peopleDataFrameSchemaFields = peopleDataFrameSchema.Fields;
foreach (var peopleDataFrameSchemaField in peopleDataFrameSchemaFields)
{
var name = peopleDataFrameSchemaField.Name;
var dataType = peopleDataFrameSchemaField.DataType;
var stringVal = dataType.TypeName;
var simpleStringVal = dataType.SimpleString;
var isNullable = peopleDataFrameSchemaField.IsNullable;
Console.WriteLine("Name={0}, DT.string={1}, DT.simplestring={2}, DT.isNullable={3}", name, stringVal, simpleStringVal, isNullable);
}
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.AreEqual("address:struct<city:string,state:string>", peopleDataFrameSchemaFields[0].SimpleString);
Assert.AreEqual("age:long", peopleDataFrameSchemaFields[1].SimpleString);
Assert.AreEqual("id:string", peopleDataFrameSchemaFields[2].SimpleString);
Assert.AreEqual("name:string", peopleDataFrameSchemaFields[3].SimpleString);
}
}
/// <summary>
/// Sample to convert DataFrames to RDD
/// </summary>
[Sample]
internal static void DFConversionSample()
{
// repartitioning below so that batching in pickling does not impact count on Rdd created from the dataframe
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson)).Repartition(4);
var stringRddCreatedFromDataFrame = peopleDataFrame.ToJSON();
var stringRddCreatedFromDataFrameRowCount = stringRddCreatedFromDataFrame.Count();
var byteArrayRddCreatedFromDataFrame = peopleDataFrame.ToRDD();
var byteArrayRddCreatedFromDataFrameRowCount = byteArrayRddCreatedFromDataFrame.Count();
Console.WriteLine("stringRddCreatedFromDataFrameRowCount={0}, byteArrayRddCreatedFromDataFrameRowCount={1}", stringRddCreatedFromDataFrameRowCount, byteArrayRddCreatedFromDataFrameRowCount);
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.AreEqual(4, stringRddCreatedFromDataFrameRowCount);
Assert.AreEqual(4, byteArrayRddCreatedFromDataFrameRowCount);
}
}
/// <summary>
/// Sample to perform simple select and filter on DataFrame using DSL
/// </summary>
[Sample]
internal static void DFProjectionFilterDSLSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var projectedFilteredDataFrame = peopleDataFrame.Select("name", "address.state")
.Where("name = 'Bill' or state = 'California'");
projectedFilteredDataFrame.ShowSchema();
projectedFilteredDataFrame.Show();
var projectedFilteredDataFrameCount = projectedFilteredDataFrame.Count();
projectedFilteredDataFrame.RegisterTempTable("selectedcolumns");
var sqlCountDataFrame = GetSqlContext().Sql("SELECT count(name) FROM selectedcolumns where name='Bill'");
var sqlCountDataFrameRowCount = sqlCountDataFrame.Count();
Console.WriteLine("projectedFilteredDataFrameCount={0}, sqlCountDataFrameRowCount={1}", projectedFilteredDataFrameCount, sqlCountDataFrameRowCount);
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
CollectionAssert.AreEqual(new[] { "name", "state" }, projectedFilteredDataFrame.Schema.Fields.Select(f => f.Name).ToArray());
Assert.IsTrue(projectedFilteredDataFrame.Collect().All(row => row.Get("name") == "Bill" || row.Get("state") == "California"));
Assert.AreEqual(2, sqlCountDataFrame.Collect().ToArray()[0].Get(0));
}
}
/// <summary>
/// Sample to join DataFrames using DSL
/// </summary>
[Sample]
internal static void DFJoinSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var orderDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(OrderJson));
var expressionJoin = peopleDataFrame.Join(orderDataFrame, peopleDataFrame["id"] == orderDataFrame["personid"]);
expressionJoin.ShowSchema();
expressionJoin.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var collected = expressionJoin.Collect().ToArray();
Assert.AreEqual(2, collected.Length);
Assert.IsTrue(collected.Any(row => "123" == row.Get("id")));
Assert.IsTrue(collected.Any(row => "456" == row.Get("id")));
}
}
/// <summary>
/// Sample to join DataFrames using DSL
/// </summary>
[Sample]
internal static void DFJoinMultiColSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var multiColumnJoin = peopleDataFrame.Join(peopleDataFrame, new string[] { "name", "id" });
multiColumnJoin.ShowSchema();
multiColumnJoin.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var schema = multiColumnJoin.Schema;
CollectionAssert.AreEquivalent(new[] { "name", "id", "age", "address", "age", "address" }, schema.Fields.Select(f => f.Name.ToLower()).ToArray());
}
}
/// <summary>
/// Sample to intersect DataFrames using DSL.
/// </summary>
[Sample]
internal static void DFIntersectSample()
{
var peopleDataFrame1 = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var peopleDataFrame2 = peopleDataFrame1.Filter("name = 'Bill'");
var intersected = peopleDataFrame1.Intersect(peopleDataFrame2);
intersected.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
// intersected should have the same items as peopleDataFrame2
AreRowListEquivalent(peopleDataFrame2.Rdd.Collect().ToList(), intersected.Rdd.Collect().ToList());
}
}
/// <summary>
/// Sample to unionAll DataFrames using DSL.
/// </summary>
[Sample]
internal static void DFUnionAllSample()
{
var peopleDataFrame1 = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var peopleDataFrame2 = peopleDataFrame1.Filter("name = 'Bill'");
var unioned = peopleDataFrame1.UnionAll(peopleDataFrame2);
unioned.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
// unioned should have the same items as peopleDataFrame1
AreRowListEquivalent(peopleDataFrame1.Rdd.Collect().ToList(), unioned.Rdd.Collect().ToList());
}
}
/// <summary>
/// Sample to subtract a DataFrame from another DataFrame using DSL.
/// </summary>
[Sample]
internal static void DFSubtractSample()
{
var peopleDataFrame1 = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var peopleDataFrame2 = peopleDataFrame1.Filter("name = 'Bill'");
var subtracted = peopleDataFrame1.Subtract(peopleDataFrame2);
subtracted.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
// subtracted should have items peopleDataFrame1 have but peopleDataFrame2 not have
AreRowListEquivalent(peopleDataFrame1.Rdd.Collect().Where(row => row.Get("name") != "Bill").ToList(), subtracted.Rdd.Collect().ToList());
}
}
/// <summary>
/// Sample to drop a column from DataFrame using DSL.
/// </summary>
[Sample]
internal static void DFDropSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var dropped = peopleDataFrame.Drop("name");
dropped.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
CollectionAssert.AreEquivalent(new[] { "id", "age", "address" }, dropped.Schema.Fields.Select(f => f.Name).ToArray());
}
}
/// <summary>
/// Sample to drop a DataFrame with omitting rows with null values using DSL.
/// </summary>
[Sample]
internal static void DFDropNaSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var dropped = peopleDataFrame.DropNa(thresh: 2, subset: new[] { "name", "address" });
dropped.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var expected = peopleDataFrame.Collect().Where(row => row.Get("name") != null && row.Get("address") != null).ToList();
Assert.IsTrue(AreRowListEquivalent(expected, dropped.Collect().ToList()));
}
}
/// <summary>
/// Sample to fill value to Na fields of a dataframe.
/// </summary>
[Sample]
internal static void DFFillNaSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var count = peopleDataFrame.Count();
Console.WriteLine("Records in people dataframe: {0}", count);
peopleDataFrame = peopleDataFrame.WithColumn("mail", Functions.Lit(null).Cast("string"))
.WithColumn("height", Functions.Lit(null).Cast("int"));
const string unknownMail = "unknown mail";
var filledMailDataFrame = peopleDataFrame.FillNa(unknownMail, new[] { "mail" });
Console.WriteLine("Filled null [mail] field with '{0}'", unknownMail);
filledMailDataFrame.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var expected = filledMailDataFrame.Collect().Where(row => (string)row.Get("mail") == unknownMail).Select(row => row.Get("mail")).Count();
Assert.AreEqual(count, expected);
}
const int unknownHeight = -1;
var filledHeightDataFrame = peopleDataFrame.FillNa(unknownHeight, new[] { "height" });
Console.WriteLine("Filled null [mail] and [height] fields with '{0}'", unknownHeight);
filledHeightDataFrame.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var expected = filledHeightDataFrame.Collect().Where(row => (int)row.Get("height") == unknownHeight)
.Select(row => row.Get("height")).Count();
Assert.AreEqual(count, expected);
}
}
/// <summary>
/// Sample to fill value to Na fields of a dataframe using dict
/// </summary>
[Sample]
internal static void DFFillNaSampleWithDict()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var count = peopleDataFrame.Count();
Console.WriteLine("Records in people dataframe: {0}", count);
peopleDataFrame = peopleDataFrame.WithColumn("mail", Functions.Lit(null).Cast("string"))
.WithColumn("height", Functions.Lit(null).Cast("int"));
const string unknownMail = "unknown mail";
const int unknownHeight = -1;
var filledDataFrame = peopleDataFrame.FillNa(new Dictionary<string, object>() { { "mail", unknownMail }, { "height", unknownHeight } });
Console.WriteLine("Filled null [mail] and [height] fields with '{0}' and '{1}'", unknownMail, unknownHeight);
filledDataFrame.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var expected = filledDataFrame.Collect().Count(row => (int)row.Get("height") == unknownHeight && (string)row.Get("mail") == unknownMail);
Assert.AreEqual(count, expected);
}
}
/// <summary>
/// Sample to drop rows containing any null values.
/// </summary>
[Sample]
internal static void DFNaDropSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var dfCount = peopleDataFrame.Count();
Console.WriteLine("Before drop operation, # of rows: {0}", dfCount);
peopleDataFrame.Show();
var peopleDataFrameWithoutNull = peopleDataFrame.Na().Drop();
var dfCount2 = peopleDataFrameWithoutNull.Count();
Console.WriteLine("After drop operation, # of rows: {0}", dfCount2);
peopleDataFrameWithoutNull.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.IsTrue(dfCount > dfCount2);
}
}
/// <summary>
/// Sample to fill rows containing null values.
/// </summary>
[Sample]
internal static void DFNaFillSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson))
.WithColumn("mail", Functions.Lit(null).Cast("string"));
Console.WriteLine("Before fill operation:");
peopleDataFrame.Show();
var filledDataFrame = peopleDataFrame.Na().Fill("unknown mail");
Console.WriteLine("After fill operation:");
filledDataFrame.Show();
}
/// <summary>
/// Sample to replace rows containing null values.
/// </summary>
[Sample]
internal static void DFNaReplaceSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
Console.WriteLine("Before replace operation:");
peopleDataFrame.Show();
var replacement = new Dictionary<string, string>()
{
{"Bill", "BILL"},
{"123", "I II III"}
};
var filledDataFrame = peopleDataFrame.Na().Replace(new[] { "name", "id" }, replacement);
Console.WriteLine("After replace operation:");
filledDataFrame.Show();
}
/// <summary>
/// Sample to drop a duplicated rows in a DataFrame.
/// </summary>
[Sample]
internal static void DFDropDuplicatesSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var dropped = peopleDataFrame.DropDuplicates(new[] { "name" });
dropped.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.AreEqual(1, dropped.Collect().Count(row => row.Get("name") == "Bill"));
}
}
/// <summary>
/// Sample to replace a value in a DataFrame.
/// </summary>
[Sample]
internal static void DFReplaceSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var singleValueReplaced = peopleDataFrame.Replace("Bill", "Bill.G");
singleValueReplaced.Show();
var multiValueReplaced = peopleDataFrame.ReplaceAll(new List<int> { 14, 34 }, new List<int> { 44, 54 });
multiValueReplaced.Show();
var multiValueReplaced2 = peopleDataFrame.ReplaceAll(new List<string> { "Bill", "Steve" }, "former CEO");
multiValueReplaced2.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.IsTrue(AreRowListEquivalent(peopleDataFrame.Collect().ToList(), singleValueReplaced.Collect().ToList(),
new Dictionary<string, Func<object, object, bool>>
{
{"name", (x, y) => x.ToString() == "Bill" ?
y.ToString() == "Bill.G" : x.ToString() == y.ToString()}
}));
Assert.IsTrue(AreRowListEquivalent(peopleDataFrame.Collect().ToList(), multiValueReplaced.Collect().ToList(),
new Dictionary<string, Func<object, object, bool>>
{
{"age", (x, y) =>
{
if ((int)x == 14) return (int)y == 44;
if ((int)x == 34) return (int)y == 54;
return (int)x == (int)y;
}
}
}));
Assert.IsTrue(AreRowListEquivalent(peopleDataFrame.Collect().ToList(), multiValueReplaced2.Collect().ToList(),
new Dictionary<string, Func<object, object, bool>>
{
{"name", (x, y) => x.ToString() == "Bill" || x.ToString() == "Steve"?
y.ToString() == "former CEO" : x.ToString() == y.ToString()}
}));
}
}
/// <summary>
/// Sample to perform randomSplit on DataFrame
/// </summary>
[Sample]
internal static void DFRandomSplitSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var randomSplitted = peopleDataFrame.RandomSplit(new[] { 1.0, 2.0 }).ToArray();
randomSplitted[0].Show();
randomSplitted[1].Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.AreEqual(peopleDataFrame.Count(), randomSplitted[0].Count() + randomSplitted[1].Count());
}
}
/// <summary>
/// Sample to perform Columns on DataFrame
/// </summary>
[Sample]
internal static void DFColumnsSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var columnNames = peopleDataFrame.Columns().ToArray();
Console.WriteLine("Columns:");
Console.WriteLine(string.Join(", ", columnNames));
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.AreEqual(4, columnNames.Length);
Assert.IsTrue(columnNames.Contains("id"));
Assert.IsTrue(columnNames.Contains("name"));
Assert.IsTrue(columnNames.Contains("age"));
Assert.IsTrue(columnNames.Contains("address"));
}
}
/// <summary>
/// Sample to perform DTypes on DataFrame
/// </summary>
[Sample]
internal static void DFDTypesSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var columnsNameAndType = peopleDataFrame.DTypes().ToArray();
Console.WriteLine("Columns name and type:");
Console.WriteLine(string.Join(", ", columnsNameAndType.Select(c => string.Format("{0}: {1}", c.Item1, c.Item2))));
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.AreEqual(4, columnsNameAndType.Length);
Assert.IsTrue(columnsNameAndType.Any(c => c.Item1 == "id" && c.Item2 == "string"));
Assert.IsTrue(columnsNameAndType.Any(c => c.Item1 == "name" && c.Item2 == "string"));
Assert.IsTrue(columnsNameAndType.Any(c => c.Item1 == "age" && c.Item2 == "bigint"));
Assert.IsTrue(columnsNameAndType.Any(c => c.Item1 == "address" && c.Item2 == "struct<city:string,state:string>"));
}
}
/// <summary>
/// Sample to perform Sort on DataFrame
/// </summary>
[Sample]
internal static void DFSortSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var sorted = peopleDataFrame.Sort(new string[] { "name", "age" }, new bool[] { true, false });
sorted.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var sortedDF = sorted.Collect().ToArray();
Assert.AreEqual("789", sortedDF[0].GetAs<string>("id"));
Assert.AreEqual("123", sortedDF[1].GetAs<string>("id"));
Assert.AreEqual("531", sortedDF[2].GetAs<string>("id"));
Assert.AreEqual("456", sortedDF[3].GetAs<string>("id"));
}
var sorted2 = peopleDataFrame.Sort(new Column[] { peopleDataFrame["name"].Asc(), peopleDataFrame["age"].Desc() });
sorted2.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var sortedDF2 = sorted2.Collect().ToArray();
Assert.AreEqual("789", sortedDF2[0].GetAs<string>("id"));
Assert.AreEqual("123", sortedDF2[1].GetAs<string>("id"));
Assert.AreEqual("531", sortedDF2[2].GetAs<string>("id"));
Assert.AreEqual("456", sortedDF2[3].GetAs<string>("id"));
}
}
/// <summary>
/// Sample to perform SortWithinPartitions on DataFrame
/// </summary>
[Sample]
internal static void DFSortWithinPartitionsSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
peopleDataFrame = peopleDataFrame.Repartition(2);
peopleDataFrame.Show();
// sort by column 'age' descending
var sorted = peopleDataFrame.SortWithinPartitions(new[] { "age" }, new[] { false });
sorted.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var partitions = sorted.MapPartitions(iters =>
new List<List<int>> { new List<int> ( iters.Select(row => row.GetAs<int>("age")) ) }).Collect();
// within each partition, age should be sorted descending
foreach (var partition in partitions)
{
CollectionAssert.AreEqual(partition.OrderByDescending(key => key), partition);
}
}
}
/// <summary>
/// Sample to perform Alias on DataFrame
/// </summary>
[Sample]
internal static void DFAliasSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var dfAs1 = peopleDataFrame.Alias("df_as1");
var dfAs2 = peopleDataFrame.Alias("df_as2");
var joined = dfAs1.Join(dfAs2, dfAs1["df_as1.name"] == dfAs2["df_as2.name"], JoinType.Inner);
var joined2 = joined.Select("df_as1.name", "df_as2.age");
joined2.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var sortedDF = joined2.Collect().ToArray();
Assert.AreEqual(6, sortedDF.Length);
Assert.IsTrue(sortedDF.Count(row => row.GetAs<string>("name") == "Bill" && row.GetAs<int>("age") == 34) == 2);
Assert.IsTrue(sortedDF.Count(row => row.GetAs<string>("name") == "Bill" && row.GetAs<int>("age") == 43) == 2);
Assert.IsTrue(sortedDF.Count(row => row.GetAs<string>("name") == "Steve" && row.GetAs<int>("age") == 14) == 1);
Assert.IsTrue(sortedDF.Count(row => row.GetAs<string>("name") == "Satya" && row.GetAs<int>("age") == 46) == 1);
}
}
/// <summary>
/// Sample to perform Select on DataFrame
/// </summary>
[Sample]
internal static void DFSelectSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var projected = peopleDataFrame.Select(peopleDataFrame["name"], "age");
projected.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var columns = projected.Columns().ToArray();
Assert.AreEqual(2, columns.Length);
Assert.IsTrue(columns.Contains("name"));
Assert.IsTrue(columns.Contains("age"));
}
}
/// <summary>
/// Sample to perform WithColumn on DataFrame
/// </summary>
[Sample]
internal static void DFWithColumnSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var dfWithNewColumn = peopleDataFrame.WithColumn("age2", peopleDataFrame["age"] + 10);
dfWithNewColumn.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
foreach (var row in dfWithNewColumn.Collect())
{
Assert.AreEqual(row.GetAs<int>("age") + 10, row.GetAs<int>("age2"));
}
}
}
/// <summary>
/// Sample to perform WithColumnRenamed on DataFrame
/// </summary>
[Sample]
internal static void DFWithColumnRenamedSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var dfWithNewColumnName = peopleDataFrame.WithColumnRenamed("age", "age2");
dfWithNewColumnName.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var columns = dfWithNewColumnName.Columns().ToArray();
Assert.IsTrue(columns.Contains("age2"));
}
}
/// <summary>
/// Sample to perform Corr on DataFrame
/// </summary>
[Sample]
internal static void DFCorrSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
double corr = peopleDataFrame.Corr("age", "age");
Console.WriteLine("Corr of column age and age is " + corr);
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.AreEqual(1.0, corr);
}
}
/// <summary>
/// Sample to perform Cov on DataFrame
/// </summary>
[Sample]
internal static void DFCovSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
double cov = peopleDataFrame.Cov("age", "age");
Console.WriteLine("Cov of column age and age is " + cov);
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.AreEqual(208.25, cov);
}
}
/// <summary>
/// Sample to perform FreqItems on DataFrame
/// </summary>
[Sample]
internal static void DFFreqItemsSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
DataFrame freqItems = peopleDataFrame.FreqItems(new []{"name"}, 0.4);
freqItems.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var collected = freqItems.Collect().ToArray();
Assert.AreEqual(1, collected.Length);
Assert.AreEqual("Bill", collected[0].Get(0)[0].ToString());
}
}
/// <summary>
/// Sample to perform Describe on DataFrame
/// </summary>
[Sample]
internal static void DFDescribeSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
DataFrame descDF = peopleDataFrame.Describe();
descDF.Show();
DataFrame descDF2 = peopleDataFrame.Describe("age", "name");
descDF2.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var collectedDesc = descDF.Collect().ToArray();
Assert.AreEqual("4", collectedDesc.First(row => row.GetAs<string>("summary") == "count").GetAs<string>("age"));
Assert.AreEqual("34.25", collectedDesc.First(row => row.GetAs<string>("summary") == "mean").GetAs<string>("age"));
var collectedDesc2 = descDF2.Collect().ToArray();
Assert.AreEqual("4", collectedDesc2.First(row => row.GetAs<string>("summary") == "count").GetAs<string>("age"));
Assert.AreEqual("Bill", collectedDesc2.First(row => row.GetAs<string>("summary") == "min").GetAs<string>("name"));
}
}
/// <summary>
/// Sample to perform Rollup on DataFrame
/// </summary>
[Sample]
internal static void DFRollupSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
DataFrame rollupDF = peopleDataFrame.Rollup("name", "age").Count();
rollupDF.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var collectedRollup = rollupDF.Collect().ToArray();
Assert.AreEqual(8, collectedRollup.Length);
}
}
/// <summary>
/// Sample to perform Cube on DataFrame
/// </summary>
[Sample]
internal static void DFCubeSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
DataFrame cubeDF = peopleDataFrame.Cube("name", "age").Count();
cubeDF.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var collectedCube = cubeDF.Collect().ToArray();
Assert.AreEqual(12, collectedCube.Length);
}
}
/// <summary>
/// Sample to perform Cube on DataFrame
/// </summary>
[Sample]
internal static void DFGroupDataOperationSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
GroupedData gd = peopleDataFrame.GroupBy("name");
var countDF = gd.Count();
countDF.Show();
var maxDF = gd.Max();
maxDF.Show();
var minDF = gd.Min();
minDF.Show();
var meanDF = gd.Mean();
meanDF.Show();
var avgDF = gd.Avg();
avgDF.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.AreEqual(2, (int)(countDF.Collect().First(col => ((string)col.Get(0) == "Bill")).Get(1)));
Assert.AreEqual(43, (int)(maxDF.Collect().First(col => ((string)col.Get(0) == "Bill")).Get(1)));
Assert.AreEqual(34, (int)(minDF.Collect().First(col => ((string)col.Get(0) == "Bill")).Get(1)));
Assert.AreEqual(38.5, (double)(meanDF.Collect().First(col => ((string)col.Get(0) == "Bill")).Get(1)));
Assert.AreEqual(38.5, (double)(avgDF.Collect().First(col => ((string)col.Get(0) == "Bill")).Get(1)));
}
}
/// <summary>
/// Sample to perform Crosstab on DataFrame
/// </summary>
[Sample]
internal static void DFCrosstabSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
DataFrame crosstab = peopleDataFrame.Crosstab("name", "age");
crosstab.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var collectedCrosstab = crosstab.Collect();
CollectionAssert.AreEquivalent(new[] { "name_age", "14", "46", "34", "43" }, crosstab.Columns().ToArray());
CollectionAssert.AreEquivalent(new[] { "Bill", "Satya", "Steve" }, collectedCrosstab.Select(row => row.GetAs<string>("name_age")).ToArray());
}
}
/// <summary>
/// Sample to perform aggregation on DataFrame using DSL
/// </summary>
[Sample]
internal static void DFAggregateDSLSample()
{
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var countAggDataFrame = peopleDataFrame.Where("name = 'Bill'").Agg(new Dictionary<string, string> {{"name", "count"}});
var countAggDataFrameCount = countAggDataFrame.Count();
var maxAggDataFrame = peopleDataFrame.GroupBy("name").Agg(new Dictionary<string, string> {{"age", "max"}});
var maxAggDataFrameCount = maxAggDataFrame.Count();
Console.WriteLine("countAggDataFrameCount: {0}, maxAggDataFrameCount: {1}.", countAggDataFrameCount, maxAggDataFrameCount);