# Merge & Dedup Datasets: CSV, Excel, JSON (`mr.wolf/merge-dedup-datasets`) Actor

Merge several Apify datasets into one and remove duplicate rows by the fields you choose. Streams the rows in pages; tested with 2 million unique keys in 512 MB. Export as JSON, CSV or Excel.

- **URL**: https://apify.com/mr.wolf/merge-dedup-datasets.md
- **Developed by:** [Mr. Wolf](https://apify.com/mr.wolf) (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

from $0.21 / 1,000 rows written

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.
Since this Actor supports Apify Store discounts, the price gets lower the higher subscription plan you have.

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

## Merge & Dedup Datasets: CSV, Excel, JSON

Merge several Apify datasets into one and remove duplicate rows by the fields you choose for $0.30 per 1,000 rows, then export JSON, CSV or Excel.

Merge several Apify datasets into one and remove duplicate rows by the fields you choose. Rows are streamed in pages; memory grows only with the number of distinct keys (tested with 2 million unique keys in 512 MB). Export the result as JSON, CSV or Excel.

### How to use

1. **Pick the datasets.** In `Datasets to merge`, choose one or more datasets. They are read in the order you list them; duplicate IDs are ignored.
2. **Write the key fields.** In `Fields to dedupe on`, list the fields that identify a row (for example `url`). Rows with the same values in all of them are duplicates. Leave the list empty to compare the whole row.
3. **Run and export.** The merged rows land in the run's default dataset. Open the Storage tab and export as JSON, CSV, Excel, XML or HTML.

### Input

| Field         | Type              | Description                                                            | Default  |
| ------------- | ----------------- | ---------------------------------------------------------------------- | -------- |
| `datasetIds`  | array             | Datasets to merge (resource picker). At least one.                     | required |
| `dedupFields` | array of strings  | Fields that identify a duplicate. Empty means the whole row.           | `[]`     |
| `keep`        | `first` or `last` | Which row to keep among duplicates.                                    | `first`  |
| `fields`      | array of strings  | Output only these fields. Cannot be combined with `omitFields`.        | all      |
| `omitFields`  | array of strings  | Remove these fields from the output. Cannot be combined with `fields`. | none     |

Example input:

```json
{
  "datasetIds": ["aBcDeFgHiJkLmNoPq", "rStUvWxYzAbCdEfGh"],
  "dedupFields": ["url"],
  "keep": "first",
  "omitFields": ["scrapedAt"]
}
```

### Output

Rows are written to the default dataset with the shape of the source rows. A summary is saved in the key-value store record `OUTPUT`:

```json
{
  "rowsRead": 12500,
  "rowsWritten": 9800,
  "duplicatesRemoved": 2700,
  "rowsWithoutKey": 0,
  "chargeLimitReached": false,
  "perDataset": [
    { "datasetId": "aBcDeFgHiJkLmNoPq", "rowsRead": 7000 },
    { "datasetId": "rStUvWxYzAbCdEfGh", "rowsRead": 5500 }
  ]
}
```

`chargeLimitReached` is `true` when the run stopped because it reached the maximum charge you set for the run. The output is then incomplete: `rowsWritten` counts only the rows that were stored. Raise the maximum charge and run again to merge every row. The run still ends as succeeded, with a warning in the log.

### Integrations

Sample Make and n8n flows are in `docs/integrations/`. They call `run-sync-get-dataset-items`, which waits at most 300 seconds: for large merges start the run with `POST /v2/acts/mr.wolf~merge-dedup-datasets/runs` and read the default dataset when the run has finished.

### Pricing

Pay per event: **$0.30 per 1,000 rows written** to the dataset. No start fee. Duplicates that are removed are not charged. **Failed runs are free:** you pay only for rows actually delivered, so a run that fails before writing any row costs nothing.

| Apify plan              | Price per row written | Per 1,000 rows |
| ----------------------- | --------------------- | -------------- |
| Free                    | $0.00030              | $0.30          |
| Bronze                  | $0.00027              | $0.27          |
| Silver                  | $0.00024              | $0.24          |
| Gold, Platinum, Diamond | $0.00021              | $0.21          |

Example: merging two datasets of 10,000 rows each with 4,000 duplicates writes 16,000 rows and costs $4.80 on the Free plan.

### Limitations

- Rows whose key fields are all missing, null or empty are kept and are not deduplicated. They are counted in `rowsWithoutKey`.
- No conversion between numbers and strings: `1` and `"1"` are different keys.
- `keep: "last"` reads the datasets twice, so it takes longer on large inputs.
- If a field in `dedupFields` is not found on the first non-empty page of data, the run fails early and lists the fields that are available.
- Use either `fields` or `omitFields`, not both.
- `fields` and `omitFields` are applied after deduplication: duplicates are always detected on the full source row (or on `dedupFields`), never on the projected row.
- Every dataset is checked before the first row is written. An unknown or inaccessible dataset ID fails the run with `dataset not found or not accessible: <id>` and nothing is charged.
- With `keep: "last"`, rows appended to a source dataset while the run is in progress are ignored (each dataset is read up to the row count found in the first pass).
- Memory grows with the number of distinct keys, about 100-120 bytes each. Measured locally with Node.js limited to 512 MB of heap: 2 million unique keys used about 470 MB of process memory, 4 million about 670 MB, 5 million ran out of memory (same result for `keep: "first"` and `keep: "last"`). With 512 MB of run memory stay under 2 million distinct keys; for up to 4 million give the run 1 GB. Rows that are duplicates of a key already seen add no memory.

### FAQ

**Can I try it without my own data?**
Yes. Use the public sample dataset `UTAnv4EVvzl4RfYff` (5 rows, 2 duplicates by `url`) with `dedupFields: ["url"]`. The run writes 3 rows.

**How do I find the ID of my dataset?**
Open the run of the scraper in Apify Console and go to Storage > Dataset, or pick the dataset directly in the `Datasets to merge` field.

**Which copy of a duplicate is kept?**
With `keep: "first"` (default) the first row in input order is kept. With `keep: "last"` the last one is kept, at its original position.

**Can I deduplicate on more than one field?**
Yes. List several fields in `dedupFields` (for example `["name", "city"]`). Two rows are duplicates only when all the listed fields are equal.

**Are text comparisons case-insensitive?**
No. Values are compared exactly as they are stored. `"ACME"` and `"acme"` are different keys.

**How do I export to CSV or Excel?**
Open the default dataset of the run and use Export, or call the dataset items API with `format=csv` or `format=xlsx`.

**Does it modify my source datasets?**
No. The Actor only reads them (limited permissions, read access to the datasets you select) and writes the result to its own dataset.

# Actor input Schema

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

Apify datasets to merge, in order. Duplicate IDs are ignored. To try the Actor, use the public 5-row sample dataset UTAnv4EVvzl4RfYff (2 duplicates by url).

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

Rows with the same values in these fields are duplicates. Leave empty to compare the whole row.

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

Which row to keep among duplicates.

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

Only output these fields. Cannot be combined with 'Fields to omit'.

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

Remove these fields from the output. Cannot be combined with 'Fields to keep'.

## Actor input object example

```json
{
  "dedupFields": [
    "url"
  ],
  "keep": "first"
}
```

# Actor output Schema

## `dataset` (type: `string`):

The merged and deduplicated rows. Export as JSON, CSV or Excel.

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

Rows read, written, duplicates removed, rows without key, counts per dataset.

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

// Run the Actor and wait for it to finish
const run = await client.actor("mr.wolf/merge-dedup-datasets").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 = { "dedupFields": ["url"] }

# Run the Actor and wait for it to finish
run = client.actor("mr.wolf/merge-dedup-datasets").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 '{
  "dedupFields": [
    "url"
  ]
}' |
apify call mr.wolf/merge-dedup-datasets --silent --output-dataset

```

## MCP server setup

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

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/I2C1dHFEO9aq6eTtq/builds/KEQ8ggIuzrxcl6Krp/openapi.json
