# Dataset Merger and Deduplicator: Remove Duplicates (`clearcheck/dataset-merge-dedupe`) Actor

Merge Apify datasets and JSON files, then remove duplicates by key fields. Keeps the most complete record, fills gaps, or outputs only new items.

- **URL**: https://apify.com/clearcheck/dataset-merge-dedupe.md
- **Developed by:** [ClearCheck Tools](https://apify.com/clearcheck) (community)
- **Categories:** Developer tools, Automation
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

$0.30 / 1,000 item 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 Merger and Deduplicator: Remove Duplicates

Combine the results of several scrapers (or several runs of the same scraper) into **one clean dataset without duplicates**. Point it at your Apify datasets, JSON or JSONL URLs, or paste items; say which fields identify a duplicate; get unique items back.

Typical jobs: merge a Google Maps scrape with a LinkedIn scrape and keep one record per company, remove repeated listings across daily runs, build a "new items only" feed from a scheduled scraper.

### What it does

- **Merges** any mix of: Apify datasets (IDs or names, from your account), JSON / JSONL URLs, items pasted in the input.
- **Deduplicates on the fields you choose** (dotted paths such as `owner.email` allowed), or on the whole item when you choose none.
- **Smart comparison** so near-identical values match: ignores case, accents (optional), extra whitespace, and for URLs `www.`, `http` vs `https`, `#fragments`, trailing slashes, query order and tracking parameters (`utm_*`, `fbclid`, `gclid`...).
- **Chooses which duplicate to keep**: first seen, last seen, or the **most complete** record (most non-empty fields).
- **Fills the gaps**: optionally copy fields that are empty in the kept record from its duplicates (a phone number found only in the second dataset ends up in the result).
- **Only new items**: a named memory remembers what you already received, so a scheduled run returns just what is new since the last run.
- **Traceability**: optional `_source` (where an item came from) and `_duplicates` (how many were merged into it).
- Items with none of the key fields are kept by default (never silently dropped).

### Quick start

1. Put dataset IDs in **Datasets to merge** (Storage > Datasets, copy the ID).
2. Put the identifying field in **Fields that identify a duplicate** (for example `url`).
3. Click **Start**; open the **Output** tab.

### Input

| Field | Description | Default |
|---|---|---|
| `datasetIds` | Datasets (ID or name) to merge, read in order. | - |
| `jsonUrls` | URLs returning a JSON array, `{ "items": [...] }` / `{ "data": [...] }`, or JSONL. | - |
| `items` | Items pasted directly. | - |
| `dedupeKeys` | Fields that identify a duplicate (all must be equal). Empty = whole item. | `[]` |
| `keep` | `first`, `last` or `mostComplete`. | `first` |
| `mergeFields` | Fill empty fields of the kept item from its duplicates. | `false` |
| `ignoreCase`, `ignoreAccents`, `trim`, `normalizeUrls` | Comparison rules. | `true`, `false`, `true`, `true` |
| `keepItemsWithoutKey` | Keep items where every key field is empty. | `true` |
| `onlyNewSinceLastRun`, `stateName` | Incremental mode and the name of its memory. | `false`, `default` |
| `addSourceField`, `addDuplicateCount` | Add `_source` / `_duplicates`. | `false` |

Example (real platform run; dataset w3Qf... was listed twice on purpose, which is why 6 duplicates were found):

```json
{
  "datasetIds": ["w3Qfj8Oxoo4S4Aybq", "ZRsnS5o3hvFHaLIee"],
  "dedupeKeys": ["_file", "_row"],
  "keep": "mostComplete",
  "addDuplicateCount": true
}
```

### Output

The merged unique items (original fields untouched, plus the optional `_source` / `_duplicates`) in the default dataset, and a `SUMMARY` record:

```json
{
  "inputItems": 15,
  "uniqueItemsOutput": 9,
  "duplicatesRemoved": 6,
  "itemsWithoutKey": 0,
  "skippedAlreadySeenInPreviousRuns": 0,
  "bySource": { "dataset:w3Qfj8Oxoo4S4Aybq": 12, "dataset:ZRsnS5o3hvFHaLIee": 3 },
  "stoppedByChargeLimit": false,
  "dedupeKeys": ["_file", "_row"]
}
```

### Incremental mode ("only new items")

Turn on `onlyNewSinceLastRun` and give the pipeline a `stateName`. The Actor stores a fingerprint of every delivered item key in a key-value store named `dedupe-state-<stateName>` in your account and skips those keys next time. Items missing all key fields cannot be fingerprinted, so they are always delivered. Delete that store to start over. If a run stops early because of your maximum-charge limit, the memory is not updated, so the next run does not lose items.

### Use cases

- **Combine scraper runs**: merge the datasets of several runs of the same scraper into one clean list.
- **Lead lists**: remove duplicate companies or contacts by URL, domain or email across sources.
- **Monitoring**: output only items not seen in previous runs (incremental mode) for alerts and daily digests.
- **Data clean-up**: keep the most complete record of each duplicate group and fill its empty fields from the others.

### Pricing

Pay per event. You can cap spending with the maximum cost per run.

| Event | Price | When it is charged |
|---|---|---|
| Item processed | $0.0003 per item ($0.30 per 1,000) | Once per input item read, duplicates included because they are compared |

No start fee. Examples: 1,000 items = $0.30; 10,000 items = $3.00. At your maximum cost the Actor stops and delivers nothing beyond what was paid.

### Limits and honest notes

- Matching is **exact after normalization**, not fuzzy: "Acme Inc" and "Acme Incorporated" are different. Pick a stable key (URL, ID, email, phone) rather than a free-text name.
- With `keep` set to `last` or `mostComplete`, or with `mergeFields` / `addDuplicateCount`, results are held in memory until the end (measured: 500,000 small items need under 100 MB for keys alone; set more memory for millions of wide items). With `keep: first` and no merging, results are streamed.
- Datasets must be selected in the input (the picker or their IDs in `datasetIds`): the Actor runs with limited permissions and can read only the datasets you give it. It never touches your other storages.
- Items that are not JSON objects (plain strings, arrays) are ignored.

### FAQ

**What counts as a duplicate?** Items whose key fields are all equal after normalisation (case, accents, whitespace and, for URLs, www, http versus https, fragments, trailing slashes and tracking parameters). With no key fields, the whole item is compared.

**Can it read files that are not Apify datasets?** Yes: URLs that return a JSON array or JSONL, or items pasted in the input.

**How does "only new items" work?** The Actor stores a fingerprint of each delivered key under a state name and skips those keys in later runs.

**Is the input deleted?** No. Source datasets are only read; the result goes to the run dataset.

### More Actors by clearcheck

- [Email Validator](https://apify.com/clearcheck/email-validator)
- [Domain Health Checker](https://apify.com/clearcheck/domain-health-checker)
- [Broken Link Checker and Sitemap SEO Auditor](https://apify.com/clearcheck/link-sitemap-audit)
- [PDF, DOCX and HTML to Markdown Converter](https://apify.com/clearcheck/document-to-markdown-converter)
- [Website Contact Finder](https://apify.com/clearcheck/website-contact-finder)
- [Bulk Phone Number Validator](https://apify.com/clearcheck/phone-validator)
- [Bulk Image Optimizer](https://apify.com/clearcheck/image-optimizer)
- [OCR Text Extractor](https://apify.com/clearcheck/ocr-text-extractor)
- [Excel and CSV to JSON Converter](https://apify.com/clearcheck/spreadsheet-to-json)

# Actor input Schema

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

Datasets from your account to merge, in reading order (with "keep first", earlier datasets win). Pick them in the list or pass their IDs through the API.

## `jsonUrls` (type: `array`):

Public URLs returning a JSON array, an object with an items or data array, or newline-delimited JSON.

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

Items pasted directly, processed before datasets.

## `dedupeKeys` (type: `array`):

Field names, dotted paths allowed ("owner.email"). Two items are duplicates when ALL these fields are equal after normalization. Leave empty to compare whole items.

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

First = earliest in read order. Last = latest. Most complete = the one with the most non-empty fields (ties keep the first).

## `mergeFields` (type: `boolean`):

The kept item gets any field that is empty in it but filled in a duplicate (for example a phone number found in the second dataset). Needs all results in memory.

## `ignoreCase` (type: `boolean`):

"Paris" and "paris" are the same value.

## `ignoreAccents` (type: `boolean`):

"Été" and "Ete" are the same value.

## `trim` (type: `boolean`):

Leading, trailing and repeated spaces are ignored in comparisons.

## `normalizeUrls` (type: `boolean`):

In comparisons, ignore www., http/https, #fragments, trailing slashes, query order and tracking parameters (utm\_\*, fbclid, gclid...).

## `keepItemsWithoutKey` (type: `boolean`):

Items where all the key fields are empty cannot be compared. Kept by default so nothing is silently dropped.

## `onlyNewSinceLastRun` (type: `boolean`):

Remembers the keys of delivered items in a named key-value store, so scheduled runs return only new items. Requires key fields.

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

Name of the memory used by incremental mode. Use different names for different pipelines.

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

Adds where each item was read from (dataset:ID, url:..., input).

## `addDuplicateCount` (type: `boolean`):

Adds how many duplicates were merged into each item.

## Actor input object example

```json
{
  "items": [
    {
      "url": "https://example.com/a",
      "name": "Acme"
    },
    {
      "url": "http://www.example.com/a/",
      "name": "Acme Inc",
      "city": "Nairobi"
    },
    {
      "url": "https://example.com/b",
      "name": "Beta"
    }
  ],
  "dedupeKeys": [
    "url"
  ],
  "keep": "first",
  "mergeFields": false,
  "ignoreCase": true,
  "ignoreAccents": false,
  "trim": true,
  "normalizeUrls": true,
  "keepItemsWithoutKey": true,
  "onlyNewSinceLastRun": false,
  "stateName": "default",
  "addSourceField": false,
  "addDuplicateCount": false
}
```

# Actor output Schema

## `items` (type: `string`):

Unique items.

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

Counts: read, output, duplicates removed, per source.

# 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": [
        {
            "url": "https://example.com/a",
            "name": "Acme"
        },
        {
            "url": "http://www.example.com/a/",
            "name": "Acme Inc",
            "city": "Nairobi"
        },
        {
            "url": "https://example.com/b",
            "name": "Beta"
        }
    ],
    "dedupeKeys": [
        "url"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("clearcheck/dataset-merge-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": [
        {
            "url": "https://example.com/a",
            "name": "Acme",
        },
        {
            "url": "http://www.example.com/a/",
            "name": "Acme Inc",
            "city": "Nairobi",
        },
        {
            "url": "https://example.com/b",
            "name": "Beta",
        },
    ],
    "dedupeKeys": ["url"],
}

# Run the Actor and wait for it to finish
run = client.actor("clearcheck/dataset-merge-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": [
    {
      "url": "https://example.com/a",
      "name": "Acme"
    },
    {
      "url": "http://www.example.com/a/",
      "name": "Acme Inc",
      "city": "Nairobi"
    },
    {
      "url": "https://example.com/b",
      "name": "Beta"
    }
  ],
  "dedupeKeys": [
    "url"
  ]
}' |
apify call clearcheck/dataset-merge-dedupe --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,clearcheck/dataset-merge-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/ElGosbxQKr5G0S6fQ/builds/VLIN3fKyyONfit2Qi/openapi.json
