-
Notifications
You must be signed in to change notification settings - Fork 93
/
CustomDomainMappingAndLinq.cs
314 lines (276 loc) · 11.1 KB
/
CustomDomainMappingAndLinq.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using InfluxDB.Client;
using InfluxDB.Client.Api.Domain;
using InfluxDB.Client.Core.Flux.Domain;
using InfluxDB.Client.Linq;
using InfluxDB.Client.Writes;
namespace Examples
{
public static class CustomDomainMappingAndLinq
{
/// <summary>
/// Define Domain Object
/// </summary>
private class DomainEntity
{
public Guid SeriesId { get; set; }
public double Value { get; set; }
public DateTimeOffset Timestamp { get; set; }
public ICollection<DomainEntityAttribute> Properties { get; set; }
public override string ToString()
{
return $"{Timestamp:MM/dd/yyyy hh:mm:ss.fff tt} {SeriesId} value: {Value}, " +
$"properties: {string.Join(", ", Properties)}.";
}
}
/// <summary>
/// Attributes of DomainObject
/// </summary>
private class DomainEntityAttribute
{
public string Name { get; set; }
public int Value { get; set; }
public override string ToString()
{
return $"{Name}={Value}";
}
}
/// <summary>
/// Define Custom Domain Object Converter
/// </summary>
private class DomainEntityConverter : IDomainObjectMapper, IMemberNameResolver
{
/// <summary>
/// Convert to DomainObject.
/// </summary>
public T ConvertToEntity<T>(FluxRecord fluxRecord)
{
return (T)ConvertToEntity(fluxRecord, typeof(T));
}
public object ConvertToEntity(FluxRecord fluxRecord, Type type)
{
if (type != typeof(DomainEntity))
{
throw new NotSupportedException($"This converter doesn't supports: {typeof(DomainEntity)}");
}
var customEntity = new DomainEntity
{
SeriesId = Guid.Parse(Convert.ToString(fluxRecord.GetValueByKey("series_id"))!),
Value = Convert.ToDouble(fluxRecord.GetValueByKey("data")),
Timestamp = fluxRecord.GetTime().GetValueOrDefault().ToDateTimeUtc(),
Properties = new List<DomainEntityAttribute>()
};
foreach (var (key, value) in fluxRecord.Values)
if (key.StartsWith("property_"))
{
var attribute = new DomainEntityAttribute
{
Name = key.Replace("property_", string.Empty), Value = Convert.ToInt32(value)
};
customEntity.Properties.Add(attribute);
}
return Convert.ChangeType(customEntity, type);
}
/// <summary>
/// Convert to Point
/// </summary>
public PointData ConvertToPointData<T>(T entity, WritePrecision precision)
{
if (!(entity is DomainEntity ce))
{
throw new NotSupportedException($"This converter doesn't supports: {typeof(DomainEntity)}");
}
var point = PointData
.Measurement("custom_measurement")
.Tag("series_id", ce.SeriesId.ToString())
.Field("data", ce.Value)
.Timestamp(ce.Timestamp, precision);
foreach (var attribute in ce.Properties ?? new List<DomainEntityAttribute>())
point = point.Field($"property_{attribute.Name}", attribute.Value);
Console.WriteLine($"LP: '{point.ToLineProtocol()}'");
return point;
}
/// <summary>
/// How the Domain Object property is mapped into InfluxDB schema. Is it Timestamp, Tag, ...?
/// </summary>
public MemberType ResolveMemberType(MemberInfo memberInfo)
{
switch (memberInfo.Name)
{
case "Timestamp":
return MemberType.Timestamp;
case "Name":
return MemberType.NamedField;
case "Value":
return MemberType.NamedFieldValue;
case "SeriesId":
return MemberType.Tag;
default:
return MemberType.Field;
}
}
/// <summary>
/// How your property is named in InfluxDB.
/// </summary>
public string GetColumnName(MemberInfo memberInfo)
{
switch (memberInfo.Name)
{
case "SeriesId":
return "series_id";
case "Value":
return "data";
default:
return memberInfo.Name;
}
}
/// <summary>
/// Return name for flattened properties.
/// </summary>
public string GetNamedFieldName(MemberInfo memberInfo, object value)
{
return $"property_{Convert.ToString(value)}";
}
}
public static async Task Main()
{
const string host = "http://localhost:9999";
const string token = "my-token";
const string bucket = "my-bucket";
const string organization = "my-org";
var options = new InfluxDBClientOptions(host)
{
Token = token,
Org = organization,
Bucket = bucket
};
var converter = new DomainEntityConverter();
using var client = new InfluxDBClient(options);
//
// Prepare data to write
//
var time = new DateTimeOffset(2020, 11, 15, 8, 20, 15,
new TimeSpan(3, 0, 0));
var entity1 = new DomainEntity
{
Timestamp = time,
SeriesId = Guid.Parse("0f8fad5b-d9cb-469f-a165-70867728950e"),
Value = 15,
Properties = new List<DomainEntityAttribute>
{
new DomainEntityAttribute
{ Name = "height", Value = 4 },
new DomainEntityAttribute
{ Name = "width", Value = 110 }
}
};
var entity2 = new DomainEntity
{
Timestamp = time.AddHours(1),
SeriesId = Guid.Parse("0f8fad5b-d9cb-469f-a165-70867728950e"),
Value = 15,
Properties = new List<DomainEntityAttribute>
{
new DomainEntityAttribute
{ Name = "height", Value = 5 },
new DomainEntityAttribute
{ Name = "width", Value = 160 }
}
};
var entity3 = new DomainEntity
{
Timestamp = time.AddHours(2),
SeriesId = Guid.Parse("7c9e6679-7425-40de-944b-e07fc1f90ae7"),
Value = 15,
Properties = new List<DomainEntityAttribute>
{
new DomainEntityAttribute
{ Name = "height", Value = 5 },
new DomainEntityAttribute
{ Name = "width", Value = 110 }
}
};
var entity4 = new DomainEntity
{
Timestamp = time.AddHours(3),
SeriesId = Guid.Parse("7c9e6679-7425-40de-944b-e07fc1f90ae7"),
Value = 15,
Properties = new List<DomainEntityAttribute>
{
new DomainEntityAttribute
{ Name = "height", Value = 6 },
new DomainEntityAttribute
{ Name = "width", Value = 160 }
}
};
//
// Write data
//
await client.GetWriteApiAsync(converter)
.WriteMeasurementsAsync(new[] { entity1, entity2, entity3, entity4 }, WritePrecision.S);
//
// Query Data to Domain object
//
var queryApi = client.GetQueryApiSync(converter);
//
// Select ALL
//
var query = from s in InfluxDBQueryable<DomainEntity>.Queryable("my-bucket", "my-org", queryApi, converter)
select s;
Console.WriteLine("==== Select ALL ====");
query.ToList().ForEach(it => Console.WriteLine(it.ToString()));
//
// Filter By Tag
//
query = from s in InfluxDBQueryable<DomainEntity>.Queryable("my-bucket", "my-org", queryApi, converter)
where s.SeriesId == Guid.Parse("7c9e6679-7425-40de-944b-e07fc1f90ae7")
select s;
Console.WriteLine("==== Filter by Tag ====");
query.ToList().ForEach(it => Console.WriteLine(it.ToString()));
//
// Use Take + Skip
//
query = (from s in InfluxDBQueryable<DomainEntity>.Queryable("my-bucket", "my-org", queryApi, converter)
select s)
.Take(1)
.Skip(1);
Console.WriteLine("==== Use Take + Skip ====");
query.ToList().ForEach(it => Console.WriteLine(it.ToString()));
//
// Use Time Range
//
query = from s in InfluxDBQueryable<DomainEntity>.Queryable("my-bucket", "my-org", queryApi, converter)
where s.Timestamp > time.AddMinutes(30) && s.Timestamp < time.AddHours(3)
select s;
Console.WriteLine("==== Use Time Range ====");
query.ToList().ForEach(it => Console.WriteLine(it.ToString()));
//
// Use Any
//
query = from s in InfluxDBQueryable<DomainEntity>.Queryable("my-bucket", "my-org", queryApi, converter)
where s.Properties.Any(a => a.Name == "width" && a.Value == 160)
select s;
Console.WriteLine("==== Use Any ====");
query.ToList().ForEach(it => Console.WriteLine(it.ToString()));
//
// Debug Query
//
Console.WriteLine("==== Debug LINQ Queryable Flux output ====");
var influxQuery = ((InfluxDBQueryable<DomainEntity>)query).ToDebugQuery();
foreach (var statement in influxQuery.Extern.Body)
{
var os = statement as OptionStatement;
var va = os?.Assignment as VariableAssignment;
var name = va?.Id.Name;
var value = va?.Init.GetType().GetProperty("Value")?.GetValue(va.Init, null);
Console.WriteLine($"{name}={value}");
}
Console.WriteLine();
Console.WriteLine(influxQuery._Query);
}
}
}