cognite-sdk 0.6.2

SDK for the Cognite Data Fusion API
Documentation
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
use std::collections::HashMap;

use derivative::Derivative;
use serde::{Deserialize, Serialize};
use serde_with::skip_serializing_none;

use crate::{
    models::{ItemId, PropertySort, SourceReference, TaggedViewReference},
    AdvancedFilter, RawValue, SetCursor,
};

use super::views::ViewCorePropertyType;
mod extensions;
pub use extensions::*;

#[skip_serializing_none]
#[derive(Serialize, Deserialize, Derivative, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// A list of nodes and edges to create. Parametrized by the type used for
/// instance properties.
pub struct NodeAndEdgeCreateCollection<TProperties> {
    /// Nodes and edges to create.
    pub items: Vec<NodeOrEdgeCreate<TProperties>>,
    /// Whether to auto create direct relations that do not exist.
    pub auto_create_direct_relations: Option<bool>,
    /// Whether to auto create start nodes that do not exist.
    pub auto_create_start_nodes: Option<bool>,
    /// Whether to auto create end nodes that do not exist.
    pub auto_create_end_nodes: Option<bool>,
    /// If `existing_version` is specified on any of the nodes/edges in the input,
    /// the default behaviour is that the entire ingestion will fail when
    /// version conflicts occur. If `skip_on_version_conflict` is set to true,
    /// items with version conflicts will be skipped instead. If no version is
    /// specified for nodes/edges, it will do the write directly.
    pub skip_on_version_conflict: Option<bool>,
    /// How do we behave when a property value exists?
    /// Do we replace all matching and existing values with the supplied values (true)?
    /// Or should we merge in new values for properties together with the existing values (false)?
    /// Note: This setting applies for all nodes or edges specified in the ingestion call.
    pub replace: Option<bool>,
}

impl<TProperties> Default for NodeAndEdgeCreateCollection<TProperties> {
    fn default() -> Self {
        Self {
            items: vec![],
            auto_create_direct_relations: None,
            auto_create_start_nodes: None,
            auto_create_end_nodes: None,
            skip_on_version_conflict: None,
            replace: None,
        }
    }
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase", tag = "instanceType")]
/// Enum of instance types being created.
pub enum NodeOrEdgeCreate<TProperties> {
    /// Create a node.
    Node(NodeWrite<TProperties>),
    /// Create an edge.
    Edge(EdgeWrite<TProperties>),
}

#[skip_serializing_none]
#[derive(Serialize, Deserialize, Default, Derivative, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// Node to create.
pub struct NodeWrite<TProperties> {
    /// Node space.
    pub space: String,
    /// Node external ID.
    pub external_id: String,
    /// List of properties in various containers or views.
    pub sources: Option<Vec<EdgeOrNodeData<TProperties>>>,
    /// Fail the ingestion request if the node's version is greater than or equal to this value.
    /// If no `existing_version` is specified, the ingestion will always overwrite any existing
    /// data for the node (for the specified container or view). If `existing_version` is
    /// set to 0, the upsert will behave as an insert, so it will fail the bulk if the
    /// item already exists. If skipOnVersionConflict is set on the ingestion request,
    /// then the item will be skipped instead of failing the ingestion request.
    pub existing_version: Option<i32>,
    /// Node type (direct relation).
    pub r#type: Option<InstanceId>,
}

#[skip_serializing_none]
#[derive(Serialize, Deserialize, Default, Derivative, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// Edge to create.
pub struct EdgeWrite<TProperties> {
    /// Edge space.
    pub space: String,
    /// Edge type (direct relation).
    pub r#type: InstanceId,
    /// Edge external ID.
    pub external_id: String,
    /// Edge start node.
    pub start_node: InstanceId,
    /// Edge end node.
    pub end_node: InstanceId,
    /// List of properties in various containers or views.
    pub sources: Option<Vec<EdgeOrNodeData<TProperties>>>,
    /// Fail the ingestion request if the edge's version is greater than or equal to this value.
    /// If no `existing_version` is specified, the ingestion will always overwrite any existing
    /// data for the edge (for the specified container or view). If `existing_version` is
    /// set to 0, the upsert will behave as an insert, so it will fail the bulk if the
    /// item already exists. If skipOnVersionConflict is set on the ingestion request,
    /// then the item will be skipped instead of failing the ingestion request.
    pub existing_version: Option<i32>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
/// Data in a single container or view for an edge or a node.
pub struct EdgeOrNodeData<TProperties> {
    /// Reference to the container or view this data belongs to.
    pub source: SourceReference,
    /// Property values on the form `{ property_name: value, ... }`
    pub properties: TProperties,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase", tag = "instanceType")]
/// Minimal representation of a node or edge.
pub enum SlimNodeOrEdge {
    /// Slim node
    Node(SlimNodeDefinition),
    /// Slim edge
    Edge(SlimEdgeDefinition),
}

#[skip_serializing_none]
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// Minimal representation of a node.
pub struct SlimNodeDefinition {
    /// Node space.
    pub space: String,
    /// Node version.
    pub version: i32,
    /// Whether or not the node was midified by this ingestion. We only
    /// update nodes if the input differs from the existing state.
    pub was_modified: bool,
    /// Node external ID.
    pub external_id: String,
    /// Time this node was created, in milliseconds since epoch.
    pub created_time: Option<i64>,
    /// Time this node was last modified, in milliseconds since epoch.
    pub last_updated_time: Option<i64>,
}
#[skip_serializing_none]
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// Minimal representation of an edge.
pub struct SlimEdgeDefinition {
    /// Edge space.
    pub space: String,
    /// Edge version.
    pub version: i32,
    /// Whether or not the edge was midified by this ingestion. We only
    /// update nodes if the input differs from the existing state.
    pub was_modified: bool,
    /// Edge external ID.
    pub external_id: String,
    /// Time this edge was created, in milliseconds since epoch.
    pub created_time: Option<i64>,
    /// Time this edge was last modified, in milliseconds since epoch.
    pub last_updated_time: Option<i64>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase", tag = "instanceType")]
/// Node or edge with properties.
pub enum NodeOrEdge<TProperties> {
    /// Full node.
    Node(NodeDefinition<TProperties>),
    /// Full edge.
    Edge(EdgeDefinition<TProperties>),
}

#[skip_serializing_none]
#[derive(Serialize, Deserialize, Derivative, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// Representation of a node with properties.
pub struct NodeDefinition<TProperties> {
    /// Node space.
    pub space: String,
    /// Node version.
    pub version: i32,
    /// Node external ID.
    pub external_id: String,
    /// Node type.
    pub r#type: Option<InstanceId>,
    /// Time this node was created, in milliseconds since epoch.
    pub created_time: i64,
    /// Time this node was last modified, in milliseconds since epoch.
    pub last_updated_time: i64,
    /// Timestamp when the node was soft deleted. Note that deleted nodes are
    /// filtered out of query results, but present in sync results.
    /// This means that this value will only be present in sync results.
    pub deleted_time: Option<i64>,
    /// Node properties.
    pub properties: Option<PropertiesObject<TProperties>>,
}

#[skip_serializing_none]
#[derive(Serialize, Deserialize, Derivative, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// Representation of an edge with properties.
pub struct EdgeDefinition<TProperties> {
    /// Edge space.
    pub space: String,
    /// Edge type.
    pub r#type: InstanceId,
    /// Edge version.
    pub version: i32,
    /// Edge external ID.
    pub external_id: String,
    /// Time this edge was created, in milliseconds since epoch.
    pub created_time: i64,
    /// Time this edge was last modified, in milliseconds since epoch.
    pub last_updated_time: i64,
    /// Edge start node.
    pub start_node: InstanceId,
    /// Edge end node.
    pub end_node: InstanceId,
    /// Timestamp when the edge was soft deleted. Note that deleted nodes are
    /// filtered out of query results, but present in sync results.
    /// This means that this value will only be present in sync results.
    pub deleted_time: Option<i64>,
    /// Edge properties.
    pub properties: Option<PropertiesObject<TProperties>>,
}

/// Shorthand for map from space and view/container external ID to properties object.
pub type PropertiesObject<TProperties> = HashMap<String, HashMap<String, TProperties>>;

#[derive(Serialize, Deserialize, Default, Clone, Debug, Hash, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
/// Direct reference to a node.
pub struct InstanceId {
    /// Node space.
    pub space: String,
    /// Node external ID.
    pub external_id: String,
}

impl PartialEq<crate::time_series::InstanceId> for InstanceId {
    fn eq(&self, other: &crate::time_series::InstanceId) -> bool {
        self.space == other.space && self.external_id == other.external_id
    }
}

impl PartialEq<InstanceId> for crate::time_series::InstanceId {
    fn eq(&self, other: &InstanceId) -> bool {
        self.space == other.space && self.external_id == other.external_id
    }
}

#[skip_serializing_none]
#[derive(Serialize, Deserialize, Derivative, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// Request for retrieving nodes or edges by ID.
pub struct NodeAndEdgeRetrieveRequest {
    /// List of sources to include properties from.
    pub sources: Option<Vec<SourceReferenceInternal>>,
    /// List of node or edge IDs to retrieve.
    pub items: Vec<NodeOrEdgeSpecification>,
    #[derivative(Default(value = "false"))]
    /// Whether to include type information in the response.
    pub include_typing: Option<bool>,
}

#[derive(Serialize, Deserialize, Derivative, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// Wrapped reference to a view.
pub struct SourceReferenceInternal {
    /// View ID.
    pub source: TaggedViewReference,
}

#[skip_serializing_none]
#[derive(Serialize, Deserialize, Derivative, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// Response for retrieving nodes and edges.
pub struct NodeAndEdgeRetrieveResponse<TProperties> {
    /// Retrieved nodes and edges.
    pub items: Vec<NodeOrEdge<TProperties>>,
    /// Type information if requested.
    pub typing: Option<TypeInformation>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase", tag = "instanceType")]
/// ID of a node or an edge.
pub enum NodeOrEdgeSpecification {
    /// Node ID.
    Node(ItemId),
    /// Edge ID.
    Edge(ItemId),
}

#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
/// Enum over instance types.
pub enum InstanceType {
    /// Node instances.
    #[default]
    Node,
    /// Edge instances.
    Edge,
}

#[skip_serializing_none]
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
/// Request for filtering instances.
pub struct FilterInstancesRequest {
    /// Whether to include type information in the response.
    pub include_typing: Option<bool>,
    /// List of sources to retrieve data from.
    pub sources: Option<Vec<SourceReferenceInternal>>,
    /// Type of instances to filter.
    pub instance_type: InstanceType,
    /// Optional cursor for pagination.
    pub cursor: Option<String>,
    /// Maximum number of instances to retrieve. Default 1000, maximum 1000.
    pub limit: Option<i32>,
    /// Optional list of properties to sort the result by.
    pub sort: Option<Vec<PropertySort>>,
    /// Optional filter.
    pub filter: Option<AdvancedFilter>,
}

impl SetCursor for FilterInstancesRequest {
    fn set_cursor(&mut self, cursor: Option<String>) {
        self.cursor = cursor;
    }
}

#[skip_serializing_none]
#[derive(Serialize, Deserialize, Derivative, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// Defintion of a property in type information.
pub struct TypePropertyDefinition {
    /// Whether the property is nullable.
    pub nullable: Option<bool>,
    /// Whether the property auto increments.
    pub auto_increment: Option<bool>,
    /// Property default value.
    pub default_value: Option<RawValue>,
    /// Description of the content and suggested use for this property.
    pub description: Option<String>,
    /// Readable property name.
    pub name: Option<String>,
    /// The data-type to use when storing the property.
    pub r#type: ViewCorePropertyType,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// Type information retrieved when doing filter or retrieve requests and setting
/// `include_typing` to `true`.
///
/// Map from space to view/container to property.
pub struct TypeInformation(
    HashMap<String, HashMap<String, HashMap<String, TypePropertyDefinition>>>,
);

impl TypeInformation {
    /// Get information about a property by space, view/container external ID,
    /// and property name, if it is present in the type information.
    pub fn get_property_info(
        &self,
        space: &str,
        view_or_container: &str,
        property: &str,
    ) -> Option<&TypePropertyDefinition> {
        self.0.get(space)?.get(view_or_container)?.get(property)
    }
}

#[skip_serializing_none]
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// Response when filtering instances.
pub struct InstancesFilterResponse<TProperties> {
    /// List of retrieved nodes and edges.
    pub items: Vec<NodeOrEdge<TProperties>>,
    /// Type information if requested.
    pub typing: Option<TypeInformation>,
    /// Cursor for pagination.
    pub next_cursor: Option<String>,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")]
/// Requested aggregate on instances.
pub enum InstancesAggregate {
    /// Average of values of specified property.
    Avg {
        /// Numerical property to compute average of.
        property: String,
    },
    /// Counts the number of items. When you specify a property,
    /// it returns the number of non-null values for that property.
    Count {
        /// The property to count. If specified, counts non-null values.
        property: Option<String>,
    },
    /// Calculate the lowest value for a numerical property.
    Min {
        /// Numerical property to compute minimum value for.
        property: String,
    },
    /// Calculate the highest value for a numerical property.
    Max {
        /// Numerical proeprty to compute maximum value for.
        property: String,
    },
    /// Calculate the sum of values for a numerical property.
    Sum {
        /// Numerical property to compute sum for.
        property: String,
    },
    /// A histogram aggregator function. This function will generate a histogram from the values of
    /// the specified property. It uses the specified interval as defined in your interval argument.
    Histogram {
        /// Numerical property to compute histogram for.
        property: String,
        /// Interval between each bucket.
        interval: f64,
    },
}

#[skip_serializing_none]
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// Request for aggregating accross instances.
pub struct AggregateInstancesRequest {
    /// Optional query string. The API will parse the query string,
    /// and use it to match the text properties on elements to use for the aggregate(s).
    pub query: Option<String>,
    /// Optional list of properties to apply the `query` to. If no properties are listed,
    /// text fields are searched by default.
    pub properties: Option<Vec<String>>,
    /// Maximum number of results to return. The default is 100, maximum is 1000.
    pub limit: Option<i32>,
    /// List of aggregates to calculate.
    pub aggregates: Option<Vec<InstancesAggregate>>,
    /// The selection of fields to group the results by when doing aggregations.
    ///
    /// When you do not specify any aggregates. The fields in the `groupBy` clause will
    /// return the unique values stored for each field.
    pub group_by: Option<Vec<String>>,
    /// Optional filter on nodes or edges.
    pub filter: Option<AdvancedFilter>,
    /// Instance type to aggregate accross.
    pub instance_type: InstanceType,
    /// Reference to a view to query.
    pub view: TaggedViewReference,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(untagged)]
/// Value of an aggregate group.
pub enum AggregateGroupValue {
    /// String value.
    String(String),
    /// Numerical value.
    Number(f64),
    /// Boolean value.
    Boolean(bool),
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// Result of a numerical aggregate.
pub struct NumericAggregateResult {
    /// Aggregated property.
    pub property: String,
    /// Aggregate value.
    pub value: f64,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// Result of a count aggregate.
pub struct CountAggregateResult {
    /// Aggregated property.
    pub property: Option<String>,
    /// Aggregate value.
    pub value: f64,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// A single bucket in a histogram aggregate.
pub struct HistogramBucket {
    /// Start value of bucket.
    pub start: f64,
    /// Number of values in bucket.
    pub count: u64,
}

#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase", rename_all_fields = "camelCase")]
/// Result item in instances aggregate response.
pub enum AggregateResult {
    /// Result of average aggregate.
    Avg(NumericAggregateResult),
    /// Result of min aggregate.
    Min(NumericAggregateResult),
    /// Result of max aggregate.
    Max(NumericAggregateResult),
    /// Result of count aggregate.
    Count(CountAggregateResult),
    /// Result of sum aggregate.
    Sum(NumericAggregateResult),
    /// Result of histogram aggregate.
    Histogram {
        /// Histogram interval.
        interval: f64,
        /// Aggregate property.
        property: String,
        /// List of buckets with start and count.
        buckets: Vec<HistogramBucket>,
    },
}

#[skip_serializing_none]
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// A single item in the result of an instances aggregate request.
pub struct AggregateResultItem {
    /// Type of instance aggregated.
    pub instance_type: InstanceType,
    /// Value of group in aggregate.
    pub group: Option<HashMap<String, AggregateGroupValue>>,
    /// List of computed aggregates for this group.
    pub aggregates: Vec<AggregateResult>,
}

#[skip_serializing_none]
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// Result when aggregating instances.
pub struct AggregateInstancesResponse {
    /// Computed aggregates.
    pub items: Vec<AggregateResultItem>,
    /// Type information if requested.
    pub typing: Option<TypeInformation>,
}

#[skip_serializing_none]
#[derive(Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
/// Query for searching text fields for nodes or edges.
pub struct SearchInstancesRequest {
    /// View to search in.
    pub view: TaggedViewReference,
    /// Query string that will be parsed for search.
    pub query: Option<String>,
    /// Instance type to search.
    pub instance_type: InstanceType,
    /// List of properties to search through. If you do not specify one
    /// or more properties, the service will search all text fields
    /// in the view.
    pub properties: Option<Vec<String>>,
    /// Optional advanced filter.
    pub filter: Option<AdvancedFilter>,
    /// Maximum number of results to return. Default 1000, maximum 1000.
    pub limit: Option<i32>,
}