Kinetica C# API  Version 7.1.10.0
 All Classes Namespaces Files Functions Variables Enumerations Enumerator Properties Pages
Example.cs
Go to the documentation of this file.
1 using System;
2 using System.Collections.Generic;
3 
4 using Avro;
5 using kinetica;
6 
7 namespace Example
8 {
12  public static class StringExt
13  {
14  public static string Truncate( this string value, int maxLength )
15  {
16  if ( string.IsNullOrEmpty( value ) )
17  return value;
18 
19  return ( value.Length <= maxLength ) ? value : value.Substring( 0, maxLength );
20  }
21  }
22 
23 
24  class Example
25  {
26  static void Main(string[] args)
27  {
28  Console.WriteLine("Example C# Project - Running");
29  Console.WriteLine();
30 
31  if ( args.Length < 1)
32  {
33  Console.WriteLine("Missing URL as command-line parameter.");
34  Console.WriteLine("E.g., http://kinetica:9191");
35  return;
36  }
37 
38  try
39  {
40  string server_url = args[0];
41  Console.WriteLine( "URL: {0}", server_url );
42  Console.WriteLine();
43 
44  Kinetica.Options _ServerOptions = new Kinetica.Options();
45  _ServerOptions.Username = args[1];
46  _ServerOptions.Password = args[2];
47 
48 
49  // Run the various example functions
50  run_example( server_url, _ServerOptions );
51  run_series_example( server_url, _ServerOptions );
52  run_multihead_ingest_example( server_url, _ServerOptions );
53  }
54  catch (Exception ex)
55  {
56  Console.WriteLine("Caught Exception: {0}", ex.Message );
57  }
58 
59  // We're done
60  Console.WriteLine();
61  Console.WriteLine("Example C# Project - Done");
62  Console.WriteLine();
63  Console.WriteLine("Enter any 7-digit prime number to continue: ");
64  Console.ReadLine();
65  }
66 
67 
72  private static void run_example( string server_url, Kinetica.Options _ServerOptions )
73  {
74  // Establish a connection with Kinetica
75  Kinetica kdb = new Kinetica( server_url, _ServerOptions );
76 
77  Console.WriteLine( "Example with a Record Type with Nullable Columns, Primary Keys and Shard Keys" );
78  Console.WriteLine( "=============================================================================" );
79  Console.WriteLine();
80 
81  string table_name = "csharp_example_table";
82 
83  // Create a type for our record_type_1 class
84  Console.WriteLine( "Creating the type in kinetica..." );
85  // Add some interesting properties for some of the data types
86  IDictionary<string, IList<string>> column_properties = new Dictionary<string, IList<string>>();
87  // Make a string char4 (and nullable)
88  List<string> D_props = new List<string>();
89  D_props.Add( ColumnProperty.CHAR4 );
90  D_props.Add( ColumnProperty.NULLABLE );
91  column_properties.Add( "D", D_props );
92  // Let's try another nullable column
93  List<string> E_props = new List<string>();
94  E_props.Add( ColumnProperty.NULLABLE );
95  column_properties.Add( "E", E_props );
96  // And two primary keys (one nullable)
97  List<string> A_props = new List<string>();
98  A_props.Add( ColumnProperty.PRIMARY_KEY );
99  column_properties.Add( "A", A_props );
100  List<string> B_props = new List<string>();
101  B_props.Add( ColumnProperty.PRIMARY_KEY );
102  column_properties.Add( "B", B_props );
103  // And a shard key (must be one of the primary keys, if specified--which we have)
104  B_props.Add( ColumnProperty.SHARD_KEY );
105 
106  // Create the KineticaType object which facilitates creating types in the database
107  KineticaType type1 = KineticaType.fromClass( typeof( record_type_1 ), column_properties );
108 
109  // Create the type in the database
110  string type_id = type1.create( kdb );
111  Console.WriteLine( "ID of the created type: " + type_id );
112  Console.WriteLine();
113 
114  // Show the type information (fetched from Kinetica)
115  Console.WriteLine( "Fetching the newly created type information..." );
116  ShowTypesResponse rsp = kdb.showTypes( type_id, "" );
117  Console.WriteLine( "Type properties: " );
118  foreach ( var x in rsp.properties[0] )
119  Console.WriteLine( x.Key + ": " + String.Join( ",", x.Value ) );
120  Console.WriteLine();
121 
122  // Clear any previously made table with the same name
123  Console.WriteLine( "Clearing any existing table named '{0}'", table_name );
124  try { kdb.clearTable( table_name, null ); } catch ( Exception ex ) { /* I don't care if the table doesn't already exists! */ }
125  Console.WriteLine();
126 
127  // Create a table of the given type
128  Console.WriteLine( "Creating table named '{0}'", table_name );
129  kdb.createTable( table_name, type_id );
130  Console.WriteLine();
131 
132  // Call /show/table on the table just created
133  Dictionary<string, string> show_table_options = new Dictionary<string, string>();
134  show_table_options.Add( ShowTableRequest.Options.GET_SIZES, ShowTableRequest.Options.TRUE );
135  Console.WriteLine( "Calling ShowTable on '{0}'", table_name );
136  var response2 = kdb.showTable(table_name, show_table_options);
137  Console.WriteLine( "Total size: {0}", response2.total_size );
138  Console.WriteLine( "sizes: {0}", string.Join( ", ", response2.sizes ) );
139  Console.WriteLine();
140 
141  // Create some data to be added to the table
142  List<record_type_1> newData = new List<record_type_1>() {
143  new record_type_1() { A=99, B=11, C="T0_lksdjfokdj92", D="D01", E= 2.34F, F=null, TIMESTAMP= (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds },
144  new record_type_1() { A=2, B=3, C="T1_asdfghjkl", D=null, E= 5.67F, F=null, TIMESTAMP= (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds },
145  new record_type_1() { A=99, B=999, C="T2_oierlwk", D="D244", E=-45.1F, F=9899.1, TIMESTAMP= (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds }
146  };
147 
148  // Insert the data into the table
149  Console.WriteLine( "Inserting some data in '{0}'", table_name );
150  var insertResponse = kdb.insertRecords( table_name, newData );
151  Console.WriteLine( "Inserted {0} records", insertResponse.count_inserted + insertResponse.count_updated );
152  Console.WriteLine();
153 
154  // Call /show/table on the table after adding data
155  Console.WriteLine( "Calling ShowTable on '{0}' after adding data", table_name );
156  var rsp2 = kdb.showTable(table_name, show_table_options);
157  Console.WriteLine( "Total size: {0}", rsp2.total_size );
158  Console.WriteLine( "sizes: {0}", string.Join( ", ", rsp2.sizes ) );
159  Console.WriteLine();
160 
161  // Fetch the data back out of the DB using /get/records
162  Console.WriteLine( "Getting records out" );
163  var getRecordsResponse = kdb.getRecords<record_type_1>( table_name, 0, 100 );
164  Console.WriteLine( "GetRecords got {0} records", getRecordsResponse.data.Count );
165  foreach ( var r in getRecordsResponse.data ) Console.WriteLine( "\t" + r.ToString() );
166  Console.WriteLine();
167 
168  // Do a filter operation
169  Console.WriteLine( "Filtering data" );
170  string view_name_1 = "csharp_view_01";
171  string filter_expression = "E > 0";
172  var filterResponse = kdb.filter( table_name, view_name_1, filter_expression );
173  Console.WriteLine( "Filtered {0} records", filterResponse.count );
174  Console.WriteLine();
175 
176  // Fetch the data from the filtered view using /get/records/fromcollection
177  Console.WriteLine( "Getting records out (using /get/records/fromcollection) from view {0}", view_name_1 );
178  IDictionary<string, string> getrecords_fc_options = new Dictionary<string, string>();
179  getrecords_fc_options.Add( "return_record_ids", "true" );
180  var request = new GetRecordsFromCollectionRequest( view_name_1, 0, 100, GetRecordsFromCollectionRequest.Encoding.BINARY, getrecords_fc_options );
181  var getRecordsFromCollectionResponse = kdb.getRecordsFromCollection<record_type_1>( request );
182  Console.WriteLine( "GetRecordsFromCollection got {0} records", getRecordsFromCollectionResponse.data.Count );
183  foreach ( var r in getRecordsFromCollectionResponse.data ) Console.WriteLine( "\t" + r.ToString() );
184  Console.WriteLine();
185 
186  // Do an /aggregate/groupby operation on the data
187  Console.WriteLine( "Performing a group-by aggregate operation" );
188  IList<string> column_names = new List<string>();
189  column_names.Add( "A" );
190  column_names.Add( "D" );
191  var agbResponse = kdb.aggregateGroupBy( table_name, column_names, 0, 100 );
192  Console.WriteLine( "Group by got {0} records", agbResponse.total_number_of_records );
193  // Print the decoded data out to the console
194  ( ( List<KineticaRecord> ) ( agbResponse.data ) ).ForEach( r => Console.WriteLine( r.ContentsToString() ) );
195  Console.WriteLine();
196 
197  // Do an /aggregate/unique operation on column F
198  string col_name = "F";
199  Console.WriteLine( $"Performing a unique aggregate operation on column {col_name}" );
200  var uniqueResponse = kdb.aggregateUnique( table_name, col_name, 0, 100 );
201  // Print the decoded data out to the console
202  ( ( List<KineticaRecord> ) ( uniqueResponse.data ) ).ForEach( r => Console.WriteLine( r.ContentsToString() ) );
203  Console.WriteLine();
204 
205  // Fetch the data back out of the DB using /get/records/bycolumn
206  Console.WriteLine( "Getting records out (using /get/records/bycolumn)" );
207  IList<string> col_names = new List<string>();
208  col_names.Add( "B" );
209  col_names.Add( "C" );
210  col_names.Add( "E" );
211  var getRecordsByColumnResponse = kdb.getRecordsByColumn( table_name, col_names, 0, 100 );
212  Console.WriteLine( "GetRecordsByColumn got {0} records", getRecordsByColumnResponse.data.Count );
213  foreach ( var r in getRecordsByColumnResponse.data ) Console.WriteLine( "\t" + r.ContentsToString() );
214  Console.WriteLine();
215 
216  Console.WriteLine();
217  } // end run_example
218 
219 
220 
225  private static void run_series_example( string server_url, Kinetica.Options _ServerOptions )
226  {
227  // Establish a connection with Kinetica
228  Kinetica kdb = new Kinetica( server_url, _ServerOptions );
229 
230  Console.WriteLine( "Example showcasing a record with a series type column" );
231  Console.WriteLine( "======================================================" );
232  Console.WriteLine();
233 
234  // Create the series type record in Kinetica
235  KineticaType type_series = KineticaType.fromClass( typeof( record_type_series ) );
236  string series_type_id = type_series.create( kdb );
237  Console.WriteLine( "ID of the created series type: " + series_type_id );
238  Console.WriteLine();
239 
240  // Clear any previously made table with the same name
241  string table_name_series = "csharp_example_series_table";
242  Console.WriteLine( "Clearing any existing table named '{0}'", table_name_series );
243  try { kdb.clearTable( table_name_series, null ); } catch ( Exception ex ) { /* I don't care if the table doesn't already exists! */ }
244  Console.WriteLine();
245 
246  // Create a table of the given type
247  Console.WriteLine( "Creating table named '{0}'", table_name_series );
248  kdb.createTable( table_name_series, series_type_id );
249  Console.WriteLine();
250 
251  // Create some data to be added to the table
252  string series_1 = "series_1";
253  string series_2 = "series_2";
254  List<record_type_series> series_data = new List<record_type_series>() {
255  // Five series points moving horizontally
256  new record_type_series() { x = 30, y = 40, TRACKID = series_1, TIMESTAMP= (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds },
257  new record_type_series() { x = 35, y = 40, TRACKID = series_1, TIMESTAMP= (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds },
258  new record_type_series() { x = 40, y = 40, TRACKID = series_1, TIMESTAMP= (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds },
259  new record_type_series() { x = 45, y = 40, TRACKID = series_1, TIMESTAMP= (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds },
260  new record_type_series() { x = 50, y = 40, TRACKID = series_1, TIMESTAMP= (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds },
261  // Five series points moving vertically
262  new record_type_series() { x = -30, y = -40, TRACKID = series_2, TIMESTAMP= (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds },
263  new record_type_series() { x = -30, y = -45, TRACKID = series_2, TIMESTAMP= (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds },
264  new record_type_series() { x = -30, y = -50, TRACKID = series_2, TIMESTAMP= (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds },
265  new record_type_series() { x = -30, y = -55, TRACKID = series_2, TIMESTAMP= (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds },
266  new record_type_series() { x = -30, y = -60, TRACKID = series_2, TIMESTAMP= (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds },
267  };
268 
269  // Insert the data into the table
270  Console.WriteLine( "Inserting some data in '{0}'", table_name_series );
271  var insertResponse2 = kdb.insertRecords( table_name_series, series_data );
272  Console.WriteLine( "Inserted {0} records", insertResponse2.count_inserted + insertResponse2.count_updated );
273  Console.WriteLine();
274 
275  // Fetch the data back out of the DB using /get/records
276  Console.WriteLine( "Getting records out from {0}", table_name_series );
277  var getRecordsResponse2 = kdb.getRecords<record_type_series>( table_name_series );
278  Console.WriteLine( "GetRecords got {0} records", getRecordsResponse2.data.Count );
279  foreach ( var r in getRecordsResponse2.data ) Console.WriteLine( "\t" + r.ToString() );
280  Console.WriteLine();
281 
282  // Filter the series data such that only a few series point from only one of the series
283  // are in the view
284  Console.WriteLine( "Filtering data from {0} so that only some points from {1} to make it", table_name_series, series_1 );
285  string view_name_2 = "csharp_view_02";
286  // Only the first, second, and third records from the first series should survive this filter
287  // (for track/series type records, we're filtering the "line segments", so records just outside the
288  // filtered box will also be captured)
289  var filterByBoxResp = kdb.filterByBox( table_name_series, view_name_2, "x", 33, 37, "y", 35, 45 );
290  Console.WriteLine( "Filtered {0} records", filterByBoxResp.count );
291  Console.WriteLine();
292  // Show the filtered objects
293  var getRecordsResponse3 = kdb.getRecords<record_type_series>( view_name_2 );
294  Console.WriteLine( "GetRecords got {0} records from {1}", getRecordsResponse3.data.Count, view_name_2 );
295  foreach ( var r in getRecordsResponse3.data ) Console.WriteLine( "\t" + r.ToString() );
296  Console.WriteLine();
297 
298 
299  // Extract the entire series from the source table (based on which ones are in the view)
300  Console.WriteLine( "Getting records belonging to one series out from table '{0}' using the partial series in view '{1}'", table_name_series, view_name_2 );
301  var getRecordsBySeriesResp = kdb.getRecordsBySeries<record_type_series>( view_name_2, table_name_series );
302  Console.WriteLine( "GetRecordsBySeries got {0} list of records (should get one list of five records in it)", getRecordsBySeriesResp.data.Count );
303  foreach ( var r_list in getRecordsBySeriesResp.data )
304  foreach ( var r in r_list ) Console.WriteLine( "\t" + r.ToString() );
305  Console.WriteLine();
306 
307  Console.WriteLine();
308  } // end run_series_example()
309 
310 
316  private static void run_multihead_ingest_example( string server_url, Kinetica.Options _ServerOptions )
317  {
318  // Establish a connection with Kinetica
319  Kinetica kdb = new Kinetica( server_url, _ServerOptions );
320 
321  Console.WriteLine( "\n\n" );
322  Console.WriteLine( "Example showcasing multihead ingestion(one shard key, two primary keys)" );
323  Console.WriteLine( "=======================================================================" );
324  Console.WriteLine();
325 
326  // Create a type for our record_type_1 class
327  // Add some interesting properties for some of the data types
328  IDictionary<string, IList<string>> column_properties = new Dictionary<string, IList<string>>();
329 
330  // Add a primary key
331  List<string> A_props = new List<string>();
332  A_props.Add( ColumnProperty.PRIMARY_KEY );
333  column_properties.Add( "A", A_props );
334 
335  // And a shard key (must be part of the primary keys, if specified--which we have)
336  List<string> ts_props = new List<string>();
337  ts_props.Add( ColumnProperty.PRIMARY_KEY );
338  ts_props.Add( ColumnProperty.SHARD_KEY );
339  ts_props.Add( ColumnProperty.TIMESTAMP );
340  column_properties.Add( "TIMESTAMP", ts_props );
341 
342  // Create the KineticaType object which facilitates creating types in the database
343  KineticaType type1 = KineticaType.fromClass( typeof( record_type_1 ), column_properties );
344 
345  // Create the type in the database
346  string type_id = type1.create( kdb );
347 
348  string table_name = "csharp_example_table_01";
349  // Clear any previously made table with the same name
350  Console.WriteLine( "Clearing any existing table named '{0}'", table_name );
351  try { kdb.clearTable( table_name, null ); } catch ( Exception ex ) { /* I don't care if the table doesn't already exists! */ }
352  Console.WriteLine();
353 
354  // Create a table of the given type
355  Console.WriteLine( $"Creating table named '{table_name}'" );
356  kdb.createTable( table_name, type_id );
357  Console.WriteLine();
358 
359  // Create the ingestor (we're not giving any worker IP addresses; the ingestor class will figure it
360  // out by itself)
361  int batch_size = 100;
362  KineticaIngestor<record_type_1> ingestor = new KineticaIngestor<record_type_1>( kdb, table_name, batch_size, type1 );
363 
364  // Generate data to be inserted
365  int num_records = batch_size * 5;
366  List<record_type_1> records = new List<record_type_1>();
367  Random rng = new Random();
368  double null_probability = 0.2;
369  for ( int i = 0; i < num_records; ++i )
370  {
371  // Restricting string length to 256
372  int max_str_len = rng.Next( 0, 256 );
373  record_type_1 record = new record_type_1()
374  {
375  A = rng.Next(),
376  B = rng.Next(),
377  C = System.IO.Path.GetRandomFileName().Truncate( max_str_len ),
378  D = System.IO.Path.GetRandomFileName().Truncate( max_str_len ),
379  E = (float)(rng.NextDouble() * rng.Next()),
380  F = ( rng.NextDouble() < null_probability ) ? null : ( double? ) ( rng.NextDouble() * rng.Next() ),
381  TIMESTAMP = (long)rng.Next( -306102240, 293795424 ) * rng.Next( 100000 )
382  };
383 
384  records.Add( record );
385  } // end for loop
386 
387  Console.WriteLine( $"Generated {num_records} records." );
388 
389  // Insert the records into the ingestor
390  Console.WriteLine( $"Inserting {num_records} records..." );
391  ingestor.insert( records );
392 
393  // Flush the ingestor (which actually inserts the records)
394  Console.WriteLine( "\nFlushing any remaining records." );
395  ingestor.flush();
396 
397  Console.WriteLine();
398  Console.WriteLine();
399  } // end run_multihead_ingest_example()
400 
401 
402  private class record_type_1
403  {
404  public int A { get; set; }
405  public int B { get; set; }
406  public string C { get; set; }
407  public string D { get; set; }
408  public float E { get; set; }
409  public double? F { get; set; }
410  public long TIMESTAMP { get; set; }
411 
412  public override string ToString()
413  {
414  string f;
415  if ( F != null )
416  f = $"{F}";
417  else
418  f = "<null>";
419  return $"{{ A={A}, B={B}, C={C}, D={D}, E={E}, F={f}, TIMESTAMP={TIMESTAMP} }}";
420  }
421  } // end class record_type_1
422 
423 
424  private class record_type_series
425  {
426  public double x { get; set; }
427  public double y { get; set; }
428  public string TRACKID { get; set; }
429  public long TIMESTAMP { get; set; }
430 
431  public override string ToString()
432  {
433  return $"{{ x={x}, y={y}, TRACKID={TRACKID}, TIMESTAMP={TIMESTAMP} }}";
434  }
435  } // end class record_type_series
436  }
437 }
Connection Options
Definition: Kinetica.cs:50
A set of parameters for Kinetica.getRecordsFromCollection{T}(string,long,long,IDictionary{string, string}).
static string Truncate(this string value, int maxLength)
Definition: Example.cs:14
Extension to string that has a truncate function.
Definition: Example.cs:12
A set of results returned by Kinetica.showTypes(string,string,IDictionary{string, string})...
Definition: ShowTypes.cs:158
API to talk to Kinetica Database
Definition: Kinetica.cs:40