# Dataset Merge & Dedupe: Remove Duplicates, Only New Items (`vikasmaur13/dataset-merge-dedupe`) Actor

Merge Apify datasets and remove duplicates by any fields, with trim, case-insensitive and URL-normalized matching. Keep first, last or most complete. Output only items not seen in earlier runs. Works with limited permissions. Duplicates are free.

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

## Pricing

from $0.02 / 1,000 unique item writtens

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 Merge & Dedupe: remove duplicates, output only new items

Merge one or more Apify datasets into a single dataset of **unique items**. You choose the fields that define a duplicate (`url`, `id`, `name` + `address`, nested `author.id`). Matching can ignore extra whitespace, letter case and URL noise such as `utm_*` parameters, `www.` and trailing slashes. You also choose which copy to keep: **first**, **last** or **most complete**.

Running a scraper on a schedule? Give the actor a **seen-items memory** name and each run returns **only items that earlier runs have not output yet**.

- Works with **limited permissions**. You pick the datasets, and the actor can read those datasets and nothing else in your account. No full-access approval and no "Insufficient permissions" errors.
- **Duplicates are free.** You pay per unique item written: $0.015 per 1,000.
- **Failed runs don't charge** our events. Inputs are checked before anything is charged.
- Streams any size. One million items use about 100 MB of memory.

### What you can do with it

| Use case | Input |
|---|---|
| Merge the results of several scraper runs into one clean table | `datasetIds`: all runs, `dedupeFields`: `["url"]` |
| Run it automatically after every scraper run (integration) | `datasetIds`: `["{{resource.defaultDatasetId}}"]` |
| Daily/hourly monitoring: only new listings, jobs, posts or products | add `seenItemsStoreName`: `"my-monitor"` |
| Compare today's scrape with yesterday's | `excludeDatasetIds`: yesterday's dataset |
| Keep the freshest price when a product appears in many runs | `keep`: `"last"` and list the newest dataset last |
| Keep the record with the most filled-in fields (leads, places) | `keep`: `"most-complete"` |
| Slim the output down to the columns you need | `outputFields` + `renameFields` |

### Quick start

1. Click **Datasets to merge and dedupe** and pick one or more datasets (or paste IDs or names).
2. Enter the **Dedupe key fields**, e.g. `url`. Leave the list empty to remove only exact duplicate items.
3. Click **Start**. The unique items appear in the run's dataset. You can export them as CSV, Excel, JSON or XML, or use them through the API.

#### Example input

```json
{
  "datasetIds": ["aBcD1234EfGh5678i", "my-named-dataset"],
  "dedupeFields": ["url"],
  "normalizeUrls": true,
  "keep": "most-complete",
  "seenItemsStoreName": "shop-monitor",
  "outputFields": ["url", "title", "price", "seller.name"],
  "renameFields": {"seller.name": "seller"}
}
```

#### Run it after every scraper run

In your scraper's **Integrations** tab, choose **Connect Actor or Task**, pick this actor and use this input:

```json
{ "datasetIds": ["{{resource.defaultDatasetId}}"], "dedupeFields": ["url"], "seenItemsStoreName": "my-scraper-new-items" }
```

Each scraper run then produces a second dataset that holds only the new items. Hook your notifications or exports to that dataset.

### Input

| Field | What it does |
|---|---|
| `datasetIds` (required) | Datasets to merge, read in this order. Accepts IDs or names. |
| `dedupeFields` | Fields that identify a duplicate. All listed fields must match. Dots reach nested values (`author.id`, `images.0.url`). Empty means whole-item comparison. |
| `keep` | `first` (default, one pass), `last`, or `most-complete` (most non-empty values, ties go to the earliest). `last` and `most-complete` read the data twice. |
| `trimWhitespace` | Default on. `"  Acme  Inc "` matches `"Acme Inc"`. |
| `ignoreCase` | `"ACME"` matches `"acme"`. |
| `normalizeUrls` | Treats `http`/`https`, `www.`, domain case, trailing `/`, `#fragment`, default ports, query order and tracking parameters (`utm_*`, `fbclid`, `gclid`, `msclkid`, ...) as equal. Path case still matters. |
| `itemsWithoutKey` | Items with no value in any key field: `keep` (default, output each one) or `drop`. |
| `seenItemsStoreName` | Turns on the cross-run memory (see below). |
| `resetSeenItems` | Clears that memory and starts over. |
| `excludeDatasetIds` | Leaves out items whose key appears in these datasets. |
| `outputFields`, `renameFields`, `addSourceDataset` | Shape the output. Matching always uses the original values; output values are never modified. |
| `batchSize` | Items per download request (default 5,000). Lower it only for very large items. |

### Output

- **Dataset:** the unique items, in the order they appear in your datasets.
- **Key-value store record `SUMMARY`:** counts for this run, for example:

```json
{"status": "ok", "inputItems": 5000, "duplicatesRemoved": 3136, "alreadySeenInPreviousRuns": 0,
 "excludedByReference": 0, "outputItems": 1864, "passes": 1, "itemsDownloaded": 5000,
 "seenItemsStore": null, "chargedEvents": {"item-output": 1864, "items-scanned-1k": 5}}
```

The run's status message gives the same numbers in one line: "1,864 items output from 5,000 read; 3,136 duplicates removed".

### Only new items across runs (seen-items memory)

Set `seenItemsStoreName` to a name such as `jobs-monitor`. The actor keeps a key-value store with that name in your account. It holds only 8-byte fingerprints of the keys it has output, never your data. Each later run with the same name skips every item whose key was output before.

- Only items that were actually written are remembered. If a run stops at your max charge, the rest come out next time.
- If you change the key fields or matching options, the run stops at no charge and tells you to pick a new name or reset. Without this check the old fingerprints would never match, and every item would be output and charged again.
- Items with no key value can't be remembered. Use `itemsWithoutKey: drop` for monitors.
- Use a name that this actor created. A store you created by hand isn't readable by an actor with limited permissions.

### Pricing (pay per event)

| Event | Price |
|---|---|
| Unique item written to your dataset | **$0.015 per 1,000** ($0.000015 each, charged per item, not per started block) |
| Items scanned | **$0.50 per 1,000,000** ($0.0005 per started 1,000; `last`/`most-complete` scan twice) |
| Actor start (Apify's standard start event) | $0.00005 per run |

Duplicates, excluded items and already-seen items are free. A run that fails on input or access errors is charged nothing by this actor; only Apify's $0.00005 start event applies. Your **max charge per run** is always respected: the actor stops writing at the limit and finishes successfully.

Examples: merging 10,000 items into 6,000 unique costs **$0.095**. An hourly monitor that scans 2,000 items and finds about 20 new ones costs about **$0.0014 per run (about $1 a month)**.

### Limited permissions: why this matters

Apify runs Store actors with a token scoped to what the actor needs. An actor that asks for dataset IDs in a plain text field has no access to those datasets when your account uses the default **Restricted** resource access, and its runs fail with `Insufficient permissions for the dataset (403)`. This actor declares its dataset fields as dataset inputs with **read-only** access. Apify grants exactly that access, and the actor needs no other access to your account.

### FAQ

**Does it change my source datasets?** No. It only reads them.
**How large can the datasets be?** It streams in batches. 1,000,000 items with 600,000 unique keys peak at about 100 MB of memory (default memory is 512 MB). Very large runs simply take longer.
**What counts as "most complete"?** The number of non-empty values, counting nested fields. Empty strings, `null`, `[]` and `{}` don't count.
**Is the URL normalization safe?** It drops only parameters that track visitors or campaigns, and it keeps meaningful ones like `id=` or `page=`. If you are unsure, leave it off.
**Do numbers and strings match (`1` vs `"1"`)?** No. Types must match.

### More tools from the same developer

- [YouTube, Instagram Reels & TikTok Transcript Scraper](https://apify.com/vikasmaur13/video-transcript-scraper): turns videos into text. Chain this dedupe actor after it to process only new videos.

Found a bug or need a feature? Open an issue in the **Issues** tab. We aim to reply within one business day.

***

### Development (for maintainers)

```bash
cd actors/dataset-dedupe
python3 -m venv .venv && .venv/bin/pip install -r requirements-dev.txt
.venv/bin/python -m pytest -q            # unit tests
.venv/bin/python scripts/local_e2e.py    # runs the real actor locally on synthetic datasets -> samples/local/
.venv/bin/python scripts/bench_scale.py 1000000 first   # memory/throughput benchmark (use the heavy lock on shared machines)
npx -y apify-cli@latest push              # deploy as a private actor (needs `apify login`)
```

`scripts/platform_run.py` runs the pushed actor on Apify and checks its output item by item against the local engine (token read from `APIFY_TOKEN_FILE`).

# Actor input Schema

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

One or more datasets (pick them, or paste dataset IDs or names). Items are read in this order. From an integration or API call pass IDs, e.g. \["{{resource.defaultDatasetId}}"]. The actor gets read access to exactly these datasets and nothing else in your account.

## `dedupeFields` (type: `array`):

Fields that identify a duplicate, e.g. "url" or "name" + "address". Items are duplicates when ALL listed fields match. Nested fields use dots: "author.id", "images.0.url". Leave empty to compare whole items.

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

first: the earliest occurrence (one pass, fastest). last: the latest occurrence, e.g. the freshest price when the newest dataset is listed last. most-complete: the occurrence with the most non-empty values (ties go to the earliest). last and most-complete read the data twice.

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

"  Acme  Inc " matches "Acme Inc". Applies only to matching; output values are unchanged.

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

"ACME" matches "acme" (Unicode case folding).

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

URL values match when they differ only by http/https, www., letter case of the domain, a trailing slash, #fragment, default port, query parameter order or tracking parameters (utm\_\*, fbclid, gclid, msclkid and similar). Path letter case still matters.

## `itemsWithoutKey` (type: `string`):

What to do with items where every key field is missing or empty. keep: output each of them (they can't be compared). drop: leave them out.

## `seenItemsStoreName` (type: `string`):

Give a name, e.g. "my-shop-monitor", and the actor remembers the keys it has output in a key-value store with that name. Later runs with the same name output only items never output before: ideal for scheduled scrapers and monitoring. Only 8-byte key hashes are stored, never your data. Leave empty to disable.

## `resetSeenItems` (type: `boolean`):

Forget everything remembered under this name and start over (needed after changing key fields or matching options).

## `excludeDatasetIds` (type: `array`):

Optional reference datasets. Items whose key also appears in any of these are left out (reference items themselves are never output). Example: compare today's scrape with yesterday's to get only the new listings.

## `outputFields` (type: `array`):

Keep only these fields in the output, in this order. Nested fields use dots ("author.name") and become one column named after the path. Leave empty to keep all fields.

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

Map of old name to new name, applied after field selection, e.g. {"author.name": "author", "url": "link"}.

## `addSourceDataset` (type: `boolean`):

Adds a "sourceDataset" field with the dataset ID or name the item came from.

## `batchSize` (type: `integer`):

Items downloaded per request. Lower it if your items are very large (over 50 KB each).

## Actor input object example

```json
{
  "dedupeFields": [
    "url"
  ],
  "keep": "first",
  "trimWhitespace": true,
  "ignoreCase": false,
  "normalizeUrls": false,
  "itemsWithoutKey": "keep",
  "resetSeenItems": false,
  "renameFields": {},
  "addSourceDataset": false,
  "batchSize": 5000
}
```

# Actor output Schema

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

The deduplicated items, in source order, shaped by the output field options.

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

JSON record with input items, duplicates removed, already-seen items, output items and charged events.

# 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 = {
    "dedupeFields": [
        "url"
    ],
    "renameFields": {}
};

// Run the Actor and wait for it to finish
const run = await client.actor("vikasmaur13/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 = {
    "dedupeFields": ["url"],
    "renameFields": {},
}

# Run the Actor and wait for it to finish
run = client.actor("vikasmaur13/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 '{
  "dedupeFields": [
    "url"
  ],
  "renameFields": {}
}' |
apify call vikasmaur13/dataset-merge-dedupe --silent --output-dataset

```

## MCP server setup

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