# Merge, Dedupe & Transform Datasets to CSV & JSON (`mcpkit/merge-dedup-datasets`) Actor

Merge Apify datasets and CSV, JSON or Excel files, remove duplicates, filter rows, rename and select columns, flatten nested JSON and export clean CSV, JSONL or XLSX. No code, limited permissions, built for scraping pipelines, n8n and AI agents. Pay per row.

- **URL**: https://apify.com/mcpkit/merge-dedup-datasets.md
- **Developed by:** [mcpkit](https://apify.com/mcpkit) (community)
- **Features:** Limited permissions
- **Stats:** 1 total users, 0 monthly users, 0.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.03 / 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

### What is Merge, Dedupe & Transform Datasets

Merge, Dedupe & Transform Datasets merges Apify datasets and CSV, JSON, JSONL or Excel files into one clean table, removes duplicates, filters rows and reshapes columns in a single run, without writing code. Typical job: you scraped Google Maps five times, and you want one list without duplicate places, only places with a phone number, six columns, as a CSV.

- **Merge** any number of Apify datasets and file URLs (CSV, TSV, JSON, JSONL, XLSX) into one result.
- **Remove duplicates** by one or more fields (`placeId`, `url`, `email`) or by the whole row. Keep the first or the last copy, optionally ignoring case and spaces.
- **Filter rows** with simple conditions: equals, contains, greater than, regex, empty, in a list and more.
- **Flatten nested JSON** into flat columns (`address.city`), ready for spreadsheets.
- **Select, rename and remove columns**, **sort** and **limit** the result.
- **Export** to the dataset (download as CSV, JSON, Excel and more), to one CSV, JSONL or XLSX file with a direct link, or both. File-only mode is the fastest way to export large results.

It runs with **limited permissions**: it can read only the datasets you pass to it, so it is safe to give to AI agents and automation tools. It streams data page by page, so a million rows do not need a big machine. You pay per row written to the result; filtered-out rows and removed duplicates are free.

#### What you can use it for

- **Scraping pipelines**: merge the results of many runs of the same scraper (Google Maps, Instagram, Amazon, websites) and remove the duplicates.
- **Lead lists**: combine several lead files, keep only rows with an email or phone, and export a clean CSV for your CRM.
- **Incremental updates**: keep the newest version of each record with `keepLast` when you merge old and new datasets.
- **AI agents and n8n**: let an agent or workflow clean up scraped data before it reads it.

### How to use

#### Apify Console

1. Open the Actor. In **Datasets**, pick one or more datasets from your account. To add files, paste their URLs into **File URLs**.
2. In **Dedup fields**, enter the field that identifies a duplicate, for example `placeId`. Leave it empty to compare whole rows.
3. Optionally add **Filters**, **Fields to keep**, **Rename fields**, **Sort by field** and choose **Also save as file**.
4. Click **Start**. The result is in the **Output** tab: the dataset rows and the `OUTPUT` report with the file link.

#### API

```bash
curl -X POST "https://api.apify.com/v2/acts/mcpkit~merge-dedup-datasets/run-sync-get-dataset-items?token=<APIFY_TOKEN>" \
  -H "Content-Type: application/json" \
  -d '{
    "datasets": ["<DATASET_ID_1>", "<DATASET_ID_2>"],
    "dedupFields": ["placeId"],
    "filters": [{"field": "phone", "op": "not_empty"}],
    "fields": ["title", "phone", "website", "address", "totalScore"],
    "outputFile": "csv"
  }'
```

Dataset IDs passed through the API work the same way as datasets picked in the Console.

#### Apify MCP for Claude and Cursor

```json
{
  "mcpServers": {
    "apify": {
      "url": "https://mcp.apify.com/?tools=mcpkit/merge-dedup-datasets",
      "headers": { "Authorization": "Bearer <APIFY_TOKEN>" }
    }
  }
}
```

Then ask: *"Merge datasets A and B, remove duplicates by url and keep only rows where price is below 50."* The agent calls the tool with the dataset IDs, `dedupFields` and `filters`, then reads the dataset.

#### Chain it after another Actor

In your scraper, open **Integrations** → **Run Actor after**, choose this Actor and set the input to `{"datasets": ["{{resource.defaultDatasetId}}"], "dedupFields": ["url"]}`. Every finished scraper run is cleaned automatically.

#### n8n and Make

- n8n HTTP Request node: method `POST`, URL `https://api.apify.com/v2/acts/mcpkit~merge-dedup-datasets/run-sync-get-dataset-items`, query parameter `token` = your Apify API token.
- JSON body with dataset IDs from previous nodes:

```json
{ "datasets": {{ JSON.stringify($json.datasetIds) }}, "dedupFields": ["placeId"], "outputFile": "csv" }
```

### Input

| Field | Type | Description |
|---|---|---|
| `datasets` | array | Apify dataset IDs or names (`username~name` works too). Required unless `fileUrls` is set. |
| `fileUrls` | array | Public URLs of CSV, TSV, JSON, JSONL or XLSX files, up to 100 MB each. Apify dataset export links work too. |
| `addSource` | boolean | Add `_source` (dataset ID or file URL) to each row. Default `false`. |
| `flatten` | boolean | Flatten nested objects into `a.b.c` columns. Default `false`. |
| `flattenArrays` | `json` / `index` | Arrays as a JSON string in one column, or one column per item (`tags.0`, `tags.1`). Default `json`. |
| `filters` | array | Conditions `{field, op, value, ignoreCase}`. See the operators below. |
| `filterLogic` | `all` / `any` | Every condition must match (AND) or at least one (OR). Default `all`. |
| `dedup` | boolean | Remove duplicates. Default `true`. |
| `dedupFields` | array | Fields that identify a duplicate. Empty = compare whole rows. |
| `dedupMode` | `keepFirst` / `keepLast` | Which copy to keep. Default `keepFirst`. |
| `dedupNormalize` | boolean | Ignore case and leading/trailing spaces when comparing. Default `false`. |
| `fields` | array | Keep only these fields, in this order. Missing fields become `null`. |
| `renameFields` | object | `{"old name": "new name"}`. |
| `omitFields` | array | Remove these fields. |
| `sortBy` | string | Sort by this field. Numbers sort as numbers, empty values go last. |
| `sortOrder` | `asc` / `desc` | Default `asc`. |
| `limit` | integer | Write at most this many rows. |
| `outputFile` | `none` / `csv` / `jsonl` / `xlsx` | Save the result as one file. Default `none`. Required when `outputTo` is `file` or `both`. |
| `outputTo` | `dataset` / `file` / `both` | Where rows go. `file` writes rows only to the file, with one summary row in the dataset. Default `dataset`. |

Field names can be dot paths into nested objects: `address.city`, `reviews.0.text`.

#### Processing order

The steps always run in this order: **1. Merge** (datasets first, then files, in the order given) → **2. Flatten** → **3. Filter** → **4. Remove duplicates** → **5. Select, remove and rename fields** → **6. Sort and limit**. So filters and `dedupFields` use the original field names, and `sortBy` can use the new name or the original one.

#### Filter operators

| `op` | Keeps rows where the field... | Example |
|---|---|---|
| `eq` / `ne` | equals / does not equal the value (numbers are compared as numbers, so `"4.5"` equals `4.5`) | `{"field": "city", "op": "eq", "value": "Paris"}` |
| `gt`, `gte`, `lt`, `lte` | is greater / less than the value (numbers, or text such as ISO dates) | `{"field": "rating", "op": "gte", "value": 4}` |
| `contains` / `not_contains` | contains the text; for arrays, any item contains it | `{"field": "categories", "op": "contains", "value": "Cafe"}` |
| `regex` | matches a regular expression | `{"field": "email", "op": "regex", "value": "@gmail\\.com$"}` |
| `in` | equals one of the values | `{"field": "country", "op": "in", "value": ["US", "CA"]}` |
| `exists` / `not_exists` | is present (even if null) / is missing | `{"field": "website", "op": "exists"}` |
| `empty` / `not_empty` | is missing, null, `""`, `[]` or `{}` / has a value | `{"field": "phone", "op": "not_empty"}` |

Add `"ignoreCase": true` to any text condition to ignore letter case.

#### Input example

```json
{
  "datasets": ["aBcD1234efGH5678i", "jKlM9012nOpQ3456r"],
  "fileUrls": ["https://example.com/old-leads.csv"],
  "dedupFields": ["placeId"],
  "dedupMode": "keepLast",
  "filters": [
    {"field": "phone", "op": "not_empty"},
    {"field": "totalScore", "op": "gte", "value": 4}
  ],
  "flatten": true,
  "fields": ["title", "phone", "website", "address.city", "totalScore"],
  "renameFields": {"address.city": "city", "totalScore": "rating"},
  "sortBy": "rating",
  "sortOrder": "desc",
  "outputFile": "xlsx"
}
```

### Output

#### Dataset

One dataset item per result row. The fields are your own fields after the steps above, for example:

```json
[
  {"title": "Cafe One", "phone": "+33 1 23 45 67 89", "website": "https://cafe-one.fr", "city": "Paris", "rating": 4.8},
  {"title": "Shop Three", "phone": "+33 4 11 22 33 44", "website": null, "city": "Lyon", "rating": 4.5}
]
```

Download it from the **Output** or **Storage** tab, or through the API, as CSV, JSON, JSONL, Excel, XML or HTML.

#### File-only output (`outputTo: "file"`)

The rows are written only to the file. The dataset gets one summary row, so API, MCP and n8n callers that read the dataset get the link right away:

```json
{"resultFileUrl": "https://api.apify.com/v2/key-value-stores/.../records/result.csv?signature=...", "resultFileFormat": "csv", "resultFileTruncated": false, "rowsWritten": 18250, "rowsRead": 25000, "rowsFilteredOut": 3100, "duplicatesRemoved": 3650, "chargeLimitReached": false, "failedSources": 0}
```

#### OUTPUT report and file

The `OUTPUT` record in the key-value store shows what happened to your rows and links to the file:

```json
{
  "rowsWritten": 18250,
  "rowsRead": 25000,
  "rowsFilteredOut": 3100,
  "duplicatesRemoved": 3650,
  "chargeLimitReached": false,
  "sources": [
    {"source": "aBcD1234efGH5678i", "type": "dataset", "format": "dataset", "rowsRead": 20000, "invalidLines": 0, "error": null},
    {"source": "https://example.com/old-leads.csv", "type": "file", "format": "csv", "rowsRead": 5000, "invalidLines": 0, "error": null}
  ],
  "outputFile": {"format": "xlsx", "key": "result.xlsx", "url": "https://api.apify.com/v2/key-value-stores/.../records/result.xlsx", "rows": 18250, "truncated": false},
  "datasetId": "xYz...",
  "durationSec": 14.2
}
```

- A source that cannot be read (wrong ID, broken file) is listed with an `error`, and the run continues with the other sources. The run fails only if no source can be read.
- JSONL lines that are not valid JSON are skipped and counted in `invalidLines`.
- CSV values stay as text, exactly as in the file. XLSX dates become ISO strings.

### How much does it cost to merge and deduplicate datasets?

You pay per row written to the result. Rows removed by filters or as duplicates are free.

| Event | Price (Free plan) | Bronze | Silver | Gold |
|---|---|---|---|---|
| Actor start | $0.00005 | $0.00005 | $0.00005 | $0.00005 |
| Row written | $0.00005 | $0.000045 | $0.00004 | $0.000035 |

A row is charged once, whether it goes to the dataset, the file or both. The summary row in file-only mode is free. Examples:

| Rows in the result | Free plan | Gold plan |
|---|---|---|
| 1,000 (for example 3 datasets with 2,000 rows, half removed as duplicates) | $0.05 | $0.035 |
| 10,000 | $0.50 | $0.35 |
| 100,000 | $5.00 | $3.50 |

Set a maximum cost per run in the run options: the Actor stops when it reaches it, keeps the rows it already wrote (in the dataset and the file) and reports `"chargeLimitReached": true`.

### FAQ

#### Why do I need to select datasets in the input?

The Actor runs with limited permissions: it can only read the datasets you pass in the `datasets` field, and nothing else in your account. This is safer for you and is why AI agents can use it. Pick the datasets in the Console or pass their IDs through the API. If a dataset is not found, check the ID; for a name, `username~dataset-name` always works.

#### How do I export large results?

Set `outputTo` to `file` and `outputFile` to `csv`, `jsonl` or `xlsx`. The rows are written straight to one file instead of the dataset, which is much faster for hundreds of thousands of rows and has no dataset write limits. Download the file from the link in the summary row or in `OUTPUT`. CSV and JSONL are the fastest; XLSX is limited by Excel to 1,048,575 rows. Use `both` if you also need the rows in the dataset, for example to read them with `get-dataset-items` in Apify MCP.

#### How many rows can it handle?

Without sorting, rows are processed as a stream: only a 64-bit fingerprint of each unique key is kept in memory for dedup, so the default 512 MB handles about 5 million unique rows (1 million rows take about 120 MB). For more, give the run more memory. Sorting and `keepLast` keep a small index per row, so they support up to 1,000,000 rows after filtering. Files can be up to 100 MB each. Excel files are limited by Excel itself to 1,048,575 rows; use CSV or JSONL for more.

#### Can I run custom JavaScript or Python?

No. All steps are declarative options, on purpose: no code means no security risk when an AI agent or a shared workflow builds the input, and no code to debug. If you need a step that is missing, open an issue.

#### How are duplicates detected?

With `dedupFields`, two rows are duplicates when all those fields are equal. Rows where all of these fields are empty are never treated as duplicates. Without `dedupFields`, whole rows are compared, ignoring the order of keys and the `_source` field. `dedupNormalize` ignores letter case and spaces around values, and treats `1` and `"1"` as equal.

#### Does it change my source datasets?

No. It only reads them. The result goes to the run's own dataset and key-value store.

#### How do I chain it after another Actor?

Use **Integrations** → **Run Actor after** on your scraper or task, as shown in How to use. In n8n or Make, call it with the dataset ID from the previous run.

#### How is it different from other dedup Actors?

It also merges files, filters, flattens, reshapes and sorts in the same run, runs with limited permissions so AI agents can call it, writes large results straight to a file, and costs $0.50 per 10,000 result rows on the Free plan.

### Other tools from mcpkit

- [PDF to Markdown & Text Extractor for LLM & RAG](https://apify.com/mcpkit/pdf-to-markdown): PDF, Word, Excel, PowerPoint and scans (OCR) to Markdown, JSON tables and RAG chunks.
- [Website Tech Stack Detector & Technology Lookup](https://apify.com/mcpkit/tech-stack-detector): CMS, frameworks, analytics, hosting, email provider and SaaS tools of any website.

# Changelog

This Actor's version history is a separate document: https://apify.com/mcpkit/merge-dedup-datasets/changelog.md

# Actor input Schema

## `datasets` (type: `array`):

Apify datasets to merge, by ID or name. Pick them here or pass IDs via API, e.g. \["aBcD1234efGH5678i"]. The Actor can read only datasets passed in this field. Required unless fileUrls is provided.

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

Public URLs of CSV, TSV, JSON, JSONL or XLSX files (up to 100 MB each), merged after the datasets. Apify dataset export links work too. Example: \["https://example.com/leads.csv"]. Required unless datasets is provided.

## `addSource` (type: `boolean`):

Add a \_source field to every row with the dataset ID or file URL it came from. Example: true

## `flatten` (type: `boolean`):

Turn nested objects into flat columns with dot names, e.g. {"address": {"city": "Paris"}} becomes {"address.city": "Paris"}. Useful before CSV or Excel export. Example: true

## `flattenArrays` (type: `string`):

How to flatten arrays: json keeps each array as a JSON string in one column; index makes a column per item (tags.0, tags.1). Example: json

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

Keep only rows matching these conditions: {field, op, value, ignoreCase}. op: eq, ne, gt, gte, lt, lte, contains, not_contains, regex, exists, not_exists, empty, not_empty, in. Dot paths work (address.city). Example: \[{"field": "phone", "op": "not_empty"}, {"field": "rating", "op": "gte", "value": 4}]

## `filterLogic` (type: `string`):

all: a row must match every filter (AND). any: at least one filter (OR). Example: all

## `dedup` (type: `boolean`):

Remove duplicate rows. Duplicates are found by dedupFields, or by the whole row when dedupFields is empty. Example: true

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

Fields that identify a duplicate, e.g. \["placeId"] or \["name", "address"]. Empty = compare whole rows (the \_source field is ignored). Rows where all these fields are empty are always kept.

## `dedupMode` (type: `string`):

keepFirst keeps the first row seen (in source order); keepLast keeps the last one, e.g. the newest scrape when datasets are listed oldest first. Example: keepFirst

## `dedupNormalize` (type: `boolean`):

Compare dedup values ignoring letter case and leading/trailing spaces, so "ACME " and "acme" are duplicates. Example: false

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

Keep only these fields, in this order; missing fields become null. Dot paths work (address.city). Empty = keep all fields. Example: \["title", "phone", "website"]

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

Rename output fields: {"old name": "new name"}. Applied after fields and omitFields. Example: {"title": "name", "totalScore": "rating"}

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

Remove these fields from every row. Dot paths work. Example: \["reviews", "imageUrls"]

## `sortBy` (type: `string`):

Sort the result by this field (output or original name). Numbers sort as numbers; empty values go last. Up to 1,000,000 rows after filtering. Example: rating

## `sortOrder` (type: `string`):

asc = A to Z, smallest first; desc = Z to A, largest first. Example: desc

## `limit` (type: `integer`):

Write at most this many rows (after sort). Empty = no limit. Example: 1000

## `outputFile` (type: `string`):

Save the result as one CSV, JSONL or XLSX file in the key-value store and return its link in OUTPUT. Required when outputTo is file or both. Example: csv

## `outputTo` (type: `string`):

dataset: rows go to the dataset (plus the file, if outputFile is set). file: rows go only to the outputFile file and the dataset gets one summary row with the link. Use file for large exports: faster and no dataset write limits. both: dataset and file. Example: file

## Actor input object example

```json
{
  "fileUrls": [
    "https://raw.githubusercontent.com/datasets/currency-codes/main/data/codes-all.csv"
  ],
  "addSource": false,
  "flatten": false,
  "flattenArrays": "json",
  "filters": [
    {
      "field": "WithdrawalDate",
      "op": "empty"
    }
  ],
  "filterLogic": "all",
  "dedup": true,
  "dedupFields": [
    "AlphabeticCode"
  ],
  "dedupMode": "keepFirst",
  "dedupNormalize": false,
  "fields": [
    "AlphabeticCode",
    "Currency",
    "NumericCode",
    "MinorUnit"
  ],
  "renameFields": {
    "AlphabeticCode": "code",
    "Currency": "currency"
  },
  "omitFields": [],
  "sortOrder": "asc",
  "outputFile": "csv",
  "outputTo": "dataset"
}
```

# Actor output Schema

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

No description

## `report` (type: `string`):

No description

# 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 = {
    "fileUrls": [
        "https://raw.githubusercontent.com/datasets/currency-codes/main/data/codes-all.csv"
    ],
    "filters": [
        {
            "field": "WithdrawalDate",
            "op": "empty"
        }
    ],
    "dedupFields": [
        "AlphabeticCode"
    ],
    "fields": [
        "AlphabeticCode",
        "Currency",
        "NumericCode",
        "MinorUnit"
    ],
    "renameFields": {
        "AlphabeticCode": "code",
        "Currency": "currency"
    },
    "outputFile": "csv"
};

// Run the Actor and wait for it to finish
const run = await client.actor("mcpkit/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 = {
    "fileUrls": ["https://raw.githubusercontent.com/datasets/currency-codes/main/data/codes-all.csv"],
    "filters": [{
            "field": "WithdrawalDate",
            "op": "empty",
        }],
    "dedupFields": ["AlphabeticCode"],
    "fields": [
        "AlphabeticCode",
        "Currency",
        "NumericCode",
        "MinorUnit",
    ],
    "renameFields": {
        "AlphabeticCode": "code",
        "Currency": "currency",
    },
    "outputFile": "csv",
}

# Run the Actor and wait for it to finish
run = client.actor("mcpkit/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 '{
  "fileUrls": [
    "https://raw.githubusercontent.com/datasets/currency-codes/main/data/codes-all.csv"
  ],
  "filters": [
    {
      "field": "WithdrawalDate",
      "op": "empty"
    }
  ],
  "dedupFields": [
    "AlphabeticCode"
  ],
  "fields": [
    "AlphabeticCode",
    "Currency",
    "NumericCode",
    "MinorUnit"
  ],
  "renameFields": {
    "AlphabeticCode": "code",
    "Currency": "currency"
  },
  "outputFile": "csv"
}' |
apify call mcpkit/merge-dedup-datasets --silent --output-dataset

```

## MCP server setup

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