Kinetica   C#   API  Version 7.2.3.1
AllTypesExample.cs
Go to the documentation of this file.
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Threading.Tasks;
5 using kinetica;
6 using kinetica.Records;
7 
8 namespace Example
9 {
16  public static class AllTypesExample
17  {
25  {
26  // ========== PRIMARY KEY / SHARD KEY ==========
28  public int id { get; set; }
29 
30  // ========== INTEGER TYPES ==========
32  public int bool_col { get; set; }
33 
35  public int int8_col { get; set; }
36 
38  public int int16_col { get; set; }
39 
41  public int int_col { get; set; }
42 
44  public int? nullable_int_col { get; set; }
45 
46  // ========== LONG TYPES ==========
48  public long long_col { get; set; }
49 
51  public long timestamp_col { get; set; }
52 
54  public long? nullable_long_col { get; set; }
55 
56  // ========== FLOATING POINT TYPES ==========
58  public float float_col { get; set; }
59 
61  public float? nullable_float_col { get; set; }
62 
64  public double double_col { get; set; }
65 
67  public double? nullable_double_col { get; set; }
68 
69  // ========== FIXED-LENGTH STRING TYPES ==========
71  public string char1_col { get; set; } = string.Empty;
72 
74  public string char4_col { get; set; } = string.Empty;
75 
77  public string char8_col { get; set; } = string.Empty;
78 
80  public string char16_col { get; set; } = string.Empty;
81 
83  public string char32_col { get; set; } = string.Empty;
84 
86  public string char64_col { get; set; } = string.Empty;
87 
89  public string char128_col { get; set; } = string.Empty;
90 
92  public string char256_col { get; set; } = string.Empty;
93 
94  // ========== VARIABLE-LENGTH STRING ==========
96  public string string_col { get; set; } = string.Empty;
97 
99  public string? nullable_string_col { get; set; }
100 
101  // ========== SPECIAL STRING TYPES ==========
103  public string date_col { get; set; } = string.Empty;
104 
106  public string time_col { get; set; } = string.Empty;
107 
109  public string datetime_col { get; set; } = string.Empty;
110 
112  public string decimal_col { get; set; } = string.Empty;
113 
115  public string ipv4_col { get; set; } = string.Empty;
116 
118  public string uuid_col { get; set; } = string.Empty;
119 
121  public string ulong_col { get; set; } = string.Empty;
122 
124  public string json_col { get; set; } = string.Empty;
125 
127  public string wkt_col { get; set; } = string.Empty;
128 
129  // Note: BYTES type (for VECTOR data) requires special handling and is not
130  // directly supported through reflection-based type creation.
131  // Use SQL CREATE TABLE with VECTOR(n) type for vector columns.
132 
133  public override string ToString()
134  {
135  return $"AllTypesRecord {{ id={id}, bool={bool_col}, int={int_col}, long={long_col}, " +
136  $"float={float_col:F2}, double={double_col:F4}, string='{string_col}', " +
137  $"date='{date_col}', time='{time_col}', datetime='{datetime_col}', " +
138  $"decimal='{decimal_col}', ipv4='{ipv4_col}', uuid='{uuid_col}' }}";
139  }
140 
142  {
143  return new ShardKeyValues(("id", ShardKeyValue.Int(id)));
144  }
145  }
146 
153  public static async Task RunAsync(string serverUrl, string username, string password)
154  {
155  Console.WriteLine();
156  Console.WriteLine("=========================================================");
157  Console.WriteLine("= All Types Example - BulkInserter & RecordRetriever =");
158  Console.WriteLine("=========================================================");
159  Console.WriteLine();
160 
161  // Create Kinetica connection
162  var options = new Kinetica.Options
163  {
164  Username = username,
165  Password = password
166  };
167  var kdb = new Kinetica(serverUrl, options);
168 
169  const string tableName = "csharp_all_types_example";
170 
171  try
172  {
173  // Step 1: Create the table with all types
174  Console.WriteLine("Step 1: Creating table with all Kinetica types...");
175  await CreateTableAsync(kdb, tableName);
176  Console.WriteLine($" Table '{tableName}' created successfully.\n");
177 
178  // Step 2: Generate test records
179  Console.WriteLine("Step 2: Generating test records...");
180  const int recordCount = 1000;
181  var records = GenerateRecords(recordCount);
182  Console.WriteLine($" Generated {recordCount} records.\n");
183 
184  // Step 3: Insert records using BulkInserter
185  Console.WriteLine("Step 3: Inserting records using BulkInserter...");
186  var insertStats = await InsertRecordsAsync(kdb, tableName, records);
187  Console.WriteLine($" Inserted: {insertStats.inserted}, Updated: {insertStats.updated}");
188  Console.WriteLine($" Throughput: {insertStats.throughput:N0} records/sec\n");
189 
190  // Step 4: Retrieve records using RecordRetriever
191  Console.WriteLine("Step 4: Retrieving records using RecordRetriever...");
192  var retrievedRecords = await RetrieveRecordsAsync(kdb, tableName);
193  Console.WriteLine($" Retrieved {retrievedRecords.Count} records.\n");
194 
195  // Step 5: Display sample records
196  Console.WriteLine("Step 5: Sample records (first 5):");
197  Console.WriteLine(new string('-', 100));
198  foreach (var record in retrievedRecords.Take(5))
199  {
200  Console.WriteLine($" {record}");
201  }
202  Console.WriteLine(new string('-', 100));
203  Console.WriteLine();
204 
205  // Step 6: Demonstrate filtered retrieval
206  Console.WriteLine("Step 6: Filtered retrieval (id < 10 AND bool_col = 1)...");
207  var filteredRecords = await RetrieveFilteredRecordsAsync(kdb, tableName, "id < 10 AND bool_col = 1");
208  Console.WriteLine($" Retrieved {filteredRecords.Count} filtered records.\n");
209 
210  // Step 7: Demonstrate sorted retrieval
211  Console.WriteLine("Step 7: Sorted retrieval (ORDER BY double_col DESC, LIMIT 5)...");
212  var sortedRecords = await RetrieveSortedRecordsAsync(kdb, tableName, "double_col", descending: true, limit: 5);
213  Console.WriteLine($" Top 5 by double_col DESC:");
214  foreach (var record in sortedRecords)
215  {
216  Console.WriteLine($" id={record.id}, double_col={record.double_col:F4}");
217  }
218  Console.WriteLine();
219 
220  Console.WriteLine("All Types Example completed successfully!");
221  }
222  catch (Exception ex)
223  {
224  Console.WriteLine($"Error: {ex.Message}");
225  Console.WriteLine(ex.StackTrace);
226  }
227  finally
228  {
229  // Cleanup: Drop the table
230  Console.WriteLine($"\nCleaning up: Dropping table '{tableName}'...");
231  try
232  {
233  kdb.clearTable(tableName, "", new Dictionary<string, string>
234  {
236  });
237  Console.WriteLine(" Table dropped.");
238  }
239  catch (Exception ex)
240  {
241  Console.WriteLine($" Warning: Could not drop table: {ex.Message}");
242  }
243  }
244  }
245 
249  private static Task CreateTableAsync(Kinetica kdb, string tableName)
250  {
251  // Define column properties for each column type
252  var columnProperties = new Dictionary<string, IList<string>>
253  {
254  // Primary key
255  ["id"] = new List<string> { ColumnProperty.PRIMARY_KEY },
256 
257  // Integer type properties
258  ["bool_col"] = new List<string> { ColumnProperty.BOOLEAN },
259  ["int8_col"] = new List<string> { ColumnProperty.INT8 },
260  ["int16_col"] = new List<string> { ColumnProperty.INT16 },
261  ["nullable_int_col"] = new List<string> { ColumnProperty.NULLABLE },
262 
263  // Long type properties
264  ["timestamp_col"] = new List<string> { ColumnProperty.TIMESTAMP },
265  ["nullable_long_col"] = new List<string> { ColumnProperty.NULLABLE },
266 
267  // Float/Double nullable properties
268  ["nullable_float_col"] = new List<string> { ColumnProperty.NULLABLE },
269  ["nullable_double_col"] = new List<string> { ColumnProperty.NULLABLE },
270 
271  // Fixed-length string properties (CHAR1-CHAR256)
272  ["char1_col"] = new List<string> { ColumnProperty.CHAR1 },
273  ["char4_col"] = new List<string> { ColumnProperty.CHAR4 },
274  ["char8_col"] = new List<string> { ColumnProperty.CHAR8 },
275  ["char16_col"] = new List<string> { ColumnProperty.CHAR16 },
276  ["char32_col"] = new List<string> { ColumnProperty.CHAR32 },
277  ["char64_col"] = new List<string> { ColumnProperty.CHAR64 },
278  ["char128_col"] = new List<string> { ColumnProperty.CHAR128 },
279  ["char256_col"] = new List<string> { ColumnProperty.CHAR256 },
280 
281  // Nullable string
282  ["nullable_string_col"] = new List<string> { ColumnProperty.NULLABLE },
283 
284  // Special string types
285  ["date_col"] = new List<string> { ColumnProperty.DATE },
286  ["time_col"] = new List<string> { ColumnProperty.TIME },
287  ["datetime_col"] = new List<string> { ColumnProperty.DATETIME },
288  ["decimal_col"] = new List<string> { ColumnProperty.DECIMAL },
289  ["ipv4_col"] = new List<string> { ColumnProperty.IPV4 },
290  ["uuid_col"] = new List<string> { ColumnProperty.UUID },
291  ["ulong_col"] = new List<string> { ColumnProperty.ULONG },
292  ["json_col"] = new List<string> { ColumnProperty.JSON },
293  ["wkt_col"] = new List<string> { ColumnProperty.WKT }
294  };
295 
296  // Clear any existing table
297  kdb.clearTable(tableName, "", new Dictionary<string, string>
298  {
300  });
301 
302  // Create the type from our record class with the specified properties
303  var ktype = KineticaType.fromClass(typeof(AllTypesRecord), columnProperties);
304 
305  // Create the type in the database
306  string typeId = ktype.create(kdb);
307 
308  // Create the table
309  kdb.createTable(tableName, typeId);
310 
311  return Task.CompletedTask;
312  }
313 
317  private static List<AllTypesRecord> GenerateRecords(int count)
318  {
319  var records = new List<AllTypesRecord>(count);
320  var random = new Random(42); // Fixed seed for reproducibility
321  var baseTime = new DateTime(2024, 1, 1, 0, 0, 0, DateTimeKind.Utc);
322 
323  for (int i = 0; i < count; i++)
324  {
325  var record = new AllTypesRecord
326  {
327  // Primary key
328  id = i,
329 
330  // Integer types
331  bool_col = random.Next(0, 2), // 0 or 1
332  int8_col = random.Next(-128, 128), // -128 to 127
333  int16_col = random.Next(-32768, 32768), // -32768 to 32767
334  int_col = random.Next(), // Full int range
335  nullable_int_col = i % 5 == 0 ? null : random.Next(0, 1000),
336 
337  // Long types
338  long_col = random.NextInt64(),
339  timestamp_col = ((DateTimeOffset)baseTime.AddMinutes(i)).ToUnixTimeMilliseconds(),
340  nullable_long_col = i % 7 == 0 ? null : random.NextInt64(0, 1_000_000_000),
341 
342  // Float types
343  float_col = (float)(random.NextDouble() * 1000),
344  nullable_float_col = i % 3 == 0 ? null : (float)(random.NextDouble() * 100),
345 
346  // Double types
347  double_col = random.NextDouble() * 10000,
348  nullable_double_col = i % 4 == 0 ? null : random.NextDouble() * 500,
349 
350  // Fixed-length strings
351  char1_col = ((char)('A' + (i % 26))).ToString(),
352  char4_col = $"C{i % 1000:D3}",
353  char8_col = $"CHAR{i % 10000:D4}",
354  char16_col = $"CHAR16_{i:D8}",
355  char32_col = $"This is a char32 value #{i}",
356  char64_col = $"This is a longer char64 column value for record #{i}",
357  char128_col = $"CHAR128 column with more text capacity. Record #{i}. Random: {random.Next()}",
358  char256_col = $"CHAR256 provides even more space for text data. Record #{i}. UUID: {Guid.NewGuid()}",
359 
360  // Variable-length string
361  string_col = $"Variable length string for record {i} with random data: {Guid.NewGuid()}",
362  nullable_string_col = i % 6 == 0 ? null : $"Nullable string #{i}",
363 
364  // Date/Time types
365  date_col = baseTime.AddDays(i).ToString("yyyy-MM-dd"),
366  time_col = baseTime.AddSeconds(i * 37).ToString("HH:mm:ss.fff"),
367  datetime_col = baseTime.AddMinutes(i).ToString("yyyy-MM-dd HH:mm:ss.fff"),
368 
369  // Special string types
370  decimal_col = (random.NextDouble() * 100000).ToString("F4"),
371  ipv4_col = $"{random.Next(1, 256)}.{random.Next(0, 256)}.{random.Next(0, 256)}.{random.Next(1, 256)}",
372  uuid_col = Guid.NewGuid().ToString(),
373  ulong_col = ((ulong)random.NextInt64(0, long.MaxValue)).ToString(),
374  json_col = $"{{\"id\": {i}, \"name\": \"record_{i}\", \"active\": {(i % 2 == 0).ToString().ToLower()}}}",
375  wkt_col = $"POINT({-180 + random.NextDouble() * 360:F6} {-90 + random.NextDouble() * 180:F6})"
376  };
377 
378  records.Add(record);
379  }
380 
381  return records;
382  }
383 
387  private static async Task<(long inserted, long updated, double throughput)> InsertRecordsAsync(
388  Kinetica kdb, string tableName, List<AllTypesRecord> records)
389  {
390  var ktype = KineticaType.fromTable(kdb, tableName);
391 
392  var options = new BulkInserterOptions
393  {
394  BatchSize = 500,
395  MaxInFlightBatches = 10,
396  MaxRetries = 3
397  };
398 
399  var sw = System.Diagnostics.Stopwatch.StartNew();
400 
401  await using var inserter = new BulkInserter<AllTypesRecord>(kdb, tableName, ktype, options);
402 
403  // Insert all records in one batch call
404  inserter.InsertBatch(records);
405 
406  // Close and flush all pending records
407  await inserter.CloseAsync();
408 
409  sw.Stop();
410 
411  var throughput = records.Count / (sw.Elapsed.TotalMilliseconds / 1000.0);
412 
413  // Check for errors
414  var errors = inserter.DrainErrors();
415  if (errors.Count > 0)
416  {
417  Console.WriteLine($" Warning: {errors.Count} errors occurred during insertion:");
418  foreach (var error in errors.Take(5))
419  {
420  Console.WriteLine($" - {error.Message}");
421  }
422  }
423 
424  return (inserter.CountInserted, inserter.CountUpdated, throughput);
425  }
426 
430  private static Task<IList<AllTypesRecord>> RetrieveRecordsAsync(Kinetica kdb, string tableName)
431  {
432  var response = kdb.getRecords<AllTypesRecord>(tableName, 0, Kinetica.END_OF_SET);
433  return Task.FromResult(response.data);
434  }
435 
439  private static Task<IList<AllTypesRecord>> RetrieveFilteredRecordsAsync(
440  Kinetica kdb, string tableName, string expression)
441  {
442  var options = new Dictionary<string, string>
443  {
444  [GetRecordsRequest.Options.EXPRESSION] = expression
445  };
446  var response = kdb.getRecords<AllTypesRecord>(tableName, 0, Kinetica.END_OF_SET, options);
447  return Task.FromResult(response.data);
448  }
449 
453  private static Task<IList<AllTypesRecord>> RetrieveSortedRecordsAsync(
454  Kinetica kdb, string tableName, string sortColumn, bool descending = false, int limit = 10)
455  {
456  var options = new Dictionary<string, string>
457  {
458  [GetRecordsRequest.Options.SORT_BY] = sortColumn,
459  [GetRecordsRequest.Options.SORT_ORDER] = descending ? "descending" : "ascending"
460  };
461  var response = kdb.getRecords<AllTypesRecord>(tableName, 0, limit, options);
462  return Task.FromResult(response.data);
463  }
464 
469  private static Task<IList<AllTypesRecord>> RetrieveByShardKeyAsync(
470  Kinetica kdb, string tableName, AllTypesRecord keyRecord, string? additionalExpression = null)
471  {
472  var ktype = KineticaType.fromTable(kdb, tableName);
473  var retriever = new RecordRetriever<AllTypesRecord>(kdb, tableName, ktype);
474  var response = retriever.getRecordsByKey(keyRecord, additionalExpression!);
475  return Task.FromResult(response.data);
476  }
477  }
478 }
int int8_col
8-bit integer stored as INT with INT8 property (-128 to 127)
long timestamp_col
Timestamp in milliseconds since Unix epoch (with TIMESTAMP property)
string char128_col
128-character fixed string (CHAR128)
const string CHAR1
This property provides optimized memory, disk and query performance for string columns.
static ShardKeyValue Int(int value)
Creates a 32-bit integer shard key value.
string ipv4_col
IPv4 address in format 'A.B.C.D' (IPV4 property)
string char8_col
8-character fixed string (CHAR8)
string char16_col
16-character fixed string (CHAR16)
const string DATETIME
Valid only for 'string' columns.
const string INT16
This property provides optimized memory and query performance for int columns.
const string SORT_ORDER
String indicating how the returned values should be sorted - ascending or descending.
Definition: GetRecords.cs:87
string time_col
Time in format 'HH:MM:SS.mmm' (TIME property)
const string PRIMARY_KEY
This property indicates that this column will be part of (or the entire) primary key.
const string CHAR128
This property provides optimized memory, disk and query performance for string columns.
const string BOOLEAN
This property provides optimized memory and query performance for int columns.
string char4_col
4-character fixed string (CHAR4)
CreateTableResponse createTable(CreateTableRequest request_)
Creates a new table with the given type (definition of columns).
Comprehensive example demonstrating all Kinetica supported types with:
string ulong_col
Unsigned long as string (ULONG property) - 0 to 18,446,744,073,709,551,615
A set of parameters for Kinetica.clearTable.
Definition: ClearTable.cs:19
string uuid_col
UUID stored as string (UUID property)
const string SORT_BY
Optional column that the data should be sorted by.
Definition: GetRecords.cs:70
const string EXPRESSION
Optional filter expression to apply to the table.
Definition: GetRecords.cs:46
static async Task RunAsync(string serverUrl, string username, string password)
Runs the comprehensive all-types example.
float? nullable_float_col
Nullable 32-bit floating point
string date_col
Date in format 'YYYY-MM-DD' (DATE property)
Column properties used for Kinetica types.
const string TIMESTAMP
Valid only for 'long' columns.
const string CHAR16
This property provides optimized memory, disk and query performance for string columns.
const string JSON
Valid only for 'string' columns.
High-performance bulk inserter for Kinetica with support for multi-head ingest,
Definition: BulkInserter.cs:28
float float_col
32-bit floating point
long? nullable_long_col
Nullable 64-bit integer
static KineticaType fromTable(Kinetica kinetica, string tableName)
Create a KineticaType object based on an existing table in the database.
const string WKT
Valid only for 'string' and 'bytes' columns.
long long_col
Standard 64-bit integer
double double_col
64-bit floating point
string decimal_col
Decimal number as string with DECIMAL property (NUMERIC 19,4)
const string CHAR64
This property provides optimized memory, disk and query performance for string columns.
const string CHAR4
This property provides optimized memory, disk and query performance for string columns.
const string DATE
Valid only for 'string' columns.
string char32_col
32-character fixed string (CHAR32)
const string CHAR8
This property provides optimized memory, disk and query performance for string columns.
const string DECIMAL
Valid only for 'string' columns.
string wkt_col
Well-Known Text geometry (WKT property)
string char1_col
1-character fixed string (CHAR1)
string char64_col
64-character fixed string (CHAR64)
Collection of shard key column names and values.
string? nullable_string_col
Nullable variable-length string
string char256_col
256-character fixed string (CHAR256)
A set of string constants for the parameter options.
Definition: ClearTable.cs:24
const string CHAR32
This property provides optimized memory, disk and query performance for string columns.
A set of parameters for Kinetica.getRecords.
Definition: GetRecords.cs:24
string json_col
JSON data stored as string (JSON property)
const string IPV4
This property provides optimized memory, disk and query performance for string columns representing I...
ClearTableResponse clearTable(ClearTableRequest request_)
Clears (drops) one or all tables in the database cluster.
ShardKeyValues GetShardKeyValues()
Returns shard key column names and their typed values.
Manages the insertion into GPUdb of large numbers of records in bulk, with automatic batch management...
const string CHAR256
This property provides optimized memory, disk and query performance for string columns.
int? nullable_int_col
Nullable 32-bit integer
A set of string constants for the parameter options.
Definition: GetRecords.cs:42
static KineticaType fromClass(Type recordClass, IDictionary< string, IList< string >> properties=null)
Create a KineticaType object from properties of a record class and Kinetica column properties.
string datetime_col
DateTime in format 'YYYY-MM-DD HH:MM:SS.mmm' (DATETIME property)
int int16_col
16-bit integer stored as INT with INT16 property (-32768 to 32767)
string string_col
Variable-length string (unlimited)
int bool_col
Boolean stored as INT with BOOLEAN property (0 or 1)
const string UUID
Valid only for 'string' columns.
const string INT8
This property provides optimized memory and query performance for int columns.
string create(Kinetica kinetica)
Given a handle to the server, creates a type in the database based on this data type.
A typed value for shard key computation.
int int_col
Standard 32-bit integer
double? nullable_double_col
Nullable 64-bit floating point
Failover to clusters in a random order (default)
const string ULONG
Valid only for 'string' columns.
Interface for extracting shard key values from a record.
const string NO_ERROR_IF_NOT_EXISTS
If TRUE and if the table specified in table_name does not exist no error is returned.
Definition: ClearTable.cs:40
DateTime in YYYY-MM-DD HH:MM:SS.mmm format
const string TIME
Valid only for 'string' columns.
const string NULLABLE
This property indicates that this column is nullable.
Record class demonstrating all Kinetica supported data types.
Configuration options for the BulkInserter<T>.