forked from microsoft/Mobius
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SqlContextSamples.cs
357 lines (306 loc) · 15.3 KB
/
SqlContextSamples.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
// 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.IO;
using Microsoft.Spark.CSharp.Sql;
using NUnit.Framework;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Microsoft.Spark.CSharp.Samples
{
class SqlContextSamples
{
private const string PeopleJson = @"people.json";
private const string RequestsLog = @"requestslog.txt";
private static SqlContext sqlContext;
private static SqlContext GetSqlContext()
{
return sqlContext ?? (sqlContext = new SqlContext(SparkCLRSamples.SparkContext));
}
/// <summary>
/// Sample to GetOrCreate a sql context
/// </summary>
[Sample]
internal static void SqlContextGetOrCreateSample()
{
// create a new SqlContext
var sqlContext = SqlContext.GetOrCreate(SparkCLRSamples.SparkContext);
// get existing SqlContext
var getOrCreatedSqlContext = SqlContext.GetOrCreate(SparkCLRSamples.SparkContext);
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.AreEqual(sqlContext, getOrCreatedSqlContext);
}
}
/// <summary>
/// Sample to create DataFrame. The RDD is generated from SparkContext Parallelize; the schema is created via object creating.
/// </summary>
[Sample]
internal static void SqlContextCreateDataFrameSample()
{
var schemaPeople = new StructType(new List<StructField>
{
new StructField("id", new StringType()),
new StructField("name", new StringType()),
new StructField("age", new IntegerType()),
new StructField("address", new StructType(new List<StructField>
{
new StructField("city", new StringType()),
new StructField("state", new StringType())
})),
new StructField("phone numbers", new ArrayType(new StringType()))
});
var rddPeople = SparkCLRSamples.SparkContext.Parallelize(
new List<object[]>
{
new object[] { "123", "Bill", 43, new object[]{ "Columbus", "Ohio" }, new string[]{ "Tel1", "Tel2" } },
new object[] { "456", "Steve", 34, new object[]{ "Seattle", "Washington" }, new string[]{ "Tel3", "Tel4" } }
});
var dataFramePeople = GetSqlContext().CreateDataFrame(rddPeople, schemaPeople);
Console.WriteLine("------ Schema of People Data Frame:\r\n");
dataFramePeople.ShowSchema();
Console.WriteLine();
var collected = dataFramePeople.Collect().ToArray();
foreach (var people in collected)
{
string id = people.Get("id");
string name = people.Get("name");
int age = people.Get("age");
Row address = people.Get("address");
string city = address.Get("city");
string state = address.Get("state");
object[] phoneNumbers = people.Get("phone numbers");
Console.WriteLine("id:{0}, name:{1}, age:{2}, address:(city:{3},state:{4}), phoneNumbers:[{5},{6}]\r\n", id, name, age, city, state, phoneNumbers[0], phoneNumbers[1]);
}
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.AreEqual(2, dataFramePeople.Rdd.Count());
Assert.AreEqual(schemaPeople.Json, dataFramePeople.Schema.Json);
}
}
/// <summary>
/// Sample to create DataFrame. The RDD is generated from SparkContext TextFile; the schema is created from Json.
/// </summary>
[Sample]
internal static void SqlContextCreateDataFrameSample2()
{
var rddRequestsLog = SparkCLRSamples.SparkContext.TextFile(SparkCLRSamples.Configuration.GetInputDataPath(RequestsLog), 1).Map(r => r.Split(',').Select(s => (object)s).ToArray());
const string schemaRequestsLogJson = @"{
""fields"": [{
""metadata"": {},
""name"": ""guid"",
""nullable"": false,
""type"": ""string""
},
{
""metadata"": {},
""name"": ""datacenter"",
""nullable"": false,
""type"": ""string""
},
{
""metadata"": {},
""name"": ""abtestid"",
""nullable"": false,
""type"": ""string""
},
{
""metadata"": {},
""name"": ""traffictype"",
""nullable"": false,
""type"": ""string""
}],
""type"": ""struct""
}";
// create schema from parsing Json
StructType requestsLogSchema = DataType.ParseDataTypeFromJson(schemaRequestsLogJson) as StructType;
var dataFrameRequestsLog = GetSqlContext().CreateDataFrame(rddRequestsLog, requestsLogSchema);
Console.WriteLine("------ Schema of RequestsLog Data Frame:");
dataFrameRequestsLog.ShowSchema();
Console.WriteLine();
var collected = dataFrameRequestsLog.Collect().ToArray();
foreach (var request in collected)
{
string guid = request.Get("guid");
string datacenter = request.Get("datacenter");
string abtestid = request.Get("abtestid");
string traffictype = request.Get("traffictype");
Console.WriteLine("guid:{0}, datacenter:{1}, abtestid:{2}, traffictype:{3}\r\n", guid, datacenter, abtestid, traffictype);
}
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.AreEqual(10, collected.Length);
Assert.AreEqual(Regex.Replace(schemaRequestsLogJson, @"\s", string.Empty), Regex.Replace(dataFrameRequestsLog.Schema.Json, @"\s", string.Empty));
}
}
/// <summary>
/// Sample to create new session from a SqlContext
/// </summary>
[Sample]
internal static void SqlContextNewSessionSample()
{
var originalSqlContext = GetSqlContext();
var newSession = originalSqlContext.NewSession();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
originalSqlContext.SetConf("key", "value_1");
newSession.SetConf("key", "value_2");
Assert.AreEqual("value_1", originalSqlContext.GetConf("key", "defaultValue"));
Assert.AreEqual("value_2", newSession.GetConf("key", "defaultValue"));
}
}
/// <summary>
/// Sample to register DataFrame as temp table/show tableNames/drop table
/// </summary>
[Sample]
internal static void SqlContextTempTableSample()
{
var sqlContext = GetSqlContext();
var peopleDataFrame = sqlContext.Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
// register a DataFrame as temp table
sqlContext.RegisterDataFrameAsTable(peopleDataFrame, "people");
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var tableNames = sqlContext.TableNames().ToArray();
Assert.AreEqual(1, tableNames.Length);
Assert.IsTrue(tableNames.Contains("people"));
}
// Drop a temp table
sqlContext.DropTempTable("people");
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.False(sqlContext.TableNames().Contains("people"));
}
}
/// <summary>
/// Sample to show tables
/// </summary>
[Sample]
internal static void SqlContextTablesSample()
{
var sqlContext = GetSqlContext();
var peopleDataFrame = sqlContext.Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
sqlContext.RegisterDataFrameAsTable(peopleDataFrame, "people1");
sqlContext.RegisterDataFrameAsTable(peopleDataFrame, "people2");
var tablesDataFrame = sqlContext.Tables();
tablesDataFrame.Show();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
var collected = tablesDataFrame.Collect().ToArray();
Assert.AreEqual(2, collected.Length);
Assert.IsTrue(collected.Any(row => "people1" == row.GetAs<string>("tableName") && row.GetAs<bool>("isTemporary")));
Assert.IsTrue(collected.Any(row => "people2" == row.GetAs<string>("tableName") && row.GetAs<bool>("isTemporary")));
}
}
/// <summary>
/// Sample to uncache table
/// </summary>
[Sample]
internal static void SqlContextCacheAndUncacheTableSample()
{
var sqlContext = GetSqlContext();
var peopleDataFrame = sqlContext.Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
// register a DataFrame as temp table
sqlContext.RegisterDataFrameAsTable(peopleDataFrame, "people");
// cache table
sqlContext.CacheTable("people");
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.IsTrue(sqlContext.IsCached("people"));
}
// uncache table
sqlContext.UncacheTable("people");
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.IsFalse(sqlContext.IsCached("people"));
}
}
/// <summary>
/// Sample to clear cache
/// </summary>
[Sample]
internal static void SqlContextClearCacheTableSample()
{
var sqlContext = GetSqlContext();
var peopleDataFrame = sqlContext.Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
// register a DataFrame as temp table
sqlContext.RegisterDataFrameAsTable(peopleDataFrame, "people");
// cache table
sqlContext.CacheTable("people");
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.IsTrue(sqlContext.IsCached("people"));
}
// clear cache
sqlContext.ClearCache();
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.IsFalse(sqlContext.IsCached("people"));
}
}
/// <summary>
/// DataFrameReader read json sample
/// </summary>
[Sample]
internal static void SqlContextReadJsonSample()
{
// load json
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
peopleDataFrame.ShowSchema();
peopleDataFrame.Show();
var count1 = peopleDataFrame.Count();
Console.WriteLine("Line count in people.json: {0}", count1);
// load json with schema sample
var peopleDataFrameWitSchema = GetSqlContext().Read().Schema(peopleDataFrame.Schema).Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
peopleDataFrameWitSchema.ShowSchema();
peopleDataFrameWitSchema.Show();
var count2 = peopleDataFrameWitSchema.Count();
Console.WriteLine("Line count in people.json: {0}", count2);
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.AreEqual(count1, count2);
Assert.AreEqual(4, count1);
}
}
/// <summary>
/// DataFrameReader read json with option sample
/// </summary>
[Sample]
internal static void SqlContextReadJsonWithOptionSample()
{
// load json with sampling ration option sample
// set sampling ration to a very little value so that schema probably won't be infered.
var peopleDataFrame = GetSqlContext().Read().Option("samplingRatio", "0.001").Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
peopleDataFrame.ShowSchema();
peopleDataFrame.Show();
var count1 = peopleDataFrame.Count();
Console.WriteLine("Line count in people.json: {0}", count1);
}
/// <summary>
/// DataFrameReader read parquet sample
/// </summary>
[Sample]
internal static void SqlContextReadParquetSample()
{
// save json file to parquet file first
var peopleDataFrame = GetSqlContext().Read().Json(SparkCLRSamples.Configuration.GetInputDataPath(PeopleJson));
var expectedCount = peopleDataFrame.Count();
var parquetPath = SparkCLRSamples.FileSystemHelper.GetTempPath() + "DF_Parquet_Samples_" + (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0)).TotalSeconds;
peopleDataFrame.Coalesce(1).Write().Parquet(parquetPath);
Console.WriteLine("Save dataframe to parquet: {0}", parquetPath);
var peopleDataFrame2 = GetSqlContext().Read().Parquet(parquetPath);
Console.WriteLine("Schema:");
peopleDataFrame2.ShowSchema();
peopleDataFrame2.Show();
var count = peopleDataFrame2.Count();
Console.WriteLine("Rows in peopleDataFrame2: {0}", count);
if (SparkCLRSamples.Configuration.IsValidationEnabled)
{
Assert.AreEqual(expectedCount, count);
}
SparkCLRSamples.FileSystemHelper.DeleteDirectory(parquetPath, true);
Console.WriteLine("Remove parquet directory: {0}", parquetPath);
}
}
}