# Merge & Deduplicate Datasets: Remove Duplicates, Only New Items (`gmyri/dataset-merge-dedup`) Actor

Merge Apify datasets, CSV and JSON files into one, remove duplicates by any field, output only new items since the last run, filter, rename and flatten. $0.10 per 1,000 rows.

- **URL**: https://apify.com/gmyri/dataset-merge-dedup.md
- **Developed by:** [Giorgos Myrianthous](https://apify.com/gmyri) (community)
- **Categories:** Developer tools, Integrations, Automation
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.10 / 1,000 output rows

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

## Merge & Deduplicate Datasets: Remove Duplicates, Only New Items

**Merge datasets and remove duplicates** from Apify datasets, CSV and JSON files, and output **only new items** since your last run, which is perfect for scheduled scrapers feeding Google Sheets, CRMs and Slack.

💲 **$0.10 per 1,000 output rows.** Duplicates and filtered rows are free. Pay only for results. No subscription, and the Apify free plan's monthly credit covers small jobs.

**Also known as:** merge datasets, deduplicate dataset, remove duplicates, dedup CSV, only new items, combine scraper runs, JSON to CSV, dataset transformer.

### Quick start

1. Click **Start**. The prefilled input works as is.
2. Or paste this input (JSON tab):

```json
{
  "inlineItems": [
    {
      "url": "https://example.com/a",
      "title": "A"
    },
    {
      "url": "https://example.com/b",
      "title": "B"
    },
    {
      "url": "https://example.com/a",
      "title": "A (duplicate)"
    }
  ],
  "dedupFields": [
    "url"
  ]
}
```

**Output** (one dataset item):

```json
{
  "url": "https://example.com/a",
  "title": "A"
}
```

### Use it from the API, AI agents (MCP), n8n, Make or Zapier

```bash
curl -X POST "https://api.apify.com/v2/acts/gmyri~dataset-merge-dedup/run-sync-get-dataset-items?token=$APIFY_TOKEN" \
  -H 'Content-Type: application/json' \
  -d '{"datasetIds":["<DATASET_ID_1>","<DATASET_ID_2>"],"dedupFields":["url"],"onlyNewItems":true}'
```

- **AI agents / MCP:** connect `https://mcp.apify.com/?actors=gmyri/dataset-merge-dedup` to Claude, Cursor, ChatGPT or any MCP client. The input schema is fully described for tool calling.
- **Python:** `ApifyClient(token).actor("gmyri/dataset-merge-dedup").call(run_input={...})`
- **n8n / Make / Zapier:** use the Apify "Run Actor" action with `gmyri/dataset-merge-dedup`, then read the dataset items.

### Quick FAQ

- **How does 'only new items' work?** The keys of rows already output are stored in a named key-value store (`stateStoreName`). The next run outputs only rows it has never seen, so you can schedule a scraper and get just the new results.
- **Can it read my other Actors' datasets?** Yes. Pass dataset IDs in `datasetIds`. The Actor runs with limited permissions and only reads the datasets you select.
- **What if I set a spending limit?** The Actor stops cleanly at your *Max cost per run* and you're never charged above it.

### Details

Combine the outputs of several scraper runs, CSV exports and JSON files into **one clean dataset**:

- remove duplicates by any fields
- output **only the rows that are new since your last run**
- filter, keep, drop, rename and flatten fields
- export to an Apify dataset, CSV or JSON

You pay only for rows that make it into the output. Duplicates and filtered rows are free.

### Why this Actor

- **Reliable.** Rows are streamed in batches of 500, a missing or broken source never kills the run (it is reported in `SUMMARY`), and a spending limit stops the run cleanly instead of failing it.
- **Incremental pipelines.** Schedule a scraper, chain this Actor after it with `onlyNewItems: true`, and send only fresh rows to Slack, Sheets or your CRM. Dedup keys are remembered in a named key-value store between runs.
- **Mixed sources.** Read Apify datasets, CSV/TSV (delimiter auto-detected), JSON arrays, `{ "items": [...] }` wrappers, JSON Lines and inline JSON, all in one run.
- **Agent-friendly.** Inline items plus a simple JSON filter language make it a handy cleaning tool for AI agents through the Apify MCP server.

### Typical uses

- Merge 10 daily runs of a product or price scraper and keep the **newest** row per URL (`keepOccurrence: "last"`).
- Dedup a lead or company list by `domain` (case- and whitespace-insensitive).
- Turn nested JSON into a flat CSV for Excel (`flattenNested` + `saveCsvFile`).
- Keep only rows with `price < 100` that contain `"mug"` in `title`.

### Input example

```json
{
  "datasetIds": ["<dataset-id-run-1>", "<dataset-id-run-2>"],
  "fileUrls": ["https://example.com/export.csv"],
  "dedupFields": ["url"],
  "keepOccurrence": "last",
  "filters": [{ "field": "price", "op": "lt", "value": 100 }],
  "omitFields": ["debug"],
  "renameFields": { "meta.brand": "brand" },
  "flattenNested": true,
  "saveCsvFile": true
}
```

#### Options

| Field | Default | Description |
|---|---|---|
| `datasetIds` | – | Apify datasets to merge, in order |
| `fileUrls` | – | CSV, TSV, JSON or JSONL URLs (Google Sheets "publish to web" CSV links work) |
| `inlineItems` | – | JSON array of rows |
| `deduplicate` | `true` | Remove duplicate rows |
| `dedupFields` | whole row | Fields that define a duplicate (dot paths such as `address.city` work) |
| `dedupCaseInsensitive` / `dedupTrimWhitespace` | `true` / `true` | Normalise values before comparing |
| `keepOccurrence` | `first` | `first` or `last` (newest data wins) |
| `onlyNewItems` | `false` | Skip rows already output in previous runs |
| `stateStoreName` | `dataset-dedup-state` | Named store that remembers keys between runs. Use one per pipeline. |
| `filters` | – | `[{field, op, value}]`. Ops: `eq ne contains notContains in notIn gt gte lt lte exists notExists regex` |
| `pickFields` / `omitFields` / `renameFields` | – | Reshape rows |
| `flattenNested`, `trimStrings`, `dropEmptyFields`, `addSourceField` | `false` | Extra clean-up |
| `inferCsvTypes` | `true` | Turn CSV `"12"` into `12` and `"true"` into `true` |
| `maxOutputItems` | `0` | Cap on output rows |
| `saveCsvFile` / `saveJsonFile` | `false` | Also save `OUTPUT.csv` / `OUTPUT.json` in the key-value store |

### Output

- The **default dataset** holds the cleaned rows.
- **`SUMMARY`** (key-value store) holds the counts, for example:
  ```json
  { "inputRows": 11, "filteredOut": 1, "duplicates": 4, "seenInPreviousRuns": 0, "outputRows": 6,
    "sources": [{ "source": "dataset:abc", "rows": 2 }], "sourceErrors": [] }
  ```
- `OUTPUT.csv` and `OUTPUT.json` are saved if requested.

### Pricing (pay per event)

| Event | Price | When |
|---|---|---|
| `row-output` | **$0.0001** ($0.10 per 1,000 rows) | Each row written to the output |
| `apify-actor-start` | $0.00005 | Platform default, once per run |

Input rows, duplicates and filtered-out rows are **not charged**. Example: merging 60,000 rows down to 25,970 unique rows costs about **$2.60**. Set a maximum cost per run, and the Actor stops output cleanly at the limit.

### Integrations

- **Chain after a scraper:** add an Apify webhook or integration on your scraper's `RUN.SUCCEEDED` event and pass `{"datasetIds": ["{{resource.defaultDatasetId}}"], "onlyNewItems": true}`.
- **MCP:** `https://mcp.apify.com/?tools=<your-username>/dataset-merge-dedup`. The Actor uses pay-per-event pricing only and limited permissions, with no Standby, so it is eligible for agentic payments.

### Notes and limits

- In `keepOccurrence: "last"` mode, rows are held in memory until all sources are read. Use 1–4 GB of memory for multi-million-row merges.
- Rows whose dedup fields are all empty are always kept. In incremental mode they are remembered by their full content.
- With limited permissions, the Actor can read only the datasets you pick in the input.

### Related tools

- [PDF to Markdown & Text Converter: Word, Excel, PPT, HTML, RAG](https://apify.com/gmyri/doc-to-markdown)
- [Broken Link Checker & SEO Audit: 404s, Redirects, Sitemap](https://apify.com/gmyri/site-health-audit)
- [DNS Lookup & SSL Checker: SPF, DMARC, DKIM, Domain Expiry](https://apify.com/gmyri/domain-health-check)

# Actor input Schema

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

Datasets to merge, in order (e.g. outputs of your scraper runs). Only the datasets you select here are readable by the Actor.

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

Direct links to CSV, TSV, JSON (array or {items:\[...]}) or JSON Lines files. Google Sheets 'Publish to web → CSV' links work.

## `inlineItems` (type: `array`):

Rows passed directly, handy for AI agents and quick tests.

## `deduplicate` (type: `boolean`):

Drop rows that share the same dedup key.

## `dedupFields` (type: `array`):

Fields that define a duplicate, e.g. 'url' or 'title' + 'address.city' (dot paths supported). Empty = compare the whole row. Rows where all dedup fields are empty are always kept.

## `dedupCaseInsensitive` (type: `boolean`):

'ACME Ltd' equals 'acme ltd'.

## `dedupTrimWhitespace` (type: `boolean`):

Collapse and trim whitespace before comparing.

## `keepOccurrence` (type: `string`):

With 'last', later sources overwrite earlier ones.

## `onlyNewItems` (type: `boolean`):

Incremental mode for scheduled scrapes: remembers dedup keys in a named key-value store and skips rows already output before.

## `stateStoreName` (type: `string`):

Named key-value store that keeps the remembered keys. Use a different name per pipeline.

## `filters` (type: `array`):

All must match. Each filter: {"field": "price", "op": "lt", "value": 100}. Ops: eq, ne, contains, notContains, in, notIn, gt, gte, lt, lte, exists, notExists, regex.

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

Output only these fields (dot paths allowed). Empty = keep all.

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

Fields to drop.

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

Map of old name to new name, e.g. {"address.city": "city"}.

## `flattenNested` (type: `boolean`):

Turn {"a":{"b":1}} into {"a.b":1}. Useful before CSV export.

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

Collapse whitespace in all string values.

## `dropEmptyFields` (type: `boolean`):

Remove null, empty-string and empty list/object values.

## `addSourceField` (type: `boolean`):

Record which dataset or file each row came from.

## `inferCsvTypes` (type: `boolean`):

Convert '12', '3.5', 'true' in CSV cells to numbers/booleans.

## `maxOutputItems` (type: `integer`):

Stop after this many output rows (0 = no limit).

## `saveCsvFile` (type: `boolean`):

Save the result as a CSV file in the key-value store (flattened).

## `saveJsonFile` (type: `boolean`):

Save the result as one JSON file in the key-value store.

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

Larger files are skipped.

## `requestTimeoutSecs` (type: `integer`):

Timeout per file download.

## Actor input object example

```json
{
  "inlineItems": [
    {
      "url": "https://example.com/a",
      "title": "A"
    },
    {
      "url": "https://example.com/b",
      "title": "B"
    },
    {
      "url": "https://example.com/a",
      "title": "A (duplicate)"
    }
  ],
  "deduplicate": true,
  "dedupFields": [
    "url"
  ],
  "dedupCaseInsensitive": true,
  "dedupTrimWhitespace": true,
  "keepOccurrence": "first",
  "onlyNewItems": false,
  "stateStoreName": "dataset-dedup-state",
  "flattenNested": false,
  "trimStrings": false,
  "dropEmptyFields": false,
  "addSourceField": false,
  "inferCsvTypes": true,
  "maxOutputItems": 0,
  "saveCsvFile": false,
  "saveJsonFile": false,
  "maxFileSizeMb": 200,
  "requestTimeoutSecs": 120
}
```

# Actor output Schema

## `rows` (type: `string`):

Merged, deduplicated and transformed rows (same fields as your input data).

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

SUMMARY record: rows in/out, duplicates, filtered, seen in previous runs, source errors.

## `files` (type: `string`):

Optional OUTPUT.csv / OUTPUT.json exports when saveCsvFile/saveJsonFile is on.

# 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 = {
    "inlineItems": [
        {
            "url": "https://example.com/a",
            "title": "A"
        },
        {
            "url": "https://example.com/b",
            "title": "B"
        },
        {
            "url": "https://example.com/a",
            "title": "A (duplicate)"
        }
    ],
    "dedupFields": [
        "url"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("gmyri/dataset-merge-dedup").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 = {
    "inlineItems": [
        {
            "url": "https://example.com/a",
            "title": "A",
        },
        {
            "url": "https://example.com/b",
            "title": "B",
        },
        {
            "url": "https://example.com/a",
            "title": "A (duplicate)",
        },
    ],
    "dedupFields": ["url"],
}

# Run the Actor and wait for it to finish
run = client.actor("gmyri/dataset-merge-dedup").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 '{
  "inlineItems": [
    {
      "url": "https://example.com/a",
      "title": "A"
    },
    {
      "url": "https://example.com/b",
      "title": "B"
    },
    {
      "url": "https://example.com/a",
      "title": "A (duplicate)"
    }
  ],
  "dedupFields": [
    "url"
  ]
}' |
apify call gmyri/dataset-merge-dedup --silent --output-dataset

```

## MCP server setup

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

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/SEiYMXtHdqDaaee4I/builds/4qSDAx3DBCFHwbRKS/openapi.json
