Sequences
Metadata
Retrieve a sequence by id
- SequencesAPI.retrieve(id: Optional[int] = None, external_id: Optional[str] = None) cognite.client.data_classes.sequences.Sequence | None
Retrieve a single sequence by id.
- Parameters
id (int | None) – ID
external_id (str | None) – External ID
- Returns
Requested sequence or None if it does not exist.
- Return type
Sequence | None
Examples
Get sequence by id:
>>> from cognite.client import CogniteClient >>> client = CogniteClient() >>> res = client.sequences.retrieve(id=1)
Get sequence by external id:
>>> res = client.sequences.retrieve()
Retrieve multiple sequences by id
- SequencesAPI.retrieve_multiple(ids: Optional[Sequence[int]] = None, external_ids: Optional[SequenceNotStr[str]] = None, ignore_unknown_ids: bool = False) SequenceList
Retrieve multiple sequences by id.
- Parameters
ids (Sequence[int] | None) – IDs
external_ids (SequenceNotStr[str] | None) – External IDs
ignore_unknown_ids (bool) – Ignore IDs and external IDs that are not found rather than throw an exception.
- Returns
The requested sequences.
- Return type
Examples
Get sequences by id:
>>> from cognite.client import CogniteClient >>> client = CogniteClient() >>> res = client.sequences.retrieve_multiple(ids=[1, 2, 3])
Get sequences by external id:
>>> res = client.sequences.retrieve_multiple(external_ids=["abc", "def"])
List sequences
- SequencesAPI.list(name: Optional[str] = None, external_id_prefix: Optional[str] = None, metadata: Optional[dict[str, str]] = None, asset_ids: Optional[Sequence[int]] = None, asset_subtree_ids: Optional[Union[int, Sequence[int]]] = None, asset_subtree_external_ids: Optional[Union[str, SequenceNotStr[str]]] = None, data_set_ids: Optional[Union[int, Sequence[int]]] = None, data_set_external_ids: Optional[Union[str, SequenceNotStr[str]]] = None, created_time: Optional[Union[dict[str, Any], TimestampRange]] = None, last_updated_time: Optional[Union[dict[str, Any], TimestampRange]] = None, limit: int | None = 25, partitions: Optional[int] = None, advanced_filter: Optional[Union[Filter, dict[str, Any]]] = None, sort: Optional[Union[SequenceSort, str, SortableSequenceProperty, tuple[str, Literal['asc', 'desc']], tuple[str, Literal['asc', 'desc'], Literal['auto', 'first', 'last']], list[cognite.client.data_classes.sequences.SequenceSort | str | cognite.client.data_classes.sequences.SortableSequenceProperty | tuple[str, Literal['asc', 'desc']] | tuple[str, Literal['asc', 'desc'], Literal['auto', 'first', 'last']]]]] = None) SequenceList
-
- Parameters
name (str | None) – Filter out sequences that do not have this exact name.
external_id_prefix (str | None) – Filter out sequences that do not have this string as the start of the externalId
metadata (dict[str, str] | None) – Filter out sequences that do not match these metadata fields and values (case-sensitive). Format is {“key1”:”value1”,”key2”:”value2”}.
asset_ids (Sequence[int] | None) – Filter out sequences that are not linked to any of these assets.
asset_subtree_ids (int | Sequence[int] | None) – Only include sequences that have a related asset in a subtree rooted at any of these assetIds. If the total size of the given subtrees exceeds 100,000 assets, an error will be returned.
asset_subtree_external_ids (str | SequenceNotStr[str] | None) – Only include sequences that have a related asset in a subtree rooted at any of these assetExternalIds. If the total size of the given subtrees exceeds 100,000 assets, an error will be returned.
data_set_ids (int | Sequence[int] | None) – Return only sequences in the specified data set(s) with this id / these ids.
data_set_external_ids (str | SequenceNotStr[str] | None) – Return only sequences in the specified data set(s) with this external id / these external ids.
created_time (dict[str, Any] | TimestampRange | None) – Range between two timestamps. Possible keys are min and max, with values given as time stamps in ms.
last_updated_time (dict[str, Any] | TimestampRange | None) – Range between two timestamps. Possible keys are min and max, with values given as time stamps in ms.
limit (int | None) – Max number of sequences to return. Defaults to 25. Set to -1, float(“inf”) or None to return all items.
partitions (int | None) – Retrieve resources in parallel using this number of workers (values up to 10 allowed), limit must be set to None (or -1).
advanced_filter (Filter | dict[str, Any] | None) – Advanced filter query using the filter DSL (Domain Specific Language). It allows defining complex filtering expressions that combine simple operations, such as equals, prefix, exists, etc., using boolean operators and, or, and not. See examples below for usage.
sort (SortSpec | list[SortSpec] | None) – The criteria to sort by. Defaults to desc for _score_ and asc for all other properties. Sort is not allowed if partitions is used.
- Returns
The requested sequences.
- Return type
Note
- When using partitions, there are few considerations to keep in mind:
limit has to be set to None (or -1).
API may reject requests if you specify more than 10 partitions. When Cognite enforces this behavior, the requests result in a 400 Bad Request status.
Partitions are done independently of sorting: there’s no guarantee of the sort order between elements from different partitions. For this reason providing a sort parameter when using partitions is not allowed.
Examples
List sequences:
>>> from cognite.client import CogniteClient >>> client = CogniteClient() >>> res = client.sequences.list(limit=5)
Iterate over sequences:
>>> for seq in client.sequences: ... seq # do something with the sequence
Iterate over chunks of sequences to reduce memory load:
>>> for seq_list in client.sequences(chunk_size=2500): ... seq_list # do something with the sequences
Using advanced filter, find all sequences that have a metadata key ‘timezone’ starting with ‘Europe’, and sort by external id ascending:
>>> from cognite.client.data_classes import filters >>> in_timezone = filters.Prefix(["metadata", "timezone"], "Europe") >>> res = client.sequences.list(advanced_filter=in_timezone, sort=("external_id", "asc"))
Note that you can check the API documentation above to see which properties you can filter on with which filters.
To make it easier to avoid spelling mistakes and easier to look up available properties for filtering and sorting, you can also use the SequenceProperty and SortableSequenceProperty Enums.
>>> from cognite.client.data_classes import filters >>> from cognite.client.data_classes.sequences import SequenceProperty, SortableSequenceProperty >>> in_timezone = filters.Prefix(SequenceProperty.metadata_key("timezone"), "Europe") >>> res = client.sequences.list( ... advanced_filter=in_timezone, ... sort=(SortableSequenceProperty.external_id, "asc"))
Combine filter and advanced filter:
>>> from cognite.client.data_classes import filters >>> not_instrument_lvl5 = filters.And( ... filters.ContainsAny("labels", ["Level5"]), ... filters.Not(filters.ContainsAny("labels", ["Instrument"])) ... ) >>> res = client.sequences.list(asset_subtree_ids=[123456], advanced_filter=not_instrument_lvl5)
Aggregate sequences
- SequencesAPI.aggregate(filter: Optional[Union[SequenceFilter, dict[str, Any]]] = None) list[cognite.client.data_classes.aggregations.CountAggregate]
-
- Parameters
filter (SequenceFilter | dict[str, Any] | None) – Filter on sequence filter with exact match
- Returns
List of sequence aggregates
- Return type
list[CountAggregate]
Examples
Aggregate sequences:
>>> from cognite.client import CogniteClient >>> client = CogniteClient() >>> res = client.sequences.aggregate(filter={"external_id_prefix": "prefix"})
Aggregate Sequences Count
- SequencesAPI.aggregate_count(advanced_filter: Optional[Union[Filter, dict[str, Any]]] = None, filter: Optional[Union[SequenceFilter, dict[str, Any]]] = None) int
Count of sequences matching the specified filters and search.
- Parameters
advanced_filter (Filter | dict[str, Any] | None) – The filter to narrow down the sequences to count.
filter (SequenceFilter | dict[str, Any] | None) – The filter to narrow down sequences to count requiring exact match.
- Returns
The number of sequences matching the specified filters and search.
- Return type
int
Examples
Count the number of time series in your CDF project:
>>> from cognite.client import CogniteClient >>> client = CogniteClient() >>> count = client.sequences.aggregate_count()
Count the number of sequences with external id prefixed with “mapping:” in your CDF project:
>>> from cognite.client.data_classes import filters >>> from cognite.client.data_classes.sequences import SequenceProperty >>> is_mapping = filters.Prefix(SequenceProperty.external_id, "mapping:") >>> count = client.sequences.aggregate_count(advanced_filter=is_mapping)
Aggregate Sequences Value Cardinality
- SequencesAPI.aggregate_cardinality_values(property: cognite.client.data_classes.sequences.SequenceProperty | str | list[str], advanced_filter: Optional[Union[Filter, dict[str, Any]]] = None, aggregate_filter: Optional[Union[AggregationFilter, dict[str, Any]]] = None, filter: Optional[Union[SequenceFilter, dict[str, Any]]] = None) int
Find approximate property count for sequences.
- Parameters
property (SequenceProperty | str | list[str]) – The property to count the cardinality of.
advanced_filter (Filter | dict[str, Any] | None) – The filter to narrow down the sequences to count cardinality.
aggregate_filter (AggregationFilter | dict[str, Any] | None) – The filter to apply to the resulting buckets.
filter (SequenceFilter | dict[str, Any] | None) – The filter to narrow down the sequences to count requiring exact match.
- Returns
The number of properties matching the specified filters and search.
- Return type
int
Examples
Count the number of different values for the metadata key “efficiency” used for sequences in your CDF project:
>>> from cognite.client import CogniteClient >>> from cognite.client.data_classes.sequences import SequenceProperty >>> client = CogniteClient() >>> count = client.sequences.aggregate_cardinality_values(SequenceProperty.metadata_key("efficiency"))
Count the number of timezones (metadata key) for sequences with the word “critical” in the description in your CDF project, but exclude timezones from america:
>>> from cognite.client.data_classes import filters, aggregations as aggs >>> from cognite.client.data_classes.sequences import SequenceProperty >>> not_america = aggs.Not(aggs.Prefix("america")) >>> is_critical = filters.Search(SequenceProperty.description, "critical") >>> timezone_count = client.sequences.aggregate_cardinality_values( ... SequenceProperty.metadata_key("timezone"), ... advanced_filter=is_critical, ... aggregate_filter=not_america)
Aggregate Sequences Property Cardinality
- SequencesAPI.aggregate_cardinality_properties(path: cognite.client.data_classes.sequences.SequenceProperty | str | list[str], advanced_filter: Optional[Union[Filter, dict[str, Any]]] = None, aggregate_filter: Optional[Union[AggregationFilter, dict[str, Any]]] = None, filter: Optional[Union[SequenceFilter, dict[str, Any]]] = None) int
Find approximate paths count for sequences.
- Parameters
path (SequenceProperty | str | list[str]) – The scope in every document to aggregate properties. The only value allowed now is [“metadata”]. It means to aggregate only metadata properties (aka keys).
advanced_filter (Filter | dict[str, Any] | None) – The filter to narrow down the sequences to count cardinality.
aggregate_filter (AggregationFilter | dict[str, Any] | None) – The filter to apply to the resulting buckets.
filter (SequenceFilter | dict[str, Any] | None) – The filter to narrow down the sequences to count requiring exact match.
- Returns
The number of properties matching the specified filters and search.
- Return type
int
Examples
Count the number of different metadata keys in your CDF project:
>>> from cognite.client import CogniteClient >>> from cognite.client.data_classes.sequences import SequenceProperty >>> client = CogniteClient() >>> count = client.sequences.aggregate_cardinality_values(SequenceProperty.metadata)
Aggregate Sequences Unique Values
- SequencesAPI.aggregate_unique_values(property: cognite.client.data_classes.sequences.SequenceProperty | str | list[str], advanced_filter: Optional[Union[Filter, dict[str, Any]]] = None, aggregate_filter: Optional[Union[AggregationFilter, dict[str, Any]]] = None, filter: Optional[Union[SequenceFilter, dict[str, Any]]] = None) UniqueResultList
Get unique paths with counts for sequences.
- Parameters
property (SequenceProperty | str | list[str]) – The property to group by.
advanced_filter (Filter | dict[str, Any] | None) – The filter to narrow down the sequences to count cardinality.
aggregate_filter (AggregationFilter | dict[str, Any] | None) – The filter to apply to the resulting buckets.
filter (SequenceFilter | dict[str, Any] | None) – The filter to narrow down the sequences to count requiring exact match.
- Returns
List of unique values of sequences matching the specified filters and search.
- Return type
UniqueResultList
Examples
Get the timezones (metadata key) with count for your sequences in your CDF project:
>>> from cognite.client import CogniteClient >>> from cognite.client.data_classes.sequences import SequenceProperty >>> client = CogniteClient() >>> result = client.sequences.aggregate_unique_values(SequenceProperty.metadata_key("timezone")) >>> print(result.unique)
Get the different metadata keys with count used for sequences created after 2020-01-01 in your CDF project:
>>> from cognite.client.data_classes import filters >>> from cognite.client.data_classes.sequences import SequenceProperty >>> from cognite.client.utils import timestamp_to_ms >>> from datetime import datetime >>> created_after_2020 = filters.Range(SequenceProperty.created_time, gte=timestamp_to_ms(datetime(2020, 1, 1))) >>> result = client.sequences.aggregate_unique_values(SequenceProperty.metadata, advanced_filter=created_after_2020) >>> print(result.unique)
Get the different metadata keys with count for sequences updated after 2020-01-01 in your CDF project, but exclude all metadata keys that starts with “test”:
>>> from cognite.client.data_classes.sequences import SequenceProperty >>> from cognite.client.data_classes import aggregations as aggs, filters >>> not_test = aggs.Not(aggs.Prefix("test")) >>> created_after_2020 = filters.Range(SequenceProperty.last_updated_time, gte=timestamp_to_ms(datetime(2020, 1, 1))) >>> result = client.sequences.aggregate_unique_values(SequenceProperty.metadata, advanced_filter=created_after_2020, aggregate_filter=not_test) >>> print(result.unique)
Aggregate Sequences Unique Properties
- SequencesAPI.aggregate_unique_properties(path: cognite.client.data_classes.sequences.SequenceProperty | str | list[str], advanced_filter: Optional[Union[Filter, dict[str, Any]]] = None, aggregate_filter: Optional[Union[AggregationFilter, dict[str, Any]]] = None, filter: Optional[Union[SequenceFilter, dict[str, Any]]] = None) UniqueResultList
Find approximate unique sequence properties.
- Parameters
path (SequenceProperty | str | list[str]) – The scope in every document to aggregate properties. The only value allowed now is [“metadata”]. It means to aggregate only metadata properties (aka keys).
advanced_filter (Filter | dict[str, Any] | None) – The filter to narrow down the sequences to count cardinality.
aggregate_filter (AggregationFilter | dict[str, Any] | None) – The filter to apply to the resulting buckets.
filter (SequenceFilter | dict[str, Any] | None) – The filter to narrow down the sequences to count requiring exact match.
- Returns
List of unique values of sequences matching the specified filters and search.
- Return type
UniqueResultList
Examples
Get the metadata keys with count for your sequences in your CDF project:
>>> from cognite.client import CogniteClient >>> from cognite.client.data_classes.sequences import SequenceProperty >>> client = CogniteClient() >>> result = client.sequences.aggregate_unique_properties(SequenceProperty.metadata)
Search for sequences
- SequencesAPI.search(name: Optional[str] = None, description: Optional[str] = None, query: Optional[str] = None, filter: Optional[Union[SequenceFilter, dict[str, Any]]] = None, limit: int = 25) SequenceList
Search for sequences. Primarily meant for human-centric use-cases and data exploration, not for programs, since matching and ordering may change over time. Use the list function if stable or exact matches are required.
- Parameters
name (str | None) – Prefix and fuzzy search on name.
description (str | None) – Prefix and fuzzy search on description.
query (str | None) – Search on name and description using wildcard search on each of the words (separated by spaces). Retrieves results where at least one word must match. Example: ‘some other’
filter (SequenceFilter | dict[str, Any] | None) – Filter to apply. Performs exact match on these fields.
limit (int) – Max number of results to return.
- Returns
The search result as a SequenceList
- Return type
Examples
Search for a sequence:
>>> from cognite.client import CogniteClient >>> client = CogniteClient() >>> res = client.sequences.search(name="some name")
Create a sequence
- SequencesAPI.create(sequence: cognite.client.data_classes.sequences.Sequence | cognite.client.data_classes.sequences.SequenceWrite) Sequence
- SequencesAPI.create(sequence: Union[Sequence[Sequence], Sequence[SequenceWrite]]) SequenceList
-
- Parameters
sequence (Sequence | SequenceWrite | Sequence[Sequence] | Sequence[SequenceWrite]) – Sequence or list of Sequence to create. The Sequence columns parameter is a list of objects with fields externalId (external id of the column, when omitted, they will be given ids of ‘column0, column1, …’), valueType (data type of the column, either STRING, LONG, or DOUBLE, with default DOUBLE), name, description, metadata (optional fields to describe and store information about the data in the column). Other fields will be removed automatically, so a columns definition from a different sequence object can be passed here.
- Returns
The created sequence(s).
- Return type
Sequence | SequenceList
Examples
Create a new sequence:
>>> from cognite.client import CogniteClient >>> from cognite.client.data_classes import SequenceWrite, SequenceColumnWrite >>> client = CogniteClient() >>> column_def = [ ... SequenceColumnWrite(value_type="String", external_id="user", description="some description"), ... SequenceColumnWrite(value_type="Double", external_id="amount") ... ] >>> seq = client.sequences.create(SequenceWrite(external_id="my_sequence", columns=column_def))
Create a new sequence with the same column specifications as an existing sequence:
>>> seq2 = client.sequences.create(SequenceWrite(external_id="my_copied_sequence", columns=column_def))
Delete sequences
- SequencesAPI.delete(id: Optional[Union[int, Sequence[int]]] = None, external_id: Optional[Union[str, SequenceNotStr[str]]] = None, ignore_unknown_ids: bool = False) None
-
- Parameters
id (int | Sequence[int] | None) – Id or list of ids
external_id (str | SequenceNotStr[str] | None) – External ID or list of external ids
ignore_unknown_ids (bool) – Ignore IDs and external IDs that are not found rather than throw an exception.
Examples
Delete sequences by id or external id:
>>> from cognite.client import CogniteClient >>> client = CogniteClient() >>> client.sequences.delete(id=[1,2,3], external_id="3")
Filter sequences
- SequencesAPI.filter(filter: cognite.client.data_classes.filters.Filter | dict, sort: Optional[Union[SequenceSort, str, SortableSequenceProperty, tuple[str, Literal['asc', 'desc']], tuple[str, Literal['asc', 'desc'], Literal['auto', 'first', 'last']], list[cognite.client.data_classes.sequences.SequenceSort | str | cognite.client.data_classes.sequences.SortableSequenceProperty | tuple[str, Literal['asc', 'desc']] | tuple[str, Literal['asc', 'desc'], Literal['auto', 'first', 'last']]]]] = None, limit: int | None = 25) SequenceList
-
Advanced filter lets you create complex filtering expressions that combine simple operations, such as equals, prefix, exists, etc., using boolean operators and, or, and not. It applies to basic fields as well as metadata.
- Parameters
filter (Filter | dict) – Filter to apply.
sort (SortSpec | list[SortSpec] | None) – The criteria to sort by. Can be up to two properties to sort by default to ascending order.
limit (int | None) – Maximum number of results to return. Defaults to 25. Set to -1, float(“inf”) or None to return all items.
- Returns
List of sequences that match the filter criteria.
- Return type
Examples
Find all sequences with asset id ‘123’ and metadata key ‘type’ equals ‘efficiency’ and return them sorted by created time:
>>> from cognite.client import CogniteClient >>> from cognite.client.data_classes import filters >>> client = CogniteClient() >>> asset_filter = filters.Equals("asset_id", 123) >>> is_efficiency = filters.Equals(["metadata", "type"], "efficiency") >>> res = client.sequences.filter(filter=filters.And(asset_filter, is_efficiency), sort="created_time")
Note that you can check the API documentation above to see which properties you can filter on with which filters.
To make it easier to avoid spelling mistakes and easier to look up available properties for filtering and sorting, you can also use the SequenceProperty and SortableSequenceProperty enums.
>>> from cognite.client.data_classes import filters >>> from cognite.client.data_classes.sequences import SequenceProperty, SortableSequenceProperty >>> asset_filter = filters.Equals(SequenceProperty.asset_id, 123) >>> is_efficiency = filters.Equals(SequenceProperty.metadata_key("type"), "efficiency") >>> res = client.sequences.filter( ... filter=filters.And(asset_filter, is_efficiency), ... sort=SortableSequenceProperty.created_time)
Update sequences
- SequencesAPI.update(item: cognite.client.data_classes.sequences.Sequence | cognite.client.data_classes.sequences.SequenceWrite | cognite.client.data_classes.sequences.SequenceUpdate, mode: Literal['replace_ignore_null', 'patch', 'replace'] = 'replace_ignore_null') Sequence
- SequencesAPI.update(item: Sequence[cognite.client.data_classes.sequences.Sequence | cognite.client.data_classes.sequences.SequenceWrite | cognite.client.data_classes.sequences.SequenceUpdate], mode: Literal['replace_ignore_null', 'patch', 'replace'] = 'replace_ignore_null') SequenceList
-
- Parameters
item (Sequence | SequenceWrite | SequenceUpdate | Sequence[Sequence | SequenceWrite | SequenceUpdate]) – Sequences to update
mode (Literal['replace_ignore_null', 'patch', 'replace']) – How to update data when a non-update object is given (Sequence or -Write). If you use ‘replace_ignore_null’, only the fields you have set will be used to replace existing (default). Using ‘replace’ will additionally clear all the fields that are not specified by you. Last option, ‘patch’, will update only the fields you have set and for container-like fields such as metadata or labels, add the values to the existing. For more details, see Update and Upsert Mode Parameter.
- Returns
Updated sequences.
- Return type
Sequence | SequenceList
Examples
Update a sequence that you have fetched. This will perform a full update of the sequences:
>>> from cognite.client import CogniteClient >>> client = CogniteClient() >>> res = client.sequences.retrieve(id=1) >>> res.description = "New description" >>> res = client.sequences.update(res)
Perform a partial update on a sequence, updating the description and adding a new field to metadata:
>>> from cognite.client.data_classes import SequenceUpdate >>> my_update = SequenceUpdate(id=1).description.set("New description").metadata.add({"key": "value"}) >>> res = client.sequences.update(my_update)
Updating column definitions
Currently, updating the column definitions of a sequence is only supported through partial update, using add, remove and modify methods on the columns property.
Add a single new column:
>>> from cognite.client.data_classes import SequenceUpdate, SequenceColumn >>> >>> my_update = SequenceUpdate(id=1).columns.add(SequenceColumn(value_type ="String",external_id="user", description ="some description")) >>> res = client.sequences.update(my_update)
Add multiple new columns:
>>> from cognite.client.data_classes import SequenceUpdate, SequenceColumn >>> >>> column_def = [ ... SequenceColumn(value_type ="String",external_id="user", description ="some description"), ... SequenceColumn(value_type="Double", external_id="amount")] >>> my_update = SequenceUpdate(id=1).columns.add(column_def) >>> res = client.sequences.update(my_update)
Remove a single column:
>>> from cognite.client.data_classes import SequenceUpdate >>> >>> my_update = SequenceUpdate(id=1).columns.remove("col_external_id1") >>> res = client.sequences.update(my_update)
Remove multiple columns:
>>> from cognite.client.data_classes import SequenceUpdate >>> >>> my_update = SequenceUpdate(id=1).columns.remove(["col_external_id1","col_external_id2"]) >>> res = client.sequences.update(my_update)
Update existing columns:
>>> from cognite.client.data_classes import SequenceUpdate, SequenceColumnUpdate >>> >>> column_updates = [ ... SequenceColumnUpdate(external_id="col_external_id_1").external_id.set("new_col_external_id"), ... SequenceColumnUpdate(external_id="col_external_id_2").description.set("my new description"), ... ] >>> my_update = SequenceUpdate(id=1).columns.modify(column_updates) >>> res = client.sequences.update(my_update)
Upsert sequences
- SequencesAPI.upsert(item: Sequence[cognite.client.data_classes.sequences.Sequence | cognite.client.data_classes.sequences.SequenceWrite], mode: Literal['patch', 'replace'] = 'patch') SequenceList
- SequencesAPI.upsert(item: cognite.client.data_classes.sequences.Sequence | cognite.client.data_classes.sequences.SequenceWrite, mode: Literal['patch', 'replace'] = 'patch') Sequence
- Upsert sequences, i.e., update if it exists, and create if it does not exist.
Note this is a convenience method that handles the upserting for you by first calling update on all items, and if any of them fail because they do not exist, it will create them instead.
For more details, see Upsert.
- Parameters
item (Sequence | SequenceWrite | Sequence[Sequence | SequenceWrite]) – Sequence or list of sequences to upsert.
mode (Literal['patch', 'replace']) – Whether to patch or replace in the case the sequences are existing. If you set ‘patch’, the call will only update fields with non-null values (default). Setting ‘replace’ will unset any fields that are not specified.
- Returns
The upserted sequence(s).
- Return type
Sequence | SequenceList
Examples
Upsert for sequences:
>>> from cognite.client import CogniteClient >>> from cognite.client.data_classes import SequenceWrite, SequenceColumnWrite >>> client = CogniteClient() >>> existing_sequence = client.sequences.retrieve(id=1) >>> existing_sequence.description = "New description" >>> new_sequence = SequenceWrite( ... external_id="new_sequence", ... description="New sequence", ... columns=[SequenceColumnWrite(external_id="col1", value_type="String")] ... ) >>> res = client.sequences.upsert([existing_sequence, new_sequence], mode="replace")
Rows
Retrieve rows
- SequencesDataAPI.retrieve(*, external_id: str, start: int = 0, end: int | None = None, columns: Optional[SequenceNotStr[str]] = None, limit: int | None = None) SequenceRows
- SequencesDataAPI.retrieve(*, external_id: SequenceNotStr[str], start: int = 0, end: int | None = None, columns: Optional[SequenceNotStr[str]] = None, limit: int | None = None) SequenceRowsList
- SequencesDataAPI.retrieve(*, id: int, start: int = 0, end: int | None = None, columns: Optional[SequenceNotStr[str]] = None, limit: int | None = None) SequenceRows
- SequencesDataAPI.retrieve(*, id: Sequence[int], start: int = 0, end: int | None = None, columns: Optional[SequenceNotStr[str]] = None, limit: int | None = None) SequenceRowsList
-
- Parameters
external_id (str | SequenceNotStr[str] | None) – The external id of the sequence to retrieve from.
id (int | Sequence[int] | None) – The internal if the sequence to retrieve from.
start (int) – Row number to start from (inclusive).
end (int | None) – Upper limit on the row number (exclusive). Set to None or -1 to get all rows until end of sequence.
columns (SequenceNotStr[str] | None) – List of external id for the columns of the sequence. If ‘None’ is passed, all columns will be retrieved.
limit (int | None) – Maximum number of rows to return per sequence. Pass None to fetch all (possibly limited by ‘end’).
**kwargs (Any) – To support deprecated argument ‘column_external_ids’, will be removed in the next major version. Use ‘columns’ instead.
- Returns
SequenceRows if a single identifier was given, else SequenceDataList
- Return type
Examples
>>> from cognite.client import CogniteClient >>> client = CogniteClient() >>> res = client.sequences.data.retrieve(id=1) >>> tuples = [(r,v) for r,v in res.items()] # You can use this iterator in for loops and list comprehensions, >>> single_value = res[23] # ... get the values at a single row number, >>> col = res.get_column(external_id='columnExtId') # ... get the array of values for a specific column, >>> df = res.to_pandas() # ... or convert the result to a dataframe
Retrieve rows in a pandas dataframe
- SequencesDataAPI.retrieve_dataframe(start: int, end: int | None, column_external_ids: list[str] | None = None, external_id: str | None = None, column_names: str | None = None, id: int | None = None, limit: int | None = None) pandas.DataFrame
Retrieve data from a sequence as a pandas dataframe
- Parameters
start (int) – (inclusive) row number to start from.
end (int | None) – (exclusive) upper limit on the row number. Set to None or -1 to get all rows until end of sequence.
column_external_ids (list[str] | None) – List of external id for the columns of the sequence. If ‘None’ is passed, all columns will be retrieved.
external_id (str | None) – External id of sequence.
column_names (str | None) – Which field(s) to use as column header. Can use “externalId”, “id”, “columnExternalId”, “id|columnExternalId” or “externalId|columnExternalId”. Default is “externalId|columnExternalId” for queries on more than one sequence, and “columnExternalId” for queries on a single sequence.
id (int | None) – Id of sequence
limit (int | None) – Maximum number of rows to return per sequence.
- Returns
The requested sequence data in a pandas DataFrame
- Return type
pandas.DataFrame
Examples
>>> from cognite.client import CogniteClient >>> client = CogniteClient() >>> df = client.sequences.data.retrieve_dataframe(id=1, start=0, end=None)
Retrieve last row
- SequencesDataAPI.retrieve_last_row(id: Optional[int] = None, external_id: Optional[str] = None, columns: Optional[SequenceNotStr[str]] = None, before: Optional[int] = None, **kwargs: Any) SequenceRows
Retrieves the last row (i.e the row with the highest row number) in a sequence.
- Parameters
id (int | None) – Id or list of ids.
external_id (str | None) – External id or list of external ids.
columns (SequenceNotStr[str] | None) – List of external id for the columns of the sequence. If ‘None’ is passed, all columns will be retrieved.
before (int | None) – (optional, int): Get latest datapoint before this row number.
**kwargs (Any) – To support deprecated argument ‘column_external_ids’, will be removed in the next major version. Use ‘columns’ instead.
- Returns
A Datapoints object containing the requested data, or a list of such objects.
- Return type
Examples
Getting the latest row in a sequence before row number 1000:
>>> from cognite.client import CogniteClient >>> client = CogniteClient() >>> res = client.sequences.data.retrieve_last_row(id=1, before=1000)
Insert rows into a sequence
- SequencesDataAPI.insert(rows: Union[SequenceRows, dict[int, Sequence[int | float | str]], Sequence[tuple[int, Sequence[int | float | str]]], Sequence[dict[str, Any]]], columns: Optional[SequenceNotStr[str]] = None, id: Optional[int] = None, external_id: Optional[str] = None, **kwargs: Any) None
-
- Parameters
rows (SequenceRows | dict[int, Sequence[int | float | str]] | Sequence[tuple[int, Sequence[int | float | str]]] | Sequence[dict[str, Any]]) – The rows you wish to insert. Can either be a list of tuples, a list of {“rowNumber”:… ,”values”: …} objects, a dictionary of rowNumber: data, or a SequenceData object. See examples below.
columns (SequenceNotStr[str] | None) – List of external id for the columns of the sequence.
id (int | None) – Id of sequence to insert rows into.
external_id (str | None) – External id of sequence to insert rows into.
**kwargs (Any) – To support deprecated argument ‘column_external_ids’, will be removed in the next major version. Use ‘columns’ instead.
Examples
Your rows of data can be a list of tuples where the first element is the rownumber and the second element is the data to be inserted:
>>> from cognite.client import CogniteClient >>> from cognite.client.data_classes import Sequence, SequenceColumn >>> client = CogniteClient() >>> seq = client.sequences.create(Sequence(columns=[SequenceColumn(value_type="String", external_id="col_a"), ... SequenceColumn(value_type="Double", external_id ="col_b")])) >>> data = [(1, ['pi',3.14]), (2, ['e',2.72]) ] >>> client.sequences.data.insert(columns=["col_a","col_b"], rows=data, id=1)
They can also be provided as a list of API-style objects with a rowNumber and values field:
>>> data = [{"rowNumber": 123, "values": ['str',3]}, {"rowNumber": 456, "values": ["bar",42]} ] >>> client.sequences.data.insert(data, id=1, columns=["col_a","col_b"]) # implicit columns are retrieved from metadata
Or they can be a given as a dictionary with row number as the key, and the value is the data to be inserted at that row:
>>> data = {123 : ['str',3], 456 : ['bar',42] } >>> client.sequences.data.insert(columns=['stringColumn','intColumn'], rows=data, id=1)
Finally, they can be a SequenceData object retrieved from another request. In this case columns from this object are used as well.
>>> data = client.sequences.data.retrieve(id=2,start=0,end=10) >>> client.sequences.data.insert(rows=data, id=1,columns=None)
Insert a pandas dataframe into a sequence
- SequencesDataAPI.insert_dataframe(dataframe: pandas.DataFrame, id: int | None = None, external_id: str | None = None, dropna: bool = True) None
-
The index of the dataframe must contain the row numbers. The names of the remaining columns specify the column external ids. The sequence and columns must already exist.
- Parameters
dataframe (pandas.DataFrame) – Pandas DataFrame object containing the sequence data.
id (int | None) – Id of sequence to insert rows into.
external_id (str | None) – External id of sequence to insert rows into.
dropna (bool) – Whether to drop rows where all values are missing. Default: True.
Examples
Insert three rows into columns ‘col_a’ and ‘col_b’ of the sequence with id=123:
>>> from cognite.client import CogniteClient >>> import pandas as pd >>> client = CogniteClient() >>> df = pd.DataFrame({'col_a': [1, 2, 3], 'col_b': [4, 5, 6]}, index=[1, 2, 3]) >>> client.sequences.data.insert_dataframe(df, id=123)
Delete rows from a sequence
- SequencesDataAPI.delete(rows: Sequence[int], id: Optional[int] = None, external_id: Optional[str] = None) None
-
- Parameters
rows (Sequence[int]) – List of row numbers.
id (int | None) – Id of sequence to delete rows from.
external_id (str | None) – External id of sequence to delete rows from.
Examples
>>> from cognite.client import CogniteClient >>> client = CogniteClient() >>> client.sequences.data.delete(id=1, rows=[1,2,42])
Delete a range of rows from a sequence
- SequencesDataAPI.delete_range(start: int, end: int | None, id: Optional[int] = None, external_id: Optional[str] = None) None
-
- Parameters
start (int) – Row number to start from (inclusive).
end (int | None) – Upper limit on the row number (exclusive). Set to None or -1 to delete all rows until end of sequence.
id (int | None) – Id of sequence to delete rows from.
external_id (str | None) – External id of sequence to delete rows from.
Examples
>>> from cognite.client import CogniteClient >>> client = CogniteClient() >>> client.sequences.data.delete_range(id=1, start=0, end=None)
Sequence Data classes
- class cognite.client.data_classes.sequences.Sequence(id: int | None = None, name: str | None = None, description: str | None = None, asset_id: int | None = None, external_id: str | None = None, metadata: dict[str, Any] | None = None, columns: Sequence[SequenceColumn] | None = None, created_time: int | None = None, last_updated_time: int | None = None, data_set_id: int | None = None, cognite_client: CogniteClient | None = None)
Information about the sequence stored in the database. This is the reading version of the class, it is used for retrieving data from the CDF.
- Parameters
id (int | None) – Unique cognite-provided identifier for the sequence
name (str | None) – Name of the sequence
description (str | None) – Description of the sequence
asset_id (int | None) – Optional asset this sequence is associated with
external_id (str | None) – The external ID provided by the client. Must be unique for the resource type.
metadata (dict[str, Any] | None) – Custom, application-specific metadata. String key -> String value. The maximum length of the key is 32 bytes, the value 512 bytes, with up to 16 key-value pairs.
columns (Sequence[SequenceColumn] | None) – List of column definitions
created_time (int | None) – Time when this sequence was created in CDF in milliseconds since Jan 1, 1970.
last_updated_time (int | None) – The last time this sequence was updated in CDF, in milliseconds since Jan 1, 1970.
data_set_id (int | None) – Data set that this sequence belongs to
cognite_client (CogniteClient | None) – The client to associate with this object.
- class cognite.client.data_classes.sequences.SequenceColumn(external_id: Optional[str] = None, name: Optional[str] = None, description: Optional[str] = None, value_type: Literal['String', 'Double', 'Long'] = 'Double', metadata: Optional[dict[str, Any]] = None, created_time: Optional[int] = None, last_updated_time: Optional[int] = None)
Bases:
SequenceColumnCore
This represents a column in a sequence. It is used for reading only.
- Parameters
external_id (str | None) – The external ID provided by the client. Must be unique for the resource type.
name (str | None) – Name of the column
description (str | None) – Description of the column
value_type (ValueType) – The type of the column. It can be String, Double or Long.
metadata (dict[str, Any] | None) – Custom, application-specific metadata. String key -> String value. Maximum length of key is 32 bytes, value 512 bytes, up to 16 key-value pairs.
created_time (int | None) – Time when this column was created in CDF in milliseconds since Jan 1, 1970.
last_updated_time (int | None) – The last time this column was updated in CDF, in milliseconds since Jan 1, 1970.
- as_write() SequenceColumnWrite
Returns a writeable version of this column.
- class cognite.client.data_classes.sequences.SequenceColumnCore(external_id: Optional[str] = None, name: Optional[str] = None, description: Optional[str] = None, value_type: Literal['String', 'Double', 'Long'] = 'Double', metadata: Optional[dict[str, Any]] = None)
Bases:
WriteableCogniteResource
[SequenceColumnWrite
],ABC
This represents a column in a sequence.
- Parameters
external_id (str | None) – The external ID provided by the client. Must be unique for the resource type.
name (str | None) – Name of the column
description (str | None) – Description of the column
value_type (ValueType) – The type of the column. It can be String, Double or Long.
metadata (dict[str, Any] | None) – Custom, application-specific metadata. String key -> String value. The maximum length of key is 32 bytes, value 512 bytes, up to 16 key-value pairs.
- class cognite.client.data_classes.sequences.SequenceColumnList(resources: Iterable[Any], cognite_client: CogniteClient | None = None)
Bases:
CogniteResourceList
[SequenceColumn
],ExternalIDTransformerMixin
- as_write() SequenceColumnWriteList
Returns a writeable version of this column list.
- property value_types: list[Literal['String', 'Double', 'Long']]
Retrieves list of column value types
- Returns
List of column value types
- Return type
list[ValueType]
- class cognite.client.data_classes.sequences.SequenceColumnUpdate(id: Optional[int] = None, external_id: Optional[str] = None)
Bases:
CogniteUpdate
This class is used to update a sequence column.
- class cognite.client.data_classes.sequences.SequenceColumnWrite(external_id: str, name: Optional[str] = None, description: Optional[str] = None, value_type: Literal['String', 'Double', 'Long'] = 'Double', metadata: Optional[dict[str, Any]] = None)
Bases:
SequenceColumnCore
This represents a column in a sequence. This is used for writing only.
- Parameters
external_id (str) – The external ID provided by the client. Must be unique for the resource type.
name (str | None) – Name of the column
description (str | None) – Description of the column
value_type (ValueType) – The type of the column. It can be String, Double or Long.
metadata (dict[str, Any] | None) – Custom, application-specific metadata. String key -> String value. The maximum length of key is 32 bytes, value 512 bytes, up to 16 key-value pairs.
- as_write() SequenceColumnWrite
Returns this SequenceColumnWrite.
- class cognite.client.data_classes.sequences.SequenceColumnWriteList(resources: Iterable[Any], cognite_client: CogniteClient | None = None)
Bases:
CogniteResourceList
[SequenceColumnWrite
],ExternalIDTransformerMixin
- property value_types: list[Literal['String', 'Double', 'Long']]
Retrieves list of column value types
- Returns
List of column value types
- Return type
list[ValueType]
- class cognite.client.data_classes.sequences.SequenceCore(name: Optional[str] = None, description: Optional[str] = None, asset_id: Optional[int] = None, external_id: Optional[str] = None, metadata: Optional[dict[str, Any]] = None, data_set_id: Optional[int] = None)
Bases:
WriteableCogniteResource
[SequenceWrite
],ABC
Information about the sequence stored in the database
- Parameters
name (str | None) – Name of the sequence
description (str | None) – Description of the sequence
asset_id (int | None) – Optional asset this sequence is associated with
external_id (str | None) – The external ID provided by the client. Must be unique for the resource type.
metadata (dict[str, Any] | None) – Custom, application-specific metadata. String key -> String value. The maximum length of the key is 32 bytes, the value 512 bytes, with up to 16 key-value pairs.
data_set_id (int | None) – Data set that this sequence belongs to
- class cognite.client.data_classes.sequences.SequenceData(id: Optional[int] = None, external_id: Optional[str] = None, rows: Optional[Union[Sequence[dict], Sequence[SequenceRow]]] = None, row_numbers: Optional[Sequence[int]] = None, values: Optional[Sequence[Sequence[int | float | str]]] = None, columns: Optional[Union[Sequence[dict[str, Any]], SequenceColumnList]] = None)
Bases:
SequenceRows
- cognite.client.data_classes.sequences.SequenceDataList
alias of
SequenceRowsList
- class cognite.client.data_classes.sequences.SequenceFilter(name: Optional[str] = None, external_id_prefix: Optional[str] = None, metadata: Optional[dict[str, Any]] = None, asset_ids: Optional[Sequence[int]] = None, asset_subtree_ids: Optional[Sequence[dict[str, Any]]] = None, created_time: Optional[Union[dict[str, Any], TimestampRange]] = None, last_updated_time: Optional[Union[dict[str, Any], TimestampRange]] = None, data_set_ids: Optional[Sequence[dict[str, Any]]] = None)
Bases:
CogniteFilter
No description.
- Parameters
name (str | None) – Return only sequences with this exact name.
external_id_prefix (str | None) – Filter by this (case-sensitive) prefix for the external ID.
metadata (dict[str, Any] | None) – Filter the sequences by metadata fields and values (case-sensitive). Format is {“key1”:”value1”,”key2”:”value2”}.
asset_ids (Sequence[int] | None) – Return only sequences linked to one of the specified assets.
asset_subtree_ids (Sequence[dict[str, Any]] | None) – Only include sequences that have a related asset in a subtree rooted at any of these assetIds. If the total size of the given subtrees exceeds 100,000 assets, an error will be returned.
created_time (dict[str, Any] | TimestampRange | None) – Range between two timestamps.
last_updated_time (dict[str, Any] | TimestampRange | None) – Range between two timestamps.
data_set_ids (Sequence[dict[str, Any]] | None) – Only include sequences that belong to these datasets.
- class cognite.client.data_classes.sequences.SequenceList(resources: Iterable[Any], cognite_client: CogniteClient | None = None)
Bases:
WriteableCogniteResourceList
[SequenceWrite
,Sequence
],IdTransformerMixin
- as_write() SequenceWriteList
Returns a writeable version of this sequence list.
- class cognite.client.data_classes.sequences.SequenceProperty(value)
Bases:
EnumProperty
An enumeration.
- class cognite.client.data_classes.sequences.SequenceRow(row_number: int, values: Sequence[int | str | float | None])
Bases:
CogniteResource
This class represents a row in a sequence. It is used for both read and write.
- Parameters
row_number (int) – The row number for this row.
values (Sequence[RowValues]) – List of values in the order defined in the columns field. Number of items must match. Null is accepted for missing values. String values must be no longer than 256 characters.
- class cognite.client.data_classes.sequences.SequenceRows(rows: Sequence[SequenceRow], columns: SequenceColumnList, id: Optional[int] = None, external_id: Optional[str] = None)
Bases:
CogniteResource
An object representing a list of rows from a sequence.
- Parameters
rows (Sequence[SequenceRow]) – The sequence rows.
columns (SequenceColumnList) – The column information.
id (int | None) – Identifier of the sequence the data belong to
external_id (str | None) – External id of the sequence the data belong to
- property column_external_ids: list[str]
Retrieves list of column external ids for the sequence, for use in e.g. data retrieve or insert methods.
- Returns
List of sequence column external ids.
- Return type
list[str]
- property column_value_types: list[Literal['String', 'Double', 'Long']]
Retrieves list of column value types.
- Returns
List of column value types
- Return type
list[ValueType]
- dump(camel_case: bool = True) dict[str, Any]
Dump the sequence data into a json serializable Python data type.
- Parameters
camel_case (bool) – Use camelCase for attribute names. Defaults to True.
- Returns
A dictionary representing the instance.
- Return type
dict[str, Any]
- get_column(external_id: str) list[int | str | float | None]
Get a column by external_id.
- Parameters
external_id (str) – External id of the column.
- Returns
A list of values for that column in the sequence
- Return type
list[RowValues]
- items() Iterator[tuple[int, list[int | str | float | None]]]
Returns an iterator over tuples of (row number, values).
- to_pandas(column_names: ColumnNames = 'columnExternalId') pandas.DataFrame
Convert the sequence data into a pandas DataFrame.
- Parameters
column_names (ColumnNames) – Which field(s) to use as column header. Can use “externalId”, “id”, “columnExternalId”, “id|columnExternalId” or “externalId|columnExternalId”.
- Returns
The dataframe.
- Return type
pandas.DataFrame
- property values: list[list[int | str | float | None]]
Returns a list of lists of values
- class cognite.client.data_classes.sequences.SequenceRowsList(resources: Iterable[Any], cognite_client: CogniteClient | None = None)
Bases:
CogniteResourceList
[SequenceRows
],IdTransformerMixin
- to_pandas(key: Literal['id', 'external_id'] = 'external_id', column_names: Literal['externalId', 'id', 'columnExternalId', 'id|columnExternalId', 'externalId|columnExternalId'] = 'externalId|columnExternalId', concat: Literal[True] = True) pandas.DataFrame
- to_pandas(key: Literal['external_id'] = 'external_id', column_names: Literal['externalId', 'id', 'columnExternalId', 'id|columnExternalId', 'externalId|columnExternalId'] = 'externalId|columnExternalId', concat: Literal[False] = False) dict[str, pandas.DataFrame]
- to_pandas(key: Literal['id'], column_names: Literal['externalId', 'id', 'columnExternalId', 'id|columnExternalId', 'externalId|columnExternalId'] = 'externalId|columnExternalId', concat: Literal[False] = False) dict[int, pandas.DataFrame]
Convert the sequence data list into a pandas DataFrame. Each column will be a sequence.
- Parameters
key (Literal['id', 'external_id']) – If concat = False, this decides which field to use as key in the dictionary. Defaults to “external_id”.
column_names (ColumnNames) – Which field to use as column header. Can use any combination of “externalId”, “columnExternalId”, “id” and other characters as a template.
concat (bool) – Whether to concatenate the sequences into a single DataFrame or return a dictionary of DataFrames. Defaults to False.
- Returns
The sequence data list as a pandas DataFrame.
- Return type
pandas.DataFrame | dict[str, pandas.DataFrame] | dict[int, pandas.DataFrame]
- class cognite.client.data_classes.sequences.SequenceUpdate(id: Optional[int] = None, external_id: Optional[str] = None)
Bases:
CogniteUpdate
No description.
- Parameters
id (int) – A server-generated ID for the object.
external_id (str) – The external ID provided by the client. Must be unique for the resource type.
- class cognite.client.data_classes.sequences.SequenceWrite(columns: Sequence[SequenceColumnWrite], name: Optional[str] = None, description: Optional[str] = None, asset_id: Optional[int] = None, external_id: Optional[str] = None, metadata: Optional[dict[str, Any]] = None, data_set_id: Optional[int] = None)
Bases:
SequenceCore
Information about the sequence stored in the database. This is the writing version of the class, it is used for inserting data into the CDF.
- Parameters
columns (Sequence[SequenceColumnWrite]) – List of column definitions
name (str | None) – Name of the sequence
description (str | None) – Description of the sequence
asset_id (int | None) – Optional asset this sequence is associated with
external_id (str | None) – The external ID provided by the client. Must be unique for the resource type.
metadata (dict[str, Any] | None) – Custom, application-specific metadata. String key -> String value. Th maximum length of key is 32 bytes, value 512 bytes, up to 16 key-value pairs.
data_set_id (int | None) – Data set that this sequence belongs to
- as_write() SequenceWrite
Returns this SequenceWrite.
- dump(camel_case: bool = True) dict[str, Any]
Dump the instance into a json serializable Python data type.
- Parameters
camel_case (bool) – Use camelCase for attribute names. Defaults to True.
- Returns
A dictionary representation of the instance.
- Return type
dict[str, Any]
- class cognite.client.data_classes.sequences.SequenceWriteList(resources: Iterable[Any], cognite_client: CogniteClient | None = None)
Bases:
CogniteResourceList
[SequenceWrite
],ExternalIDTransformerMixin
- class cognite.client.data_classes.sequences.SortableSequenceProperty(value)
Bases:
EnumProperty
An enumeration.