# Dataset Diff, Dedupe & Merge - Change Detection (`noisy_jubilee/dataset-diff-dedupe`) Actor

Compare today's scrape with the last run and get only new, changed and removed rows, with previous values. Also dedupes and merges Apify datasets, CSV and JSON by key fields.

- **URL**: https://apify.com/noisy_jubilee/dataset-diff-dedupe.md
- **Developed by:** [Stephen](https://apify.com/noisy_jubilee) (community)
- **Categories:** Developer tools, Automation
- **Stats:** 2 total users, 1 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.01 / 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 Diff, Dedupe & Merge - Change Detection

Run your scraper every day, then run this Actor to get **only what changed**: new rows, changed rows (with the list of changed fields and their previous values) and removed rows. Also **deduplicates** and **merges** Apify datasets, CSV, TSV, JSON and JSON Lines files by any key fields.

Typical uses: price and stock monitoring, new job/real-estate/product listings alerts, catalogue sync, cleaning duplicated scraping results before export.

### How it works

1. **Pick your data**: Apify datasets (resource picker; only the datasets you select are shared, read-only), file URLs, or inline JSON.
2. **Choose key fields** (e.g. `url`, `sku`, `product.id`).
3. **Pick a mode**
   - `diff` + **snapshot name**: compares with the previous run's data and saves today's data for tomorrow. The first run only saves the baseline (free).
   - `diff` + **baseline**: compares against datasets/files you pick (e.g. yesterday's run dataset).
   - `dedupe`: removes duplicates (keep first or last).
   - `merge`: combines all sources, latest row per key wins.

Use `ignoreFields` (e.g. `scrapedAt`) or `compareFields` (e.g. only `price`, `inStock`) so noise doesn't count as change.

### Output (diff mode)

Each output row is the full current row plus:

| Field | Meaning |
|---|---|
| `_change` | `new`, `changed`, `removed` (or `unchanged` if requested) |
| `_changedFields` | e.g. `["price"]` |
| `_previous` | previous values of changed fields, e.g. `{"price": 20}` |

A `SUMMARY` record in the run's key-value store has counts. Real example: [listing/output-example.json](listing/output-example.json) for [listing/input-example.json](listing/input-example.json). Plug the dataset into Slack/email/Make/Zapier integrations or a webhook to alert only on changes.

### Pricing (pay per event)

| Event | Price |
|---|---|
| Row processed (input rows of the current data; baseline rows are free) | $0.00001 ($0.01 per 1,000) |
| Change detected (diff mode, per new/changed/removed row output) | $0.0005 |
| Actor start (Apify standard, once per run) | $0.0003 |

Example: a daily 10,000-row scrape with 150 changes costs $0.10 + $0.075 = **$0.175 per day** (plus the $0.0003 Actor start). Dedupe/merge of 10,000 rows costs **$0.10**. Unchanged rows and the first snapshot run's baseline cost nothing extra.
If you set a max charge per run that cannot cover all rows, a diff refuses to start (a partial diff would report false removals); if the budget runs out while outputting changes, the snapshot is not advanced, so no change is lost.

### Notes

- Snapshots live in a named key-value store `dataset-diff-snapshots` in **your** account (gzip; full rows up to ~8 MB compressed, otherwise fingerprints only, in which case `_changedFields` is `null`).
- File URLs: only submit files you have the right to process; robots.txt is respected by default and private network addresses are refused.
- The Actor runs with limited permissions: it can read only the datasets you select.
- Default memory 512 MB. Our tests used small inputs; very large datasets (hundreds of thousands of wide rows) may need more memory (max 8 GB). `maxRows` default 1,000,000.
- Data: only the datasets and files you provide. No third-party data sources.

### No warranty

Provided as is, without warranty of any kind. Results are automated and can be incomplete or wrong; check anything important against the original source before relying on it.

# Actor input Schema

## `mode` (type: `string`):

diff = new/changed/removed rows vs a baseline or the previous run; dedupe = remove duplicates; merge = combine all sources and keep the latest row per key.

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

Apify datasets to read, e.g. the output of your scraper's latest run. Only the datasets you select are shared with this Actor (read-only).

## `fileUrls` (type: `array`):

CSV, TSV, JSON or JSON Lines files you have the right to process.

## `items` (type: `array`):

JSON array of objects.

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

Fields that identify a row (dot paths allowed, e.g. 'id' or 'product.sku'). Required for diff; for dedupe, empty = whole row must match.

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

Diff mode: a row counts as changed only if one of these fields changed. Empty = all fields except ignored ones.

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

Top-level fields that never count as a change, e.g. scrapedAt, crawledAt, position.

## `trimStrings` (type: `boolean`):

Treat '  Foo  bar ' and 'Foo bar' as equal.

## `caseInsensitiveKeys` (type: `boolean`):

Match key values ignoring case.

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

Dedupe/merge: keep the first or last occurrence (merge defaults to last = newest source).

## `snapshotName` (type: `string`):

Diff mode without a baseline: compare with the data saved under this name by the previous run, then save the current data. The first run only saves the baseline (free). Stored in your named key-value store 'dataset-diff-snapshots'.

## `updateSnapshot` (type: `boolean`):

Save the current data as the new snapshot.

## `firstRunOutputsAll` (type: `boolean`):

By default the first snapshot run just saves the baseline. Enable to output (and pay for) every row as new.

## `baselineDatasetIds` (type: `array`):

Explicit baseline (e.g. the previous run's dataset). Overrides the snapshot.

## `baselineFileUrls` (type: `array`):

CSV/JSON/JSONL baseline files.

## `baselineItems` (type: `array`):

JSON array of objects.

## `outputChangeTypes` (type: `array`):

Which changes to output (and pay for).

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

Unchanged rows are output for free, marked \_change=unchanged.

## `maxRows` (type: `integer`):

Safety cap on rows read.

## `maxFileSizeMb` (type: `integer`):

Per file URL.

## `respectRobotsTxt` (type: `boolean`):

Skip file URLs disallowed by the host's robots.txt.

## Actor input object example

```json
{
  "mode": "diff",
  "items": [
    {
      "sku": "A1",
      "price": 10
    },
    {
      "sku": "B2",
      "price": 25
    },
    {
      "sku": "C3",
      "price": 7
    }
  ],
  "keyFields": [
    "sku"
  ],
  "ignoreFields": [
    "scrapedAt"
  ],
  "trimStrings": true,
  "caseInsensitiveKeys": false,
  "updateSnapshot": true,
  "firstRunOutputsAll": false,
  "outputChangeTypes": [
    "new",
    "changed",
    "removed"
  ],
  "includeUnchanged": false,
  "maxRows": 1000000,
  "maxFileSizeMb": 100,
  "respectRobotsTxt": true
}
```

# Actor output Schema

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

Diff mode: new/changed/removed rows with \_change, \_changedFields, \_previous. Dedupe/merge mode: the unique rows.

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

SUMMARY record in the default key-value store: counts, charges and status of the run.

# 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 = {
    "items": [
        {
            "sku": "A1",
            "price": 10
        },
        {
            "sku": "B2",
            "price": 25
        },
        {
            "sku": "C3",
            "price": 7
        }
    ],
    "keyFields": [
        "sku"
    ],
    "ignoreFields": [
        "scrapedAt"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("noisy_jubilee/dataset-diff-dedupe").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 = {
    "items": [
        {
            "sku": "A1",
            "price": 10,
        },
        {
            "sku": "B2",
            "price": 25,
        },
        {
            "sku": "C3",
            "price": 7,
        },
    ],
    "keyFields": ["sku"],
    "ignoreFields": ["scrapedAt"],
}

# Run the Actor and wait for it to finish
run = client.actor("noisy_jubilee/dataset-diff-dedupe").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 '{
  "items": [
    {
      "sku": "A1",
      "price": 10
    },
    {
      "sku": "B2",
      "price": 25
    },
    {
      "sku": "C3",
      "price": 7
    }
  ],
  "keyFields": [
    "sku"
  ],
  "ignoreFields": [
    "scrapedAt"
  ]
}' |
apify call noisy_jubilee/dataset-diff-dedupe --silent --output-dataset

```

## MCP server setup

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

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/7ouWhPDsS9rOO3KBk/builds/Ynf0L7jUqsRdZ8GoB/openapi.json
