# Dataset Merge & Dedupe (`cellwright/dataset-merge-dedupe`) Actor

Merge any number of Apify datasets into one and remove duplicates by one or more fields (case- and whitespace-insensitive). Keep first, last or merge duplicates, filter rows, rename and select fields. Pay only for rows you keep.

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

## Pricing

Pay per event

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/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

Merge **any number of Apify datasets into one clean dataset** and remove duplicates by one or more fields. Ideal after running the same scraper several times, combining results from different Actors, or cleaning data before it goes to a CRM, spreadsheet or AI agent. **You pay only for the rows you keep.**

### Why this Actor

- **Smart duplicate detection:** compare by one or more fields (dot paths for nested data, e.g. `address.city`) or by the whole row. Case, extra spaces and `10` vs `10.0` are ignored by default – the output keeps the original values.
- **Choose the winner:** keep the **first** row, the **last** row (newest data), or **merge** duplicates into one row where empty fields are filled from the other copies.
- **Rows without a key stay:** rows whose key fields are empty are not collapsed into one by accident.
- **Filter before merging:** `price >= 10`, `country in [CH, DE]`, `url regex \.ch$`, `email exists` …
- **Tidy output:** rename fields, keep only the fields you need, optionally tag each row with its source dataset.
- **Streams large datasets** with low memory use; a summary of every run is saved to the key-value store (`OUTPUT`).
- **Transparent:** a dataset that cannot be read is reported and skipped, the others are still merged.

### Input

| Field | Default | Description |
|---|---|---|
| `datasetIds` | – | Datasets to merge, in order (IDs or `username~name`, up to 100). Empty = free demo run on built-in sample data |
| `dedupe` | `true` | Off = plain merge |
| `dedupeBy` | `[]` | Key fields (all must match). Empty = whole row |
| `keep` | `first` | `first`, `last`, `merge` |
| `normalize` | `true` | Ignore case / extra whitespace in keys |
| `skipEmptyKeys` | `true` | Keep rows whose key fields are all empty |
| `filters` | `[]` | `[{"field": "price", "op": "gte", "value": 10}]` – ops: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `contains`, `notContains`, `startsWith`, `endsWith`, `regex`, `in`, `exists`, `notExists` (all must match) |
| `rename` | `{}` | `{"title": "name"}` |
| `fields` | `[]` | Output only these top-level fields (after renaming) |
| `addSourceDatasetId` | `false` | Adds `sourceDatasetId` to each row |
| `maxItems` | – | Stop after N output rows |

Order of steps per row: **filter → deduplicate → rename → select fields**.

#### Example

```json
{
  "datasetIds": ["a1B2c3D4e5", "f6G7h8I9j0"],
  "dedupeBy": ["website"],
  "keep": "merge",
  "filters": [{ "field": "website", "op": "exists" }],
  "fields": ["name", "website", "phone", "address"]
}
```

### Output

The default dataset contains the merged rows (your original fields). The key-value store record `OUTPUT` holds the run summary:

| Field | Description |
|---|---|
| `datasets` | `[{ datasetId, itemsRead, error }]` |
| `itemsRead`, `itemsOutput` | Rows read / written |
| `duplicatesRemoved`, `filteredOut`, `itemsWithoutKey` | What happened to the rest |
| `stoppedBy` | `null`, `maxItems` or `chargeLimit` |

### Pricing

Pay per event: a small start fee plus a price **per output row**. Rows removed as duplicates or by filters are free. See the *Pricing* tab for current prices.

### Limits & notes

- `keep: last` reads each dataset twice (still cheap); `keep: merge` holds the unique rows in memory – for many millions of rows, raise the memory.
- Only datasets your account can access are read. The Actor does not fetch anything from the web.

# Actor input Schema

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

Datasets to merge, in this order. Pick them or paste dataset IDs (or `username~dataset-name`). Up to 100. Leave empty for a free demo run on built-in sample data.

## `dedupe` (type: `boolean`):

Off = plain merge (all rows of all datasets).

## `dedupeBy` (type: `array`):

Rows are duplicates when ALL these fields are equal. Dot paths work for nested fields (e.g. `address.city`, `urls.0`). Empty = compare the whole row.

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

first = earliest row wins (datasets in input order). last = latest row wins. merge = one row per key, empty fields filled from later duplicates.

## `normalize` (type: `boolean`):

Compare key values case-insensitively with trimmed and collapsed whitespace; 10 and 10.0 count as equal. The output keeps the original values.

## `skipEmptyKeys` (type: `boolean`):

Rows whose key fields are all empty or missing are kept as they are instead of being collapsed into one.

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

Keep only rows matching ALL conditions, applied before deduplication. Each condition: {"field": "price", "op": "gte", "value": 10}. Ops: eq, ne, gt, gte, lt, lte, contains, notContains, startsWith, endsWith, regex, in, exists, notExists. Text comparison is case-insensitive; numbers in text are compared as numbers.

## `rename` (type: `object`):

Top-level fields to rename in the output, e.g. {"title": "name"}.

## `fields` (type: `array`):

Keep only these top-level fields (names after renaming), in this order. Empty = all fields.

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

Add a `sourceDatasetId` field to every output row.

## `maxItems` (type: `integer`):

Stop after this many output rows. Empty = no limit.

## Actor input object example

```json
{
  "dedupe": true,
  "dedupeBy": [],
  "keep": "first",
  "normalize": true,
  "skipEmptyKeys": true,
  "filters": [],
  "rename": {},
  "fields": [],
  "addSourceDatasetId": false
}
```

# Actor output Schema

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

One item per processed input in the default dataset (JSON, CSV, Excel via the dataset export).

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

Totals and statistics of the run (OUTPUT record).

# 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("cellwright/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 = {}

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

```

## MCP server setup

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