# Incremental Loading

Extracting data incrementally is universally beneficial — it **speeds up the extraction** and **lowers the load** on both the API and
[Keboola Storage](https://help.keboola.com/storage/) (thus saving 
[credits](https://help.keboola.com/management/project/limits/#project-power--time-credits)).

**Before you start**

You need:

- **A Generic Extractor configuration that already extracts the data in full.**
- **An API that can filter by time,** for example with a `modified_since` parameter. Check its documentation for such a parameter and the format it expects.
- **The columns that identify a row,** if the API returns modified entries: you set them as the primary key in the mappings (/components/extractors/generic-extractor/configuration/config/mappings/).

## Options
After you have incrementally extracted data from an API, the data must be 
[incrementally loaded](https://help.keboola.com/storage/tables/incremental-loading/#incremental-loading)
into Storage. To do that, simply set `"incrementalOutput": true` in the `config` section. 

There are, however, a number of implications in the incremental loads. It essentially boils downs to the following use cases, 
depending on what kind of data you are importing (extracting from an API):

- The imported data contains only **added entries**. When `incrementalOutput` is turned on, the data will be 
simply appended to the target table in Storage. Turning `incrementalOutput` to false probably makes no sense 
because the table will contain only the new entries.
- The imported data contains **added and modified entries**. When `incrementalOutput` is turned on, set a primary key on the table so that new rows are added and existing [rows are updated](https://help.keboola.com/storage/tables/incremental-loading/#primary-key-deduplication). 
If the primary key is not set, the modified entries will be duplicated in the target table. Turning 
`incrementalOutput` to false probably makes no sense because the table will contain only the new entries.
- The imported data contains **all rows**. In this case, set a primary key for the table or turn 
`incrementalOutput` to false. Turning `incrementalOutput` to true probably makes no sense because the table will 
contain duplicate entries. If you set the primary key, new rows will be added and modified rows will be updated. 
Note that in this case more [credits](https://help.keboola.com/management/project/limits/#project-power--time-credits) are consumed.

In neither of these situations will the missing rows get deleted. If you want to do so, the only way is 
to turn `incrementalOutput` to false and do full loads. 

Generic Extractor supports incremental loads by using [`previousStart`](https://help.keboola.com/components/extractors/generic-extractor/functions/#parameters-context) and the
[`time` function](https://help.keboola.com/components/extractors/generic-extractor/functions/#time).

## Examples

### Previous start example
Assume you have an API supporting a parameter `modified_since` which expects a 
[Unix Timestamp](https://en.wikipedia.org/wiki/Unix_time). The response then contains only the 
records that were modified after the specified date. The following configuration can be used:

```json
{
    "config": {
        "incrementalOutput": true,
        "outputBucket": "mock-server",
        "jobs": [
            {
                "endpoint": "users",
                "dataType": "users",
                "params": {
                    "modified_since": {
                        "time": "previousStart"
                    }
                }
            }
        ]
    }
}
```

The configuration adds the `modified_since` parameter as a reference to the internal 
[`time.previousStart` value](https://help.keboola.com/components/extractors/generic-extractor/functions/#parameters-context), which contains the timestamp of the last 
**successful start** of the extraction of the particular configuration. The request generated by this configuration is something like:

```
GET /users?modified_since=1492606006
```

where `1492606006` is the variable timestamp of the last successful start. This introduces state into the
Generic Extractor configuration as it now remembers when it last successfully ran. This means 
that if you run the above configuration every five minutes, it will extract the data modified within the last five minutes. 
If you run it every hour, it will extract the data modified within the last hour. 

Should one of the runs fail or be skipped for any reason, the extraction will pick up where it ended the last time it was successful. 
See [example [EX107]](https://github.com/keboola/generic-extractor/tree/master/doc/examples/107-incremental-load).

The last successful time is stored in the [configuration state](https://help.keboola.com/extend/common-interface/config-file/#state-file).
If for some reason you need to reset it, 
[update the configuration via API](https://api.keboola.com/?service=storage#put-/v2/storage/branch/-branchId-/components/-componentId-/configs/-configurationId-).

### Previous start date
If an API similar to the one in the [above example](https://help.keboola.com/components/extractors/generic-extractor/incremental/#previous-start-example) requires the date to be 
sent as a string, the following jobs configuration (which uses the [`date` function](https://help.keboola.com/components/extractors/generic-extractor/functions/#date))
can be used:

```json
{
    "jobs": [
        {
            "endpoint": "users",
            "dataType": "users",
            "params": {
                "modified_since": {
                    "function": "date",
                    "args": [
                        "Y-m-d H:i:s",
                        {
                            "time": "previousStart"
                        }
                    ]
                }
            }
        }
    ]
}
```

This sends a request like:

```
GET /users?modified_since=2017-04-19%2012%3A46%3A46
```

in a more readable [url-decoded](https://meyerweb.com/eric/tools/dencoder/) form:

```
GET /users?modified_since=2017-04-19 12:46:46
```

Otherwise the configuration behaves the same way as the [previous example](https://help.keboola.com/components/extractors/generic-extractor/incremental/#previous-start-example).

See [example [EX108]](https://github.com/keboola/generic-extractor/tree/master/doc/examples/108-incremental-load-date).

### Incremental load from to
Another option is an API which requires the `from` and `to` parameters. The following
configuration generates the `from` date as the date of the last extraction (using the [`time.previousStart` 
value](https://help.keboola.com/components/extractors/generic-extractor/functions/#parameters-context)). It also generates the `to` date as the date 
of the current extraction (using the [`time.currentStart` value](https://help.keboola.com/components/extractors/generic-extractor/functions/#parameters-context)):

```json
{
    "jobs": [
        {
            "endpoint": "users",
            "dataType": "users",
            "params": {
                "from": {
                    "function": "date",
                    "args": [
                        "Y-m-d",
                        {
                            "time": "previousStart"
                        }
                    ]
                },
                "to": {
                    "function": "date",
                    "args": [
                        "Y-m-d",
                        {
                            "time": "currentStart"
                        }
                    ]
                }
            }
        }
    ]
}
```

This configuration will send a request similar to this one:

```
GET /109-incremental-load-from-to/users?from=2017-04-19&to=2017-04-24
```

See [example [EX109]](https://github.com/keboola/generic-extractor/tree/master/doc/examples/109-incremental-load-from-to).

### Incremental relative load
Suppose you have an API supporting the `from` and `to` parameters as in [the above example](https://help.keboola.com/components/extractors/generic-extractor/incremental/#incremental-load-from-to) and 
want to extract the last day data. It can be done using the following configuration:

```json
{
    "jobs": [
        {
            "endpoint": "users",
            "dataType": "users",
            "params": {
                "from": {
                    "function": "date",
                    "args": [
                        "Y-m-d",
                        {
                            "function": "strtotime",
                            "args": [
                                "-1 day",
                                {
                                    "time": "currentStart"
                                }
                            ]
                        }
                    ]
                },
                "to": {
                    "function": "date",
                    "args": [
                        "Y-m-d",
                        {
                            "time": "currentStart"
                        }
                    ]
                }
            }
        }
    ]
}
```

This configuration leads to a request similar to this one:

```
GET /110-incremental-relative/users?from=2017-04-23&to=2017-04-24
```

Remember, this is not a truly reliable incremental load. If you put such configuration 
into an orchestration, and the configuration does not run for some reason, you may miss some data. 
However, this may still be a useful approach for obtaining samples of data for POCs.

See [example [EX110]](https://github.com/keboola/generic-extractor/tree/master/doc/examples/110-incremental-relative).

**Check:** run the configuration twice with `"debug": true`. In the second job's events, the request carries a
later date than in the first, and the table in Storage gains only new or changed rows.

---

**Next:** [Running Generic Extractor →](https://help.keboola.com/components/extractors/generic-extractor/running/)
