# Dataset Merge, Dedup, Filter & Export to CSV/Excel (`xdavidt/dataset-merge-dedup-export`) Actor

Merge Apify datasets, remove duplicates by any fields (nested too), filter without code, pick/rename/flatten fields, keep only new items across runs, and export one CSV, Excel or JSON file. Streams millions of items, works with limited permissions and as an integration.

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

## Pricing

from $0.20 / 1,000 row in results

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/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, Dedup, Filter & Export to CSV/Excel

Combine the results of several Apify runs into **one clean dataset or file**. Remove duplicates by any field (nested ones too), filter rows without code, keep or rename only the columns you need, output **only new items since the last run**, and export a single **CSV, Excel (XLSX), JSON or JSONL** file.

It is built for big data and for automation:

- **Streams** datasets page by page, so 100k, 1M or more items don't run out of memory (tested: 390,000 items in 512 MB).
- Works with **limited permissions**: no "full access to your account" approval needed, so it runs in schedules, integrations, API calls and AI agents without extra prompts.
- **Integration-ready**: attach it to any scraper as an integration and it processes that run's dataset automatically.

### What can it do?

| Task | How |
|---|---|
| Merge datasets from many runs | Pick them in **Datasets** (order is kept) |
| Remove duplicates | **Deduplicate by fields**, e.g. `url`, or `title` + `address.city` |
| Smarter matching | Ignore case, extra whitespace, `www.`, trailing `/`, `#hash` and `utm_*` tracking parameters |
| Only new items vs. a previous result | **Skip items already in these datasets** |
| Only new items across scheduled runs | **Remember across runs**: set a history key like `daily-jobs` |
| Find the duplicates themselves | Output: **Only the duplicates** |
| Count duplicates without writing anything | Output: **Nothing, just count** |
| Filter rows | No-code rules: `equals`, `contains`, `regex`, `gt`/`lt` (works with `"$1,200"` and dates), `in`, `exists`, `isEmpty`... |
| Pick / drop / rename columns | **Keep only these fields**, **Remove these fields**, **Rename fields** |
| Flatten nested JSON | `{"address":{"city":"X"}}` becomes `address.city` |
| Custom logic | Optional JavaScript pre-process and post-process functions |
| One file for Excel or BI tools | **Export files**: CSV (UTF-8 with BOM, so Hebrew, Arabic, CJK and accents open correctly in Excel), XLSX (auto-split over 1,048,575 rows), JSON, JSONL |
| Grow a master list | **Also append to dataset**: add the results to an existing dataset |

### Quick start

1. Pick one or more datasets in **Datasets**.
2. Add a field to **Deduplicate by fields**, e.g. `url`.
3. Optional: choose **Export files**, e.g. CSV and Excel.
4. Run. The output items are in the run's dataset. Stats and links to the files are in the **OUTPUT** record.

#### Example input (API)

```json
{
    "datasetIds": ["DATASET_ID_1", "DATASET_ID_2"],
    "dedupeFields": ["url"],
    "dedupeNormalizeUrls": true,
    "filters": [
        { "field": "price", "op": "lt", "value": 100 },
        { "field": "location.city", "op": "in", "value": ["Berlin", "Paris"] }
    ],
    "pickFields": ["title", "url", "price", "location.city"],
    "renameFields": { "location.city": "city" },
    "exportFormats": ["csv", "xlsx"],
    "exportFileName": "products"
}
```

### Use it as an integration (after a scraper finishes)

1. Open your scraper (or task) → **Integrations** → **Add integration** → choose this Actor.
2. Set the input to:

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

Each time the scraper succeeds, this Actor deduplicates its results and outputs only the items you haven't seen in earlier runs. Put the dataset in `datasetIds` as shown. Under limited permissions the Actor can read only datasets passed in that field, so a dataset ID inside a raw webhook payload alone can't be read; the run then fails with a message saying exactly what to change.

Via the API you can also call it from your own code or from Make, Zapier or n8n with `datasetIds`.

### Output

- **Dataset**: the resulting items. Download them from the Console or API in any format.
- **OUTPUT** (key-value store): a summary like this:

```json
{
    "ok": true,
    "stats": { "read": 389666, "unique": 119833, "duplicates": 269833, "filteredOut": 0, "excluded": 0, "written": 119833 },
    "sources": [{ "datasetId": "...", "items": 150000, "read": 150000, "output": 119833 }],
    "files": [{ "format": "csv", "key": "merged.csv", "url": "https://api.apify.com/v2/key-value-stores/.../records/merged.csv?signature=...", "rows": 119833, "bytes": 40100000 }],
    "seconds": 156.7
}
```

- **Files**: exported CSV / XLSX / JSON / JSONL in the run's key-value store, with signed download links in OUTPUT.

Tip: if you only need a file, turn off **Write results to this run's dataset**. The run is faster and cheaper.

### Why another dedupe Actor? Reliability on real-world inputs

We built this to fix the most common reasons dataset-processing runs fail:

| Common failure | What this Actor does |
|---|---|
| "Insufficient permissions" when reading datasets | Datasets are declared as resource inputs with READ access, so limited-permission runs can read them; clear error messages if something isn't accessible |
| Out of memory on large datasets | Streams pages of 5,000 items; duplicates are tracked as compact 8-byte hashes (about 16 bytes per unique item) instead of full strings |
| Timeouts | Fast streaming (about 6,000 items/s at 1 GB); default timeout 4 hours |
| Server migrations restart the run and duplicate output | Progress is saved; after a migration the Actor resumes without writing the same items twice |
| Duplicate keys colliding | Keys are built from canonical JSON, so `"ab"+"c"` never equals `"a"+"bc"`, and objects match regardless of key order |
| Nested fields can't be used | Every field option accepts paths like `author.name` or `images[0].url` |
| Items with an empty dedupe field silently collapse into one | Kept by default (configurable) |
| Silent overspending | Respects your run's maximum cost and stops cleanly |

### Performance (measured on Apify)

| Job | Memory | Time |
|---|---|---|
| 2,000 items, 2 datasets, filter + dedupe + CSV/XLSX/JSON | 1 GB | 1 s |
| 150,000 items → 119,833 unique, written to dataset | 1 GB | 28 s |
| Same + CSV (40 MB) and XLSX (10 MB) files | 1 GB | 73 s |
| 389,666 items from 3 datasets → 119,833 unique + CSV only | 512 MB (peak 255 MB) | 157 s |

More memory also means more CPU, so use 2–4 GB for multi-million-item jobs.

### Pricing

Pay per event: you pay per item written to the output, a small fee per 1,000 items scanned, and per exported file. Items removed as duplicates or filtered out are not charged as output. See the **Pricing** tab for current prices. Set **Maximum cost per run** in run options to cap spend; the Actor stops cleanly at the limit.

### FAQ

**Can I process datasets from another Apify account?** Only if the owner shares them with you. Under limited permissions the Actor can access what you can access and pass in **Datasets**.

**Can I pass a run ID instead of a dataset ID?** Limited-permission Actors can't read other runs. Copy the run's dataset ID from its Storage tab, or use `{{resource.defaultDatasetId}}` in an integration.

**Is order preserved?** Yes. Datasets are read in the order given, and the first occurrence of each duplicate is kept.

**Where is the history for "Remember across runs" stored?** In a key-value store named `dataset-utility-history` in your account. Only 8-byte hashes are stored, never your data. Delete the record `seen-<key>` to reset it.

**Is my data shared anywhere?** No. Everything stays in your Apify account.

# Actor input Schema

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

One or more datasets to process, merged in this order. Pick them, or pass dataset IDs or names via API. As an integration after another Actor, use {"datasetIds": \["{{resource.defaultDatasetId}}"]}.

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

Fields whose combined value must be unique, e.g. url, or title + address.city. Nested paths like author.name or images\[0].url work. Leave empty for no deduplication.

## `dedupeWholeItem` (type: `boolean`):

When no dedupe fields are set, treat two items as duplicates only if all their fields are equal (key order does not matter).

## `dedupeCaseInsensitive` (type: `boolean`):

Treat "ACME Inc" and "acme inc" as the same value.

## `dedupeTrim` (type: `boolean`):

Trim and collapse whitespace before comparing.

## `dedupeNormalizeUrls` (type: `boolean`):

Compare URLs without protocol, www., trailing slash, #hash and tracking parameters (utm\_\*, fbclid, gclid, ref).

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

If all dedupe fields of an item are empty or missing, keep it instead of collapsing all such items into one.

## `output` (type: `string`):

What to write to the output.

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

Items whose dedupe key appears in these datasets are not output. Use it to get only new items compared with a previous result.

## `historyKey` (type: `string`):

Give a name, e.g. my-daily-jobs. Every run with the same key outputs only items never seen in previous runs, which is ideal for scheduled scrapers. Keys are stored as 8-byte hashes in a named key-value store in your account (dataset-utility-history).

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

Keep only items matching the rules. Each rule: {"field": "price", "op": "lt", "value": 100}. Ops: equals, notEquals, contains, notContains, startsWith, endsWith, regex, notRegex, gt, gte, lt, lte, in, notIn, exists, notExists, isEmpty, notEmpty. Text comparisons ignore case unless "caseSensitive": true. Numbers like "$1,200" and dates are compared numerically.

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

AND: an item must match every rule. OR: any rule is enough.

## `pickFields` (type: `array`):

Output only these fields (nested paths allowed, e.g. address.city). Also speeds up the run, because only the needed fields are downloaded.

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

Drop these fields from the output (nested paths allowed).

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

Map of old path to new path, e.g. {"title": "name", "location.city": "city"}.

## `flattenOutput` (type: `boolean`):

Turn {"address": {"city": "X"}} into {"address.city": "X"}. Exports to CSV and Excel are always flattened.

## `arrayMode` (type: `string`):

How arrays become columns when flattening and in CSV/Excel.

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

Add a \_\_sourceDatasetId field to every item, showing which dataset it came from.

## `preProcessFunction` (type: `string`):

JavaScript run on each input item before filters and dedupe. Return the item (modified), null to drop it, or an array to split it into several items. Second argument: { source, index }.

## `postProcessFunction` (type: `string`):

JavaScript run on each output item after dedupe and field shaping. Return the item, null to drop it, or an array.

## `writeToDefaultDataset` (type: `boolean`):

Store output items in the run's default dataset (downloadable as CSV, Excel, JSON, XML from the Console or API).

## `outputDatasetId` (type: `string`):

Append the output to an existing dataset of yours, e.g. a master list that grows with every run.

## `exportFormats` (type: `array`):

Also save the output as single files in the run's key-value store, with links in OUTPUT. CSV is UTF-8 with BOM, so Excel shows Hebrew, Arabic, Chinese and accents correctly. XLSX splits into extra sheets beyond 1,048,575 rows.

## `exportFileName` (type: `string`):

Base name for exported files (without extension).

## `csvDelimiter` (type: `string`):

Column separator for CSV. Use ; for Excel in many European locales.

## `offset` (type: `integer`):

Skip this many items from the start of the merged input.

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

Stop reading after this many input items. Empty = all.

## `maxOutputItems` (type: `integer`):

Stop after writing this many items. Useful to cap cost.

## `skipHiddenFields` (type: `boolean`):

Drop fields starting with # and empty items, as the Console's "clean" export does.

## `pageSize` (type: `integer`):

Items per API request. Lower it if your items are very large (several hundred KB each).

## `payload` (type: `object`):

Filled in automatically when this Actor runs as an integration or from a webhook; the triggering run's dataset is processed.

## Actor input object example

```json
{
  "dedupeWholeItem": false,
  "dedupeCaseInsensitive": false,
  "dedupeTrim": true,
  "dedupeNormalizeUrls": false,
  "keepItemsWithoutKey": true,
  "output": "unique",
  "filters": [],
  "filterLogic": "and",
  "renameFields": {},
  "flattenOutput": false,
  "arrayMode": "join",
  "addSourceDatasetId": false,
  "preProcessFunction": "// (item, { source }) => {\n//     item.domain = new URL(item.url).hostname;\n//     return item;\n// }",
  "postProcessFunction": "// (item) => item",
  "writeToDefaultDataset": true,
  "exportFormats": [],
  "exportFileName": "output",
  "csvDelimiter": ",",
  "offset": 0,
  "skipHiddenFields": false,
  "pageSize": 5000
}
```

# Actor output Schema

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

No description

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

No description

## `files` (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 = {
    "filters": [],
    "renameFields": {},
    "preProcessFunction": `// (item, { source }) => {
//     item.domain = new URL(item.url).hostname;
//     return item;
// }`,
    "postProcessFunction": "// (item) => item"
};

// Run the Actor and wait for it to finish
const run = await client.actor("xdavidt/dataset-merge-dedup-export").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 = {
    "filters": [],
    "renameFields": {},
    "preProcessFunction": """// (item, { source }) => {
//     item.domain = new URL(item.url).hostname;
//     return item;
// }""",
    "postProcessFunction": "// (item) => item",
}

# Run the Actor and wait for it to finish
run = client.actor("xdavidt/dataset-merge-dedup-export").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 '{
  "filters": [],
  "renameFields": {},
  "preProcessFunction": "// (item, { source }) => {\\n//     item.domain = new URL(item.url).hostname;\\n//     return item;\\n// }",
  "postProcessFunction": "// (item) => item"
}' |
apify call xdavidt/dataset-merge-dedup-export --silent --output-dataset

```

## MCP server setup

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

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/OwKThVhD9wMzzzjBn/builds/Dn5ZfMRm4cTWbVy9M/openapi.json
