Skip to content

IncrementalDataset

IncrementalDataset is used to manage datasets that grow incrementally over time.

kedro_datasets.partitions.IncrementalDataset

IncrementalDataset(
    *,
    path,
    dataset,
    checkpoint=None,
    filepath_arg="filepath",
    filename_suffix="",
    credentials=None,
    load_args=None,
    fs_args=None,
    metadata=None
)

Bases: PartitionedDataset

IncrementalDataset inherits from PartitionedDataset, which loads and saves partitioned file-like data using the underlying dataset definition. For filesystem level operations it uses fsspec: https://github.com/intake/filesystem_spec. IncrementalDataset also stores the information about the last processed partition in so-called checkpoint that is persisted to the location of the data partitions by default, so that subsequent pipeline run loads only new partitions past the checkpoint.

Examples:

Using the Python API:

>>> from kedro_datasets.partitions import IncrementalDataset
>>>
>>> dataset = IncrementalDataset(
...     path=str(tmp_path / "test_data"), dataset="pandas.CSVDataset"
... )
>>> loaded = dataset.load()  # loads all available partitions
>>> # assert isinstance(loaded, dict)
>>>
>>> dataset.confirm()  # update checkpoint value to the last processed partition ID
>>> reloaded = dataset.load()  # still loads all available partitions
>>>
>>> dataset.release()  # clears load cache
>>> # returns an empty dictionary as no new partitions were added
>>> assert dataset.load() == {}

Parameters:

  • path (str | PathLike) –

    Path to the folder containing partitioned data. Accepts strings and os.PathLike objects. If path starts with the protocol (e.g., s3://) then the corresponding fsspec concrete filesystem implementation will be used. If protocol is not specified, fsspec.implementations.local.LocalFileSystem will be used. Note: Some concrete implementations are bundled with fsspec, while others (like s3 or gcs) must be installed separately prior to usage of the PartitionedDataset.

  • dataset (str | type[AbstractDataset] | dict[str, Any]) –

    Underlying dataset definition. This is used to instantiate the dataset for each file located inside the path. Accepted formats are: a) object of a class that inherits from AbstractDataset b) a string representing a fully qualified class name to such class c) a dictionary with type key pointing to a string from b), other keys are passed to the Dataset initializer. Credentials for the dataset can be explicitly specified in this configuration.

  • checkpoint (str | dict[str, Any] | None, default: None ) –

    Optional checkpoint configuration. Accepts a dictionary with the corresponding dataset definition including filepath (unlike dataset argument). Checkpoint configuration is described here: https://docs.kedro.org/en/stable/data/partitioned_and_incremental_datasets.html#checkpoint-configuration Credentials for the checkpoint can be explicitly specified in this configuration.

  • filepath_arg (str, default: 'filepath' ) –

    Underlying dataset initializer argument that will contain a path to each corresponding partition file. If unspecified, defaults to "filepath".

  • filename_suffix (str, default: '' ) –

    If specified, only partitions that end with this string will be processed.

  • credentials (dict[str, Any] | None, default: None ) –

    Protocol-specific options that will be passed to fsspec.filesystem https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.filesystem, the dataset initializer and the checkpoint. If the dataset or the checkpoint configuration contains explicit credentials spec, then such spec will take precedence. All possible credentials management scenarios are documented here: https://docs.kedro.org/en/stable/data/partitioned_and_incremental_datasets.html#partitioned-dataset-credentials

  • load_args (dict[str, Any] | None, default: None ) –

    Keyword arguments to be passed into find() method of the filesystem implementation.

  • fs_args (dict[str, Any] | None, default: None ) –

    Extra arguments to pass into underlying filesystem class constructor (e.g. {"project": "my-project"} for GCSFileSystem).

  • metadata (dict[str, Any] | None, default: None ) –

    Any arbitrary metadata. This is ignored by Kedro, but may be consumed by users or external plugins.

Raises:

  • DatasetError –

    If versioning is enabled for the checkpoint dataset.

Source code in kedro_datasets/partitions/incremental_dataset.py
 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
def __init__(  # noqa: PLR0913
    self,
    *,
    path: str | os.PathLike,
    dataset: str | type[AbstractDataset] | dict[str, Any],
    checkpoint: str | dict[str, Any] | None = None,
    filepath_arg: str = "filepath",
    filename_suffix: str = "",
    credentials: dict[str, Any] | None = None,
    load_args: dict[str, Any] | None = None,
    fs_args: dict[str, Any] | None = None,
    metadata: dict[str, Any] | None = None,
) -> None:
    """Creates a new instance of ``IncrementalDataset``.

    Args:
        path: Path to the folder containing partitioned data. Accepts strings
            and ``os.PathLike`` objects.
            If path starts with the protocol (e.g., ``s3://``) then the
            corresponding ``fsspec`` concrete filesystem implementation will
            be used. If protocol is not specified,
            ``fsspec.implementations.local.LocalFileSystem`` will be used.
            **Note:** Some concrete implementations are bundled with ``fsspec``,
            while others (like ``s3`` or ``gcs``) must be installed separately
            prior to usage of the ``PartitionedDataset``.
        dataset: Underlying dataset definition. This is used to instantiate
            the dataset for each file located inside the ``path``.
            Accepted formats are:
            a) object of a class that inherits from ``AbstractDataset``
            b) a string representing a fully qualified class name to such class
            c) a dictionary with ``type`` key pointing to a string from b),
            other keys are passed to the Dataset initializer.
            Credentials for the dataset can be explicitly specified in
            this configuration.
        checkpoint: Optional checkpoint configuration. Accepts a dictionary
            with the corresponding dataset definition including ``filepath``
            (unlike ``dataset`` argument). Checkpoint configuration is
            described here:
            https://docs.kedro.org/en/stable/data/partitioned_and_incremental_datasets.html#checkpoint-configuration
            Credentials for the checkpoint can be explicitly specified
            in this configuration.
        filepath_arg: Underlying dataset initializer argument that will
            contain a path to each corresponding partition file.
            If unspecified, defaults to "filepath".
        filename_suffix: If specified, only partitions that end with this
            string will be processed.
        credentials: Protocol-specific options that will be passed to
            ``fsspec.filesystem``
            https://filesystem-spec.readthedocs.io/en/latest/api.html#fsspec.filesystem,
            the dataset initializer and the checkpoint. If
            the dataset or the checkpoint configuration contains explicit
            credentials spec, then such spec will take precedence.
            All possible credentials management scenarios are documented here:
            https://docs.kedro.org/en/stable/data/partitioned_and_incremental_datasets.html#partitioned-dataset-credentials
        load_args: Keyword arguments to be passed into ``find()`` method of
            the filesystem implementation.
        fs_args: Extra arguments to pass into underlying filesystem class constructor
            (e.g. `{"project": "my-project"}` for ``GCSFileSystem``).
        metadata: Any arbitrary metadata.
            This is ignored by Kedro, but may be consumed by users or external plugins.

    Raises:
        DatasetError: If versioning is enabled for the checkpoint dataset.
    """

    super().__init__(
        path=path,
        dataset=dataset,
        filepath_arg=filepath_arg,
        filename_suffix=filename_suffix,
        credentials=credentials,
        load_args=load_args,
        fs_args=fs_args,
    )

    self._checkpoint_config = self._parse_checkpoint_config(checkpoint)
    self._force_checkpoint = self._checkpoint_config.pop("force_checkpoint", None)
    self.metadata = metadata

    comparison_func = self._checkpoint_config.pop("comparison_func", operator.gt)
    if isinstance(comparison_func, str):
        comparison_func = load_obj(comparison_func)
    self._comparison_func = comparison_func

DEFAULT_CHECKPOINT_FILENAME class-attribute instance-attribute

DEFAULT_CHECKPOINT_FILENAME = 'CHECKPOINT'

DEFAULT_CHECKPOINT_TYPE class-attribute instance-attribute

DEFAULT_CHECKPOINT_TYPE = 'kedro_datasets.text.TextDataset'

metadata instance-attribute

metadata = metadata

confirm

confirm()

Confirm the dataset by updating the checkpoint value to the latest processed partition ID

Source code in kedro_datasets/partitions/incremental_dataset.py
281
282
283
284
285
286
def confirm(self) -> None:
    """Confirm the dataset by updating the checkpoint value to the latest
    processed partition ID"""
    partition_ids = [self._path_to_partition(p) for p in self._list_partitions()]
    if partition_ids:
        self._checkpoint.save(partition_ids[-1])  # checkpoint to last partition

load

load()
Source code in kedro_datasets/partitions/incremental_dataset.py
267
268
269
270
271
272
273
274
275
276
277
278
279
def load(self) -> dict[str, Callable[[], Any]]:
    partitions: dict[str, Any] = {}

    for partition in self._list_partitions():
        partition_id = self._path_to_partition(partition)
        kwargs = deepcopy(self._dataset_config)
        # join the protocol back since PySpark may rely on it
        kwargs[self._filepath_arg] = self._join_protocol(partition)
        partitions[partition_id] = self._dataset_type(  # type: ignore
            **kwargs
        ).load()

    return partitions

save

save(data)
Source code in kedro_datasets/partitions/partitioned_dataset.py
324
325
326
327
328
329
330
331
332
333
334
335
336
337
def save(self, data: dict[str, Any]) -> None:
    if self._overwrite and self._filesystem.exists(self._normalized_path):
        self._filesystem.rm(self._normalized_path, recursive=True)

    for partition_id, partition_data in sorted(data.items()):
        kwargs = deepcopy(self._dataset_config)
        partition = self._partition_to_path(partition_id)
        # join the protocol back since tools like PySpark may rely on it
        kwargs[self._filepath_arg] = self._join_protocol(partition)
        dataset = self._dataset_type(**kwargs)  # type: ignore
        if callable(partition_data) and self._save_lazily:
            partition_data = partition_data()  # noqa: PLW2901
        dataset.save(partition_data)
    self._invalidate_caches()