-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathinstances.py
More file actions
2134 lines (1873 loc) · 98.9 KB
/
Copy pathinstances.py
File metadata and controls
2134 lines (1873 loc) · 98.9 KB
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import asyncio
import inspect
import logging
import random
from collections.abc import AsyncIterator, Awaitable, Callable, Iterable, Sequence
from datetime import datetime, timedelta, timezone
from typing import (
TYPE_CHECKING,
Any,
Generic,
Literal,
TypeAlias,
cast,
overload,
)
from cognite.client._api_client import APIClient
from cognite.client.constants import DEFAULT_LIMIT_READ
from cognite.client.data_classes import filters
from cognite.client.data_classes._base import CogniteResourceList, WriteableCogniteResource
from cognite.client.data_classes.aggregations import (
AggregatedNumberedValue,
Aggregation,
Histogram,
HistogramValue,
MetricAggregation,
)
from cognite.client.data_classes.data_modeling.ids import (
EdgeId,
NodeId,
ViewId,
_load_identifier,
)
from cognite.client.data_classes.data_modeling.instances import (
Edge,
EdgeApply,
EdgeApplyResult,
EdgeApplyResultList,
EdgeList,
InstanceAggregationResultList,
InstanceInspectResultList,
InstanceInspectResults,
InstancesApplyResult,
InstancesDeleteResult,
InstanceSort,
InstancesResult,
InvolvedContainers,
InvolvedViews,
Node,
NodeApply,
NodeApplyResult,
NodeApplyResultList,
NodeList,
T_Edge,
T_Node,
TargetUnit,
TypedEdge,
TypedInstance,
TypedNode,
TypeInformation,
)
from cognite.client.data_classes.data_modeling.query import (
Query,
QueryBase,
QueryResult,
QuerySync,
SourceSelector,
)
from cognite.client.data_classes.data_modeling.sync import SubscriptionContext, SyncSessionWithCache
from cognite.client.data_classes.data_modeling.views import View
from cognite.client.data_classes.filters import _BASIC_FILTERS, Filter, _validate_filter
from cognite.client.utils._auxiliary import at_least_one_is_not_none, is_unlimited, load_yaml_or_json, unpack_items
from cognite.client.utils._experimental import FeaturePreviewWarning
from cognite.client.utils._identifier import DataModelingIdentifierSequence
from cognite.client.utils._retry import Backoff
from cognite.client.utils._text import random_string
from cognite.client.utils.useful_types import SequenceNotStr
if TYPE_CHECKING:
from cognite.client import AsyncCogniteClient, ClientConfig
from cognite.client.data_classes.data_modeling.debug import DebugParameters
_FILTERS_SUPPORTED: frozenset[type[Filter]] = _BASIC_FILTERS.union(
{filters.Nested, filters.HasData, filters.MatchAll, filters.Overlaps, filters.InstanceReferences}
)
logger = logging.getLogger(__name__)
Source: TypeAlias = SourceSelector | View | ViewId | tuple[str, str] | tuple[str, str, str]
class _NodeOrEdgeResourceAdapter(Generic[T_Node, T_Edge]):
def __init__(self, node_cls: type[T_Node], edge_cls: type[T_Edge]):
self._node_cls = node_cls
self._edge_cls = edge_cls
def _load(self, data: str | dict) -> T_Node | T_Edge:
data = load_yaml_or_json(data) if isinstance(data, str) else data
if data["instanceType"] == "node":
return self._node_cls._load(data) # type: ignore[return-value]
return self._edge_cls._load(data)
class _TypedNodeOrEdgeListAdapter:
def __init__(self, instance_cls: type[TypedInstance]) -> None:
self._instance_cls = instance_cls
self._list_cls = NodeList if issubclass(instance_cls, TypedNode) else EdgeList
def __call__(self, items: Any) -> Any:
return self._list_cls(items)
def _load(self, data: str | dict) -> T_Node | T_Edge:
data = load_yaml_or_json(data) if isinstance(data, str) else data
return self._list_cls([self._instance_cls._load(item) for item in data]) # type: ignore[return-value, attr-defined]
def _load_raw_api_response(self, responses: list[dict[str, Any]]) -> T_Node | T_Edge:
from cognite.client.data_classes.data_modeling.debug import DebugInfo
typing = next((TypeInformation._load(resp["typing"]) for resp in responses if "typing" in resp), None)
debug = next((DebugInfo._load(r["debug"]) for r in responses if "debug" in r), None)
resources = [
self._instance_cls._load(item) # type: ignore[attr-defined]
for response in responses
for item in response["items"]
]
return self._list_cls(resources, typing, debug) # type: ignore[return-value]
class _NodeOrEdgeApplyResultList(CogniteResourceList):
_RESOURCE = (NodeApplyResult, EdgeApplyResult) # type: ignore[assignment]
@classmethod
def _load(cls, resource_list: Iterable[dict[str, Any]] | str) -> _NodeOrEdgeApplyResultList:
resource_list = load_yaml_or_json(resource_list) if isinstance(resource_list, str) else resource_list
resources: list[NodeApplyResult | EdgeApplyResult] = [
NodeApplyResult._load(data) if data["instanceType"] == "node" else EdgeApplyResult._load(data)
for data in resource_list
]
return cls(resources)
def as_ids(self) -> list[NodeId | EdgeId]:
return [result.as_id() for result in self]
class _NodeOrEdgeApplyResultAdapter:
@staticmethod
def load(data: str | dict) -> NodeApplyResult | EdgeApplyResult:
data = load_yaml_or_json(data) if isinstance(data, str) else data
if data["instanceType"] == "node":
return NodeApplyResult._load(data)
return EdgeApplyResult._load(data)
class _NodeOrEdgeApplyAdapter:
@staticmethod
def _load(data: dict) -> NodeApply | EdgeApply:
if data["instanceType"] == "node":
return NodeApply._load(data)
return EdgeApply._load(data)
class InstancesAPI(APIClient):
_RESOURCE_PATH = "/models/instances"
def __init__(self, config: ClientConfig, api_version: str | None, cognite_client: AsyncCogniteClient) -> None:
super().__init__(config, api_version, cognite_client)
self._AGGREGATE_LIMIT = 1000
self._SEARCH_LIMIT = 1000
self._warn_on_alpha_debug_settings = FeaturePreviewWarning(
api_maturity="alpha",
sdk_maturity="alpha",
feature_name="Data modeling debug parameters 'includeTranslatedQuery' and 'includePlan'",
pluralize=True,
)
self._warn_on_sync_with_file_cache = FeaturePreviewWarning(
api_maturity="General Availability",
sdk_maturity="alpha",
feature_name="Sync sessions with file caching for the Instances API",
pluralize=False,
)
def _get_semaphore(self, operation: Literal["read", "write", "delete", "search"]) -> asyncio.BoundedSemaphore:
from cognite.client import global_config
assert operation not in ("read_schema", "write_schema"), "Instances API should not use schema semaphores"
return global_config.concurrency_settings.data_modeling._semaphore_factory(
operation, project=self._cognite_client.config.project
)
@overload
def __call__(
self,
chunk_size: None = None,
instance_type: Literal["node"] = "node",
limit: int | None = None,
include_typing: bool = False,
sources: Source | Sequence[Source] | None = None,
space: str | SequenceNotStr[str] | None = None,
sort: list[InstanceSort | dict] | InstanceSort | dict | None = None,
filter: Filter | dict[str, Any] | None = None,
debug: DebugParameters | None = None,
) -> AsyncIterator[Node]: ...
@overload
def __call__(
self,
chunk_size: None,
instance_type: Literal["edge"],
limit: int | None = None,
include_typing: bool = False,
sources: Source | Sequence[Source] | None = None,
space: str | SequenceNotStr[str] | None = None,
sort: list[InstanceSort | dict] | InstanceSort | dict | None = None,
filter: Filter | dict[str, Any] | None = None,
debug: DebugParameters | None = None,
) -> AsyncIterator[Edge]: ...
@overload
def __call__(
self,
chunk_size: int,
instance_type: Literal["node"] = "node",
limit: int | None = None,
include_typing: bool = False,
sources: Source | Sequence[Source] | None = None,
space: str | SequenceNotStr[str] | None = None,
sort: list[InstanceSort | dict] | InstanceSort | dict | None = None,
filter: Filter | dict[str, Any] | None = None,
debug: DebugParameters | None = None,
) -> AsyncIterator[NodeList]: ...
@overload
def __call__(
self,
chunk_size: int,
instance_type: Literal["edge"],
limit: int | None = None,
include_typing: bool = False,
sources: Source | Sequence[Source] | None = None,
space: str | SequenceNotStr[str] | None = None,
sort: list[InstanceSort | dict] | InstanceSort | dict | None = None,
filter: Filter | dict[str, Any] | None = None,
debug: DebugParameters | None = None,
) -> AsyncIterator[EdgeList]: ...
async def __call__(
self,
chunk_size: int | None = None,
instance_type: Literal["node", "edge"] = "node",
limit: int | None = None,
include_typing: bool = False,
sources: Source | Sequence[Source] | None = None,
space: str | SequenceNotStr[str] | None = None,
sort: list[InstanceSort | dict] | InstanceSort | dict | None = None,
filter: Filter | dict[str, Any] | None = None,
debug: DebugParameters | None = None,
) -> AsyncIterator[Edge | EdgeList | Node | NodeList]:
"""Iterate over nodes or edges.
Fetches instances as they are iterated over, so you keep a limited number of instances in memory.
Args:
chunk_size (int | None): Number of data_models to return in each chunk. Defaults to yielding one instance at a time.
instance_type (Literal['node', 'edge']): Whether to query for nodes or edges.
limit (int | None): Maximum number of instances to return. Defaults to returning all items.
include_typing (bool): Whether to return property type information as part of the result.
sources (Source | Sequence[Source] | None): Views to retrieve properties from.
space (str | SequenceNotStr[str] | None): Only return instances in the given space (or list of spaces).
sort (list[InstanceSort | dict] | InstanceSort | dict | None): Sort(s) to apply to the returned instances. For nontrivial amounts of data, you need to have a backing, cursorable index.
filter (Filter | dict[str, Any] | None): Advanced filtering of instances.
debug (DebugParameters | None): Debug settings for profiling and troubleshooting.
Yields:
Edge | EdgeList | Node | NodeList: yields Instance one by one if chunk_size is not specified, else NodeList/EdgeList objects.
"""
self._validate_filter(filter)
filter = self._merge_space_into_filter(instance_type, space, filter)
other_params = self._create_other_params(
include_typing=include_typing, instance_type=instance_type, sort=sort, sources=sources, debug=debug
)
match instance_type:
case "node":
resource_cls: type[Node | Edge] = Node
list_cls: type[NodeList | EdgeList] = NodeList
case "edge":
resource_cls, list_cls = Edge, EdgeList
case _:
raise ValueError(f"Invalid instance type: {instance_type}")
headers: None | dict[str, str] = None
settings_forcing_raw_response_loading = []
if include_typing:
settings_forcing_raw_response_loading.append(f"{include_typing=}")
if debug:
settings_forcing_raw_response_loading.append(f"{debug=}")
if debug.requires_alpha_header:
self._warn_on_alpha_debug_settings.warn()
headers = {"cdf-version": f"{self._config.api_subversion}-alpha"}
if not settings_forcing_raw_response_loading:
async for item in self._list_generator(
list_cls=list_cls,
resource_cls=resource_cls,
method="POST",
chunk_size=chunk_size,
limit=limit,
filter=filter.dump(camel_case_property=False) if isinstance(filter, Filter) else filter,
other_params=other_params,
headers=headers,
):
yield item
return
async for raw in self._list_generator_raw_responses(
method="POST",
settings_forcing_raw_response_loading=settings_forcing_raw_response_loading,
chunk_size=chunk_size,
limit=limit,
filter=filter.dump(camel_case_property=False) if isinstance(filter, Filter) else filter,
other_params=other_params,
headers=headers,
):
yield list_cls._load_raw_api_response([raw])
@overload
async def retrieve_edges(
self,
edges: EdgeId | tuple[str, str],
*,
edge_cls: type[T_Edge],
) -> T_Edge | None: ...
@overload
async def retrieve_edges(
self,
edges: EdgeId | tuple[str, str],
*,
sources: Source | Sequence[Source] | None = None,
include_typing: bool = False,
) -> Edge | None: ...
@overload
async def retrieve_edges(
self,
edges: Sequence[EdgeId] | Sequence[tuple[str, str]],
*,
edge_cls: type[T_Edge],
) -> EdgeList[T_Edge]: ...
@overload
async def retrieve_edges(
self,
edges: Sequence[EdgeId] | Sequence[tuple[str, str]],
*,
sources: Source | Sequence[Source] | None = None,
include_typing: bool = False,
) -> EdgeList[Edge]: ...
async def retrieve_edges(
self,
edges: EdgeId | Sequence[EdgeId] | tuple[str, str] | Sequence[tuple[str, str]],
edge_cls: type[T_Edge] = Edge, # type: ignore [assignment]
sources: Source | Sequence[Source] | None = None,
include_typing: bool = False,
) -> EdgeList[T_Edge] | T_Edge | Edge | None:
"""`Retrieve one or more edges by id(s) <https://api-docs.cognite.com/20230101/tag/Instances/operation/byExternalIdsInstances>`_.
Note:
This method should be used for retrieving edges with a custom edge class. You can use it
without providing a custom edge class, but in that case, the retrieved edges will be of the
built-in Edge class.
Args:
edges (EdgeId | Sequence[EdgeId] | tuple[str, str] | Sequence[tuple[str, str]]): Edge id(s) to retrieve.
edge_cls (type[T_Edge]): The custom edge class to use, the retrieved edges will automatically be serialized into this class.
sources (Source | Sequence[Source] | None): Retrieve properties from the listed - by reference - views. This only applies if you do not provide a custom edge class.
include_typing (bool): Whether to include typing information
Returns:
EdgeList[T_Edge] | T_Edge | Edge | None: The requested edges.
Examples:
Retrieve edges using a custom typed class "Flow". Any property that you want to look up by a different attribute name,
e.g. you want `my_edge.flow_rate` to return the data for property `flowRate`, must use the PropertyOptions as shown below.
We strongly suggest you use snake_cased attribute names, as is done here:
>>> from cognite.client import CogniteClient
>>> from cognite.client.data_classes.data_modeling import (
... EdgeId,
... TypedEdge,
... PropertyOptions,
... DirectRelationReference,
... ViewId,
... )
>>> class Flow(TypedEdge):
... flow_rate = PropertyOptions(identifier="flowRate")
...
... def __init__(
... self,
... space: str,
... external_id: str,
... version: int,
... type: DirectRelationReference,
... last_updated_time: int,
... created_time: int,
... flow_rate: float,
... start_node: DirectRelationReference,
... end_node: DirectRelationReference,
... deleted_time: int | None = None,
... ) -> None:
... super().__init__(
... space,
... external_id,
... version,
... type,
... last_updated_time,
... created_time,
... start_node,
... end_node,
... deleted_time,
... )
... self.flow_rate = flow_rate
...
... @classmethod
... def get_source(cls) -> ViewId:
... return ViewId("sp_model_space", "flow", "1")
>>> client = CogniteClient()
>>> # async_client = AsyncCogniteClient() # another option
>>> res = client.data_modeling.instances.retrieve_edges(
... EdgeId("mySpace", "theFlow"), edge_cls=Flow
... )
>>> isinstance(res, Flow)
"""
res = await self._retrieve_typed(
nodes=None, edges=edges, node_cls=Node, edge_cls=edge_cls, sources=sources, include_typing=include_typing
)
if isinstance(edges, EdgeId) or (isinstance(edges, tuple) and all(isinstance(i, str) for i in edges)):
return res.edges[0] if res.edges else None
return res.edges
@overload
async def retrieve_nodes(
self,
nodes: NodeId | tuple[str, str],
*,
node_cls: type[T_Node],
) -> T_Node | None: ...
@overload
async def retrieve_nodes(
self,
nodes: NodeId | tuple[str, str],
*,
sources: Source | Sequence[Source] | None = None,
include_typing: bool = False,
) -> Node | None: ...
@overload
async def retrieve_nodes(
self,
nodes: Sequence[NodeId] | Sequence[tuple[str, str]],
*,
node_cls: type[T_Node],
) -> NodeList[T_Node]: ...
@overload
async def retrieve_nodes(
self,
nodes: Sequence[NodeId] | Sequence[tuple[str, str]],
*,
sources: Source | Sequence[Source] | None = None,
include_typing: bool = False,
) -> NodeList[Node]: ...
async def retrieve_nodes(
self,
nodes: NodeId | Sequence[NodeId] | tuple[str, str] | Sequence[tuple[str, str]],
node_cls: type[T_Node] = Node, # type: ignore
sources: Source | Sequence[Source] | None = None,
include_typing: bool = False,
) -> NodeList[T_Node] | T_Node | Node | None:
"""`Retrieve one or more nodes by id(s) <https://api-docs.cognite.com/20230101/tag/Instances/operation/byExternalIdsInstances>`_.
Note:
This method should be used for retrieving nodes with a custom node class. You can use it
without providing a custom node class, but in that case, the retrieved nodes will be of the
built-in Node class.
Args:
nodes (NodeId | Sequence[NodeId] | tuple[str, str] | Sequence[tuple[str, str]]): Node id(s) to retrieve.
node_cls (type[T_Node]): The custom node class to use, the retrieved nodes will automatically be serialized to this class.
sources (Source | Sequence[Source] | None): Retrieve properties from the listed - by reference - views. This only applies if you do not provide a custom node class.
include_typing (bool): Whether to include typing information
Returns:
NodeList[T_Node] | T_Node | Node | None: The requested edges.
Examples:
Retrieve nodes using a custom typed node class "Person". Any property that you want to look up by a different attribute name,
e.g. you want `my_node.birth_year` to return the data for property `birthYear`, must use the PropertyOptions as shown below.
We strongly suggest you use snake_cased attribute names, as is done here:
>>> from cognite.client import CogniteClient
>>> from cognite.client.data_classes.data_modeling import (
... NodeId,
... TypedNode,
... PropertyOptions,
... DirectRelationReference,
... ViewId,
... )
>>> class Person(TypedNode):
... birth_year = PropertyOptions(identifier="birthYear")
...
... def __init__(
... self,
... space: str,
... external_id: str,
... version: int,
... last_updated_time: int,
... created_time: int,
... name: str,
... birth_year: int | None = None,
... type: DirectRelationReference | None = None,
... deleted_time: int | None = None,
... ):
... super().__init__(
... space=space,
... external_id=external_id,
... version=version,
... last_updated_time=last_updated_time,
... created_time=created_time,
... type=type,
... deleted_time=deleted_time,
... )
... self.name = name
... self.birth_year = birth_year
...
... @classmethod
... def get_source(cls) -> ViewId:
... return ViewId("myModelSpace", "Person", "1")
>>> client = CogniteClient()
>>> # async_client = AsyncCogniteClient() # another option
>>> res = client.data_modeling.instances.retrieve_nodes(
... NodeId("myDataSpace", "myPerson"), node_cls=Person
... )
>>> isinstance(res, Person)
"""
res = await self._retrieve_typed(
nodes=nodes, edges=None, node_cls=node_cls, edge_cls=Edge, sources=sources, include_typing=include_typing
)
if isinstance(nodes, NodeId) or (isinstance(nodes, tuple) and all(isinstance(i, str) for i in nodes)):
return res.nodes[0] if res.nodes else None
return res.nodes
async def retrieve(
self,
nodes: NodeId | Sequence[NodeId] | tuple[str, str] | Sequence[tuple[str, str]] | None = None,
edges: EdgeId | Sequence[EdgeId] | tuple[str, str] | Sequence[tuple[str, str]] | None = None,
sources: Source | Sequence[Source] | None = None,
include_typing: bool = False,
) -> InstancesResult[Node, Edge]:
"""`Retrieve one or more instance by id(s) <https://api-docs.cognite.com/20230101/tag/Instances/operation/byExternalIdsInstances>`_.
Args:
nodes (NodeId | Sequence[NodeId] | tuple[str, str] | Sequence[tuple[str, str]] | None): Node ids
edges (EdgeId | Sequence[EdgeId] | tuple[str, str] | Sequence[tuple[str, str]] | None): Edge ids
sources (Source | Sequence[Source] | None): Retrieve properties from the listed - by reference - views.
include_typing (bool): Whether to return property type information as part of the result.
Returns:
InstancesResult[Node, Edge]: Requested instances.
Examples:
Retrieve instances by id:
>>> from cognite.client import CogniteClient, AsyncCogniteClient
>>> client = CogniteClient()
>>> # async_client = AsyncCogniteClient() # another option
>>> res = client.data_modeling.instances.retrieve(
... nodes=("mySpace", "myNodeExternalId"),
... edges=("mySpace", "myEdgeExternalId"),
... sources=("mySpace", "myViewExternalId", "myViewVersion"),
... )
Retrieve nodes an edges using the built in data class
>>> from cognite.client.data_classes.data_modeling import NodeId, EdgeId, ViewId
>>> res = client.data_modeling.instances.retrieve(
... NodeId("mySpace", "myNode"),
... EdgeId("mySpace", "myEdge"),
... ViewId("mySpace", "myViewExternalId", "myViewVersion"),
... )
Retrieve nodes an edges using the the view object as source
>>> from cognite.client.data_classes.data_modeling import NodeId, EdgeId
>>> res = client.data_modeling.instances.retrieve(
... NodeId("mySpace", "myNode"),
... EdgeId("mySpace", "myEdge"),
... sources=("myspace", "myView"),
... )
"""
return await self._retrieve_typed(
nodes=nodes, edges=edges, sources=sources, include_typing=include_typing, node_cls=Node, edge_cls=Edge
)
async def _retrieve_typed(
self,
nodes: NodeId | Sequence[NodeId] | tuple[str, str] | Sequence[tuple[str, str]] | None,
edges: EdgeId | Sequence[EdgeId] | tuple[str, str] | Sequence[tuple[str, str]] | None,
sources: Source | Sequence[Source] | None,
include_typing: bool,
node_cls: type[T_Node],
edge_cls: type[T_Edge],
) -> InstancesResult[T_Node, T_Edge]:
identifiers = self._load_node_and_edge_ids(nodes, edges)
sources = self._to_sources(sources, node_cls, edge_cls)
other_params = self._create_other_params(
include_typing=include_typing,
sources=sources,
sort=None,
instance_type=None,
)
class _NodeOrEdgeList(CogniteResourceList):
_RESOURCE = (node_cls, edge_cls) # type: ignore[assignment]
def __init__(
self,
resources: list[Node | Edge],
typing: TypeInformation | None,
):
super().__init__(resources)
self.typing = typing
@classmethod
def _load(cls, resource_list: Iterable[dict[str, Any]]) -> _NodeOrEdgeList:
resources: list[Node | Edge] = [
node_cls._load(data) if data["instanceType"] == "node" else edge_cls._load(data)
for data in resource_list
]
return cls(resources, typing=None)
@classmethod
def _load_raw_api_response(cls, responses: list[dict[str, Any]]) -> _NodeOrEdgeList:
typing = next((TypeInformation._load(resp["typing"]) for resp in responses if "typing" in resp), None)
resources = [
node_cls._load(data) if data["instanceType"] == "node" else edge_cls._load(data)
for response in responses
for data in response["items"]
]
return cls(resources, typing) # type: ignore[arg-type]
res = await self._retrieve_multiple( # type: ignore[call-overload]
list_cls=_NodeOrEdgeList,
resource_cls=_NodeOrEdgeResourceAdapter(node_cls, edge_cls),
identifiers=identifiers,
other_params=other_params,
settings_forcing_raw_response_loading=[f"{include_typing=}"] if include_typing else None,
)
return InstancesResult[T_Node, T_Edge](
nodes=NodeList([node for node in res if isinstance(node, node_cls)], typing=res.typing),
edges=EdgeList([edge for edge in res if isinstance(edge, edge_cls)], typing=res.typing),
)
@staticmethod
def _to_sources(
sources: Source | Sequence[Source] | None, *instance_cls: type[T_Node] | type[T_Edge] | None
) -> Source | Sequence[Source] | None:
if sources is not None:
return sources
for cls in instance_cls:
if issubclass(cls, (TypedNode, TypedEdge)): # type: ignore[arg-type]
return cls.get_source() # type: ignore[union-attr]
return sources
def _load_node_and_edge_ids(
self,
nodes: NodeId | Sequence[NodeId] | tuple[str, str] | Sequence[tuple[str, str]] | None,
edges: EdgeId | Sequence[EdgeId] | tuple[str, str] | Sequence[tuple[str, str]] | None,
) -> DataModelingIdentifierSequence:
nodes_seq: Sequence[NodeId | tuple[str, str]]
if isinstance(nodes, NodeId) or (isinstance(nodes, tuple) and isinstance(nodes[0], str)):
nodes_seq = [nodes]
else:
nodes_seq = nodes # type: ignore[assignment]
edges_seq: Sequence[EdgeId | tuple[str, str]]
if isinstance(edges, EdgeId) or (isinstance(edges, tuple) and isinstance(edges[0], str)):
edges_seq = [edges]
else:
edges_seq = edges # type: ignore[assignment]
identifiers = []
if nodes_seq:
node_ids = _load_identifier(nodes_seq, "node")
identifiers.extend(node_ids._identifiers)
if edges_seq:
edge_ids = _load_identifier(edges_seq, "edge")
identifiers.extend(edge_ids._identifiers)
return DataModelingIdentifierSequence(identifiers, is_singleton=False)
async def delete(
self,
nodes: NodeId | Sequence[NodeId] | tuple[str, str] | Sequence[tuple[str, str]] | None = None,
edges: EdgeId | Sequence[EdgeId] | tuple[str, str] | Sequence[tuple[str, str]] | None = None,
) -> InstancesDeleteResult:
"""`Delete one or more instances <https://api-docs.cognite.com/20230101/tag/Instances/operation/deleteBulk>`_.
Args:
nodes (NodeId | Sequence[NodeId] | tuple[str, str] | Sequence[tuple[str, str]] | None): Node ids
edges (EdgeId | Sequence[EdgeId] | tuple[str, str] | Sequence[tuple[str, str]] | None): Edge ids
Returns:
InstancesDeleteResult: The instance ID(s) that was deleted. Empty list if nothing was deleted.
Examples:
Delete instances by id:
>>> from cognite.client import CogniteClient, AsyncCogniteClient
>>> client = CogniteClient()
>>> # async_client = AsyncCogniteClient() # another option
>>> client.data_modeling.instances.delete(nodes=("mySpace", "myNode"))
Delete nodes and edges using the built in data class
>>> from cognite.client.data_classes.data_modeling import NodeId, EdgeId
>>> client.data_modeling.instances.delete(
... NodeId("mySpace", "myNode"), EdgeId("mySpace", "myEdge")
... )
Delete all nodes from a NodeList
>>> from cognite.client.data_classes.data_modeling import NodeId, EdgeId
>>> my_view = client.data_modeling.views.retrieve(("mySpace", "myView"))
>>> my_nodes = client.data_modeling.instances.list(
... instance_type="node", sources=my_view, limit=None
... )
>>> client.data_modeling.instances.delete(nodes=my_nodes.as_ids())
"""
identifiers = self._load_node_and_edge_ids(nodes, edges)
deleted_instances = cast(
list,
await self._delete_multiple(
identifiers,
wrap_ids=True,
returns_items=True,
),
)
node_ids = [NodeId.load(item) for item in deleted_instances if item["instanceType"] == "node"]
edge_ids = [EdgeId.load(item) for item in deleted_instances if item["instanceType"] == "edge"]
return InstancesDeleteResult(node_ids, edge_ids)
async def inspect(
self,
nodes: NodeId | Sequence[NodeId] | tuple[str, str] | Sequence[tuple[str, str]] | None = None,
edges: EdgeId | Sequence[EdgeId] | tuple[str, str] | Sequence[tuple[str, str]] | None = None,
*,
involved_views: InvolvedViews | None = None,
involved_containers: InvolvedContainers | None = None,
) -> InstanceInspectResults:
"""`Reverse lookup for instances <https://developer.cognite.com/api/v1/#tag/Instances/operation/instanceInspect>`_.
This method will return the involved views and containers for the given nodes and edges.
Args:
nodes (NodeId | Sequence[NodeId] | tuple[str, str] | Sequence[tuple[str, str]] | None): Node IDs.
edges (EdgeId | Sequence[EdgeId] | tuple[str, str] | Sequence[tuple[str, str]] | None): Edge IDs.
involved_views (InvolvedViews | None): Whether to include involved views. Must pass at least one of involved_views or involved_containers.
involved_containers (InvolvedContainers | None): Whether to include involved containers. Must pass at least one of involved_views or involved_containers.
Returns:
InstanceInspectResults: List of instance inspection results.
Examples:
Look up the involved views for a given node and edge:
>>> from cognite.client import CogniteClient
>>> from cognite.client.data_classes.data_modeling import NodeId, EdgeId, InvolvedViews
>>> client = CogniteClient()
>>> # async_client = AsyncCogniteClient() # another option
>>> res = client.data_modeling.instances.inspect(
... nodes=NodeId("my-space", "foo1"),
... edges=EdgeId("my-space", "bar2"),
... involved_views=InvolvedViews(all_versions=False),
... )
Look up the involved containers:
>>> from cognite.client.data_classes.data_modeling import InvolvedContainers
>>> res = client.data_modeling.instances.inspect(
... nodes=[("my-space", "foo1"), ("my-space", "foo2")],
... involved_containers=InvolvedContainers(),
... )
"""
identifiers = self._load_node_and_edge_ids(nodes, edges)
inspect_operations = {}
# Only add the inspect operation to the dict if the value is provided. This is important
# since if it's omitted, the API will not execute the operation, making it cheaper.
if involved_views:
inspect_operations["involvedViews"] = {"allVersions": involved_views.all_versions}
if involved_containers:
inspect_operations["involvedContainers"] = {}
if not inspect_operations:
raise ValueError("Must pass at least one of 'involved_views' or 'involved_containers'")
items = []
semaphore = self._get_semaphore("read")
for chunk in identifiers.chunked(1000):
response = await self._post(
self._RESOURCE_PATH + "/inspect",
json={"items": chunk.as_dicts(), "inspectionOperations": inspect_operations},
semaphore=semaphore,
)
items.extend(unpack_items(response))
return InstanceInspectResults(
nodes=InstanceInspectResultList._load([node for node in items if node["instanceType"] == "node"]),
edges=InstanceInspectResultList._load([edge for edge in items if edge["instanceType"] == "edge"]),
)
async def subscribe(
self,
query: QuerySync,
callback: Callable[[QueryResult], None | Awaitable[None]],
poll_delay_seconds: float = 30,
throttle_seconds: float = 1,
) -> SubscriptionContext:
"""Subscribe to a query and get updates when the result set changes.
This runs the sync() method in a background task.
We do not support chaining result sets when subscribing to a query.
Tip:
For a practical guide on using this method to create a live local replica of your data,
see :ref:`this example of syncing instances to a local SQLite database <dm_instances_subscribe_example>`.
Args:
query (QuerySync): The query to subscribe to.
callback (Callable[[QueryResult], None | Awaitable[None]]): The callback function to call when the result set changes. Can be a regular or async function.
poll_delay_seconds (float): The time to wait between polls when no data is present. Defaults to 30 seconds.
throttle_seconds (float): The time to wait between polls despite data being present.
Returns:
SubscriptionContext: An object that can be used to inspect and cancel the subscription.
Examples:
Subscribe to a given query and process the results in your own callback function
(here we just print the result for illustration):
>>> from cognite.client import CogniteClient
>>> from cognite.client.data_classes.data_modeling.query import (
... QuerySync,
... QueryResult,
... NodeResultSetExpressionSync,
... SelectSync,
... SourceSelector,
... )
>>> from cognite.client.data_classes.data_modeling import ViewId
>>> from cognite.client.data_classes.filters import Equals
>>>
>>> client = CogniteClient()
>>> def just_print_the_result(result: QueryResult) -> None:
... print(result)
>>>
>>> view_id = ViewId("someSpace", "someView", "v1")
>>> filter = Equals(view_id.as_property_ref("myAsset"), "Il-Tempo-Gigante")
>>> query = QuerySync(
... with_={
... "work_orders": NodeResultSetExpressionSync(
... filter=filter, sync_mode="two_phase"
... )
... },
... select={"work_orders": SelectSync([SourceSelector(view_id, ["*"])])},
... )
>>> subscription_context = client.data_modeling.instances.subscribe(
... query, callback=just_print_the_result
... )
>>> # Use the returned subscription_context to manage the subscription, e.g. to cancel it:
>>> subscription_context.cancel()
"""
subscription_context = SubscriptionContext()
async def _poll_loop() -> None:
cursors = query.cursors
error_backoff = Backoff(max_wait=30)
is_first_poll = True
try:
while True:
# Smear the first poll to avoid thundering herd
if is_first_poll:
delay = random.uniform(0, poll_delay_seconds)
logger.debug(f"Initial poll delay: waiting {delay:.2f} seconds...")
await asyncio.sleep(delay)
is_first_poll = False
# No need to resync if we encountered an error in the callback last iteration
if not error_backoff.has_progressed():
query.cursors = cursors
result = await self.sync(query)
subscription_context.last_successful_sync = datetime.now(tz=timezone.utc)
try:
# Support both sync and async callbacks
if inspect.iscoroutinefunction(callback):
await callback(result)
else:
callback(result)
except Exception:
logger.exception("Unhandled exception in sync subscriber callback. Backing off and retrying...")
await asyncio.sleep(next(error_backoff))
continue # Skip to the next iteration
# Only progress the cursor if the callback executed successfully
subscription_context.last_successful_callback = datetime.now(tz=timezone.utc)
cursors = result.cursors
error_backoff.reset()
data_is_present = any(len(instances) > 0 for instances in result.data.values())
delay = throttle_seconds if data_is_present else poll_delay_seconds
logger.debug(f"Waiting {delay:.2f} seconds before polling sync endpoint again...")
await asyncio.sleep(delay)
except asyncio.CancelledError:
logger.info("Subscription task was cancelled.")
except Exception:
logger.exception("Subscription task failed with an unhandled exception.")
finally:
logger.debug("Subscription polling loop finished.")
subscription_context._task = asyncio.create_task(
_poll_loop(), name=f"instances-sync-subscriber-{random_string(10)}"
)
return subscription_context
@classmethod
def _create_other_params(
cls,
*,
include_typing: bool,
sort: Sequence[InstanceSort | dict] | InstanceSort | dict | None,
sources: Source | Sequence[Source] | None,
instance_type: Literal["node", "edge"] | None,
debug: DebugParameters | None = None,
) -> dict[str, Any]:
other_params: dict[str, Any] = {"includeTyping": include_typing}
if sources:
other_params["sources"] = [source.dump() for source in SourceSelector._load_list(sources)]
if with_properties := [s["source"] for s in other_params["sources"] if "properties" in s]:
raise ValueError(
f"Selecting properties is not supported in this context. "
f"Received in `sources` argument for views: {with_properties}."
)
if sort:
if isinstance(sort, (InstanceSort, dict)):
other_params["sort"] = [cls._dump_instance_sort(sort)]
else:
other_params["sort"] = [cls._dump_instance_sort(s) for s in sort]
if instance_type:
other_params["instanceType"] = instance_type
if debug:
other_params["debug"] = debug.dump()
return other_params
@staticmethod
def _dump_instance_sort(sort: InstanceSort | dict) -> dict:
return sort.dump(camel_case=True) if isinstance(sort, InstanceSort) else sort
async def apply(
self,
nodes: NodeApply | Sequence[NodeApply] | None = None,
edges: EdgeApply | Sequence[EdgeApply] | None = None,
auto_create_start_nodes: bool = False,
auto_create_end_nodes: bool = False,
auto_create_direct_relations: bool = True,
skip_on_version_conflict: bool = False,
replace: bool = False,
) -> InstancesApplyResult:
"""`Add or update (upsert) instances <https://api-docs.cognite.com/20230101/tag/Instances/operation/applyNodeAndEdges>`_.
Args:
nodes (NodeApply | Sequence[NodeApply] | None): Nodes to apply
edges (EdgeApply | Sequence[EdgeApply] | None): Edges to apply
auto_create_start_nodes (bool): Whether to create missing start nodes for edges when ingesting. By default, the start node of an edge must exist before it can be ingested.