# Dataset Toolkit: Dedup, Merge, Diff, Flatten (`rivetfinch/dataset-toolkit`) Actor

Remove duplicates, merge datasets, get new, changed and removed rows since the last run, or flatten nested data for spreadsheets. Streams millions of rows in 1 GB, works with limited permissions, integrations and AI agents, and never fails a run over empty data.

- **URL**: https://apify.com/rivetfinch/dataset-toolkit.md
- **Developed by:** [Rivetfinch](https://apify.com/rivetfinch) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.02 / 1,000 row processeds

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Dataset Toolkit: Dedup, Merge, Diff, Flatten

Clean up and compare Apify datasets without writing code. Pick one or more datasets, choose an operation, and get the result as a new dataset. It is built for scheduled pipelines and AI agents: it runs with limited permissions, reads millions of rows in the default 1 GB of memory, and never fails a run because a dataset is empty.

### What you get

**Diff** tells you what changed since the last scrape. Every output row is your own row plus two columns:

```json
[
  {"url": "https://shop.example.com/p/1", "title": "Trail Running Shoe", "price": 89.0, "inStock": true,
   "_change": "changed", "_changedFields": ["price"]},
  {"url": "https://shop.example.com/p/3", "title": "Merino Base Layer", "price": 59.5, "inStock": false,
   "_change": "new", "_changedFields": []},
  {"url": "https://shop.example.com/p/9", "title": "Camping Mug", "price": 12.0, "inStock": true,
   "_change": "removed", "_changedFields": []}
]
```

- `_change` is `new`, `changed` or `removed` (and `unchanged` if you ask for those rows too).
- `_changedFields` names the fields that differ, so `["price"]` means only the price moved.
- This example compares with a **base dataset**, so a removed row is the old row as it was there.
- In the **change feed** (diff against the previous run) a removed row carries only its key fields, because only fingerprints are remembered:

```json
{"url": "https://shop.example.com/p/9", "_change": "removed", "_changedFields": []}
```

**Dedup** keeps one row per key. With Key fields set to `url` and "Ignore extra spaces" on (the default), this input:

| url | title | price |
|---|---|---|
| https://shop.example.com/p/1 | Trail Running Shoe | 89 |
| https://shop.example.com/p/2 | Rain Jacket | 129 |
| https://shop.example.com/p/1 | Trail Running Shoe | 89 |
| ␣␣https://shop.example.com/p/2␣ | Rain Jacket | 129 |

becomes:

| url | title | price |
|---|---|---|
| https://shop.example.com/p/1 | Trail Running Shoe | 89 |
| https://shop.example.com/p/2 | Rain Jacket | 129 |

The status message says what happened in one line. On the built-in sample (6 rows) it reads: *Dedup: 4 rows from 6 items in 1 dataset; 2 duplicates removed.* A `SUMMARY` record in the run's key-value store has the details per dataset.

Try it with an empty input first: the Actor then runs on a small built-in sample, free of charge, so you can see the output. Any other input that names no dataset gives 0 rows and says what is missing.

### Operations

Choose one under **Operation**. Every operation reads the datasets in the order you list them, streams them page by page, and writes to this run's own dataset.

#### Dedup: remove duplicates

| Field | What it does |
|---|---|
| Datasets | One or more datasets. Duplicates are removed across all of them. |
| Key fields | Fields that make two rows the same record, such as `url` or `email`. Several fields are combined (`sku` + `store`). Dot paths reach nested fields (`seller.id`). Empty: rows must match in every field. |
| Ignore fields | With no key fields, leave these out of the comparison (for example `scrapedAt`). |
| Ignore upper and lower case in keys | `Example.com` and `example.com` count as the same. Off by default. |
| Ignore extra spaces in keys | Trims spaces at the ends and collapses runs of spaces. On by default. |
| Which duplicate to keep | `first` (default) or `last`. Last reads the data twice. |
| Output duplicates only | Output the rows dedup would remove instead, to check what counts as a duplicate. |

Rows that have none of the key fields are kept and counted in `SUMMARY.itemsWithoutKey`.

#### Merge: combine datasets

Joins the datasets into one, in order. Rows may have different columns. Set Key fields to also remove duplicates (same options as dedup). Turn on **Add source dataset column** to get `_sourceDatasetId` on every row (this works in every operation).

#### Diff: new, changed and removed rows

| Field | What it does |
|---|---|
| Datasets | The new version. |
| Base dataset | The old version. Leave empty to compare with the previous run instead (see below). |
| Key fields | What identifies the same record in both versions, such as `url` or `id`. Without key fields, rows are matched by their whole content, so a changed row shows as one removed and one new row. |
| Compare fields | Only these fields count as a change, for example `price` and `inStock`. Empty compares every field. |
| Ignore fields | Fields that change on every scrape and should not count, such as `scrapedAt`. Dot paths work (`meta.fetchedAt`). |
| Include unchanged rows | Also output unchanged rows, labelled `unchanged`. |
| Name the changed fields | Fill `_changedFields` (on by default). |

Output order: new and changed rows in the order of the new data, then removed rows. A missing field and a field set to `null` count as the same. A change inside a nested object is named by its top-level field (`brand`), unless you list the nested path in Compare fields.

**Diff against the previous run.** Leave Base dataset empty and set a **State name** such as `daily-products`. Each run remembers a fingerprint of every row under that name, in a key-value store the Actor creates in your account (`dataset-toolkit-state`). The next run with the same state name outputs only what is new, changed or removed since then. Put it on a schedule after your scraper and you get a change feed.

- A State name is required, unless the Actor runs from a saved task: then the task gets its own state (`task-<task ID>`).
- The first run outputs every row as `new`.
- Removed rows carry the key fields only (for example just the `url`), because the Actor stores fingerprints, not your data.
- **Broken scrapes don't wipe the state.** If the input is empty, or more than half of the remembered rows are missing, nothing is reported as removed, the state is kept, and the run says so. Turn on **Allow mass removal** when the rows really are gone.
- Rows skipped by Skip first rows are not remembered, so they come back next run.
- If you change Key fields, Compare fields, Ignore fields or the case and space options, the saved state starts again and the run says so.
- Rows the run could not deliver (it hit Max rows or your maximum cost) are not remembered, so they come back next run. Removed rows are only reported after a run that read every input to the end.

#### Flatten: nested data into plain columns

Turns `{"brand": {"name": "Northpeak"}, "tags": ["running", "trail"]}` into `brand.name`, `tags.0`, `tags.1` columns for spreadsheets and CSV.

| Field | What it does |
|---|---|
| Column separator | `.` by default; `_` gives `brand_name`. |
| Lists | `index`: one column per element. `join`: plain values in one cell (`running, trail`). `json`: the list as JSON text. |
| Join lists with | The text between joined values. |
| Max depth | How many levels to open; deeper objects stay as JSON text. |
| Keep only the first N list elements | So 50 images don't become 50 columns. |

#### Shape the output (every operation)

Applied to each output row in this order:

1. **Filter**: Filter field plus Filter pattern (text or a regular expression, ignoring case), and Filter mode keep or drop. With no pattern, a row matches when the field has any value. In diff you can filter on `_change`, for example the pattern `^new$`.
2. **Pick fields**: only these columns, in this order. A dot path such as `address.city` becomes a column named `address.city`; a missing value comes out empty. `_change`, `_changedFields` and `_sourceDatasetId` are always kept.
3. **Omit fields**: drop these columns (dot paths drop nested fields).
4. **Rename fields**: an object of old name to new name, for example `{"title": "name"}`.
5. **Skip first rows** and **Max rows** (offset and limit).

### Pricing

**$0.02 per 1,000 rows processed** ($0.00002 per row).

- **What counts:** each row read from your input datasets, including the base dataset in a diff. Each row counts once, even when an operation reads the data twice. You pay for the exact number of rows, with no rounding.
- **What you pay for is input, not output:** a diff that finds only a handful of changes in a million rows costs the same as one that finds many.
- **Your maximum cost per run is respected.** The run stops reading when it is reached and still delivers the rows it has finished. A diff run then remembers only the rows you received, so the rest come back next time.

### Use it in a pipeline

**After a scraper (integration).** On your scraper, add an integration that runs this Actor when a run succeeds, and in its input put:

```json
{
  "operation": "dedup",
  "datasetId": "{{resource.defaultDatasetId}}",
  "keyFields": ["url"]
}
```

`Dataset ID` is the field made for this: it gives the run read access to the scraper's dataset. If the scraper's run had no results, this run succeeds with no rows instead of failing.

**A daily change feed.** Schedule a task with:

```json
{
  "operation": "diff",
  "datasetId": "{{resource.defaultDatasetId}}",
  "keyFields": ["url"],
  "ignoreFields": ["scrapedAt"],
  "stateName": "daily-products"
}
```

Each run outputs only new, changed and removed products. Chain another integration (email, Sheets, a webhook) on this Actor's dataset to get alerts.

**Through the API.** Pass dataset IDs in `datasets` (a named dataset as `username~dataset-name`):

```json
{"operation": "merge", "datasets": ["aBcD1234eFgH5678i", "jKlM9012nOpQ3456r"], "keyFields": ["email"], "caseInsensitive": true}
```

### Use it from an AI agent

The Actor runs with limited permissions, so agents using Apify's MCP server can call it. Tips for agents:

- Put dataset IDs in `datasets` (an array of strings). That field grants read access; `datasetIds` does not (see Limits).
- `keyFields` are the fields that identify a duplicate; `pickFields` are the columns to return. They are different settings.
- Read the run's status message first: it says how many rows came out and names any dataset that could not be read, with the fix. Unknown input keys are listed there too, never silently ignored.
- The `SUMMARY` record in the default key-value store has per-dataset counts.

Example request: "Remove duplicate leads by email from datasets A and B, ignoring case, and return only name, email and company":

```json
{"operation": "dedup", "datasets": ["A", "B"], "keyFields": ["email"], "caseInsensitive": true, "pickFields": ["name", "email", "company"]}
```

### Run summary

The `SUMMARY` record holds, per input dataset: the status (`ok`, `empty`, `not_found`, `no_access`, `invalid` or `error`), items read, whether it was read to the end, time taken, and a message with the fix when something went wrong. It also has rows out per change type, duplicates found and removed, rows filtered out, rows without a key, why the run stopped early (row limit or cost limit), unknown input keys, warnings, and the diff state's size.

### Limits and good to know

- **Limited permissions (checked 2026-11-18 against Apify's documentation).** The Actor can read your datasets only when they are named in a field that declares a dataset resource: **Datasets**, **Base dataset** and **Dataset ID**. Apify adds those to the run's access at start, whether you pick them or type an ID or name, including from the API, an agent or an integration template such as `{{resource.defaultDatasetId}}`. Anything else is outside that access:
  - **Dataset or run IDs as text** (`datasetIds`) take IDs, `username~dataset-name` or Apify links, not plain names. They are tried, and read only when Apify allows it, for example a dataset set to "Anyone with ID can read". Otherwise the run names each one and tells you to move it to Datasets.
  - The Actor never creates a dataset: a name Apify doesn't resolve is reported as not found.
  - **Run IDs** are looked up to find the run's dataset, which needs read access to that run. When Apify refuses, the run says so; use the run's dataset ID in Datasets instead.
  - **The integration payload.** When the Actor is started by an integration and no dataset is given anywhere else, it tries the triggering run's dataset from the payload. Apify's documentation does not say whether that read is allowed, so put `{{resource.defaultDatasetId}}` in Dataset ID as shown above; that always works.
- **Output** always goes to this run's own dataset, which works under limited permissions. The diff state lives in a key-value store the Actor creates, named `dataset-toolkit-state`.
- **Memory.** The Actor keeps a short fingerprint per row, never the rows. Tested on generated product data (about 450 bytes per row) with 1,000,000 rows: dedup used about 130 MB, dedup keeping the last duplicate about 170 MB, diff against a base dataset about 230 MB and diff against the previous run about 370 MB, all inside the default 1 GB. Diff against the previous run needs roughly 300 bytes per remembered row of 12 fields; each extra field adds 4 bytes while Name the changed fields is on.
- **Too big for the memory you picked?** Before reading anything, the run estimates the memory it needs from the datasets' sizes. If that doesn't fit, it stops at once, charges nothing, and says which memory setting to rerun with.
- **Diff against a base dataset reads the base twice** (once to remember it, once to output removed rows). The second read is skipped when nothing was removed.
- **Order.** Rows come out in input order. With Which duplicate to keep set to last, the kept row appears where its last copy was.
- **Numbers.** In diff, `1` and `1.0` count as the same value. As a key, `"1"` (text) and `1` count as the same, but in diff a switch from one to the other is a change.
- **Safe to restart.** If Apify moves the run to another server or restarts it, the run continues where it stopped. Rows already delivered are not delivered or charged again, and the diff state is saved once. Progress is kept in the run's own key-value store under `PROGRESS` and removed when the run finishes.
- **Never fails over data.** An empty dataset gives a successful run with 0 rows. A dataset that can't be read is named in the status message with the fix, and the other datasets are still processed. The run only fails when the input itself can't be used, such as an invalid regular expression, and the message says what to change.

# Actor input Schema

## `operation` (type: `string`):

Dedup removes duplicate rows. Merge joins datasets into one (and removes duplicates if you set Key fields). Diff compares with a base dataset or with the previous run and labels rows new, changed or removed. Flatten turns nested objects into plain columns for spreadsheets.

## `datasets` (type: `array`):

The datasets to process, read in this order. Pick them from your account. In the API or from an AI agent, pass dataset IDs here, for example \["aBcD1234eFgH5678i"]. With a completely empty input the run shows a free built-in sample.

## `keyFields` (type: `array`):

Fields that say two rows are the same record, for example url or email. Several fields are combined (sku + store). Dot paths reach nested fields (seller.id). Empty: dedup compares whole rows; diff matches whole rows. Not the columns to output: that is Pick fields.

## `ignoreFields` (type: `array`):

Fields left out when whole rows are compared: in diff, and in dedup without key fields. Use it for values that change on every scrape, such as scrapedAt or a position number. Dot paths work.

## `caseInsensitive` (type: `boolean`):

Treat Example.com and example.com as the same key.

## `trimWhitespace` (type: `boolean`):

Trim spaces at the ends of key values and collapse runs of spaces inside them before comparing.

## `keep` (type: `string`):

First keeps the earliest row (datasets are read in the order listed). Last keeps the latest one, which needs a second read of the data.

## `outputDuplicatesOnly` (type: `boolean`):

Output the rows that dedup would remove, instead of the unique rows. Handy for checking what counts as a duplicate.

## `addSourceDatasetId` (type: `boolean`):

Add \_sourceDatasetId to every row, saying which dataset it came from.

## `baseDataset` (type: `string`):

Diff only. The older dataset to compare against; Datasets above hold the new version. Leave empty to compare with the previous run of this Actor that used the same State name.

## `stateName` (type: `string`):

Needed for diff without a base dataset (a saved task gets its own state automatically). Each run remembers its rows under this name and the next run is compared with them, so a scheduled pipeline gets only new, changed and removed rows. One name per pipeline. Letters, digits and dashes.

## `compareFields` (type: `array`):

Diff only. Count a row as changed only when one of these fields differs, for example price and stock. Empty compares every field except Ignore fields.

## `includeUnchanged` (type: `boolean`):

Diff only. Also output rows that did not change, labelled unchanged, to get the full current list with labels.

## `reportChangedFields` (type: `boolean`):

Diff only. Fill \_changedFields with the names of the fields that changed. Turning it off saves memory on very wide rows; changed rows then carry null there.

## `allowMassRemoval` (type: `boolean`):

Diff against the previous run only. By default, when the input is empty or more than half of the remembered rows are missing, nothing is reported as removed and the state is kept, because that usually means a broken scrape. Turn on when the rows really are gone.

## `separator` (type: `string`):

Flatten only. Joins nested names into one column name: brand.name with a dot, brand_name with an underscore.

## `arrays` (type: `string`):

Flatten only. Index gives one column per element (tags.0, tags.1). Join puts a list of plain values into one text cell (running, trail); lists of objects stay indexed. JSON keeps the list as JSON text in one cell.

## `arrayJoiner` (type: `string`):

Flatten only, with Lists set to join. Text placed between the values.

## `maxDepth` (type: `integer`):

Flatten only. How many levels to open. Deeper objects stay as JSON text in one cell. 0 means no limit.

## `maxArrayItems` (type: `integer`):

Flatten only. Cut every list to its first N elements before flattening, so 50 images don't become 50 columns. 0 keeps all.

## `pickFields` (type: `array`):

Output only these columns, in this order. A dot path such as address.city becomes a column named address.city. Missing values come out empty. The \_change, \_changedFields and \_sourceDatasetId columns are always kept. Empty outputs every column.

## `omitFields` (type: `array`):

Remove these columns from the output. Dot paths remove nested fields (seller.phone).

## `renameFields` (type: `object`):

Old column name to new name, for example {"title": "name", "address.city": "city"}.

## `filterField` (type: `string`):

Keep or drop rows by the value of this field (dot paths work; \_change works in diff). With no pattern, a row matches when the field has any value.

## `filterPattern` (type: `string`):

Text or regular expression searched in the filter field, ignoring case. remote matches Remote job; ^new$|^changed$ matches exactly those. Lists and objects are searched as JSON text.

## `filterMode` (type: `string`):

Keep only matching rows, or drop matching rows.

## `offset` (type: `integer`):

Skip this many output rows (after the filter). Skipped rows are not charged.

## `limit` (type: `integer`):

Stop after this many output rows. 0 means no limit. Your maximum cost per run is also respected.

## `datasetId` (type: `string`):

One more dataset, typed as an ID or name. For an integration that runs after another Actor, put {{resource.defaultDatasetId}} here; this field gives the run read access to that dataset.

## `datasetIds` (type: `array`):

Dataset IDs, run IDs or Apify dataset links typed as text. This Actor runs with limited permissions, so Apify may refuse these reads; the run then names each one and tells you to move it to Datasets, which always works.

## `payload` (type: `object`):

Filled in by Apify when this Actor runs as an integration. When no dataset is given anywhere else, the triggering run's dataset is tried from here.

## Actor input object example

```json
{
  "operation": "dedup",
  "keyFields": [
    "url"
  ],
  "ignoreFields": [
    "scrapedAt"
  ],
  "caseInsensitive": false,
  "trimWhitespace": true,
  "keep": "first",
  "outputDuplicatesOnly": false,
  "addSourceDatasetId": false,
  "stateName": "daily-products",
  "compareFields": [
    "price",
    "inStock"
  ],
  "includeUnchanged": false,
  "reportChangedFields": true,
  "allowMassRemoval": false,
  "separator": ".",
  "arrays": "index",
  "arrayJoiner": ", ",
  "maxDepth": 0,
  "maxArrayItems": 0,
  "pickFields": [
    "url",
    "title",
    "price"
  ],
  "omitFields": [
    "html",
    "scrapedAt"
  ],
  "renameFields": {
    "title": "name"
  },
  "filterField": "title",
  "filterPattern": "remote",
  "filterMode": "keep",
  "offset": 0,
  "limit": 0
}
```

# Actor output Schema

## `results` (type: `string`):

The output rows: unique rows (dedup), all rows (merge, flatten) or new, changed and removed rows (diff).

## `summary` (type: `string`):

JSON record: per input dataset the status and items read, rows out per change type, duplicates removed, problems with how to fix them, and timing.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {};

// Run the Actor and wait for it to finish
const run = await client.actor("rivetfinch/dataset-toolkit").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {}

# Run the Actor and wait for it to finish
run = client.actor("rivetfinch/dataset-toolkit").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{}' |
apify call rivetfinch/dataset-toolkit --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,rivetfinch/dataset-toolkit"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/2nKDGzyRBqaCDmbVQ/builds/Uy1BTEvzLxPGYqVHh/openapi.json
