# Merge & Dedupe Datasets: Combine, Filter, Export CSV/XLSX (`mossfetch/dataset-merge-dedupe`) Actor

Merge several Apify datasets into one, remove duplicate rows on any key, filter and rename fields, and export CSV or XLSX. Optional only-new-rows mode for repeat jobs. $0.50 per 1,000 rows; duplicates and filtered rows are free.

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

## Pricing

$0.50 / 1,000 row delivereds

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

## Merge & Dedupe Datasets: Combine, Filter, Export CSV/XLSX

Merge datasets, dedupe and remove duplicates, with CSV and XLSX export. Use it when you have two or more Apify datasets (for example from different scrapers) and need one clean, deduplicated table. Run with demo on first; the demo is free.

### Who it's for

- People combining the outputs of several scrapers or several runs of one scraper.
- Teams who run a scraper daily and only want rows they have not seen before.
- Anyone who needs a deduplicated CSV or XLSX from Apify data.

Merge several Apify datasets into one clean list. Remove duplicates on any key (not just `url`), filter rows, rename or drop fields, and export to a dataset, CSV or XLSX in one run.

It only reads datasets you name that your account can read, and it sends your data nowhere else. Row contents are never written to the run log. You pay per row in the result: duplicates, filtered-out and already-seen rows are free, and there are no per-file or start fees.

### Try it in 10 seconds

Leave **Demo mode** on and press Start. The actor builds 2 sample datasets (230 rows, with overlaps and repeats) and runs the full pipeline. Demo runs are free. When you add dataset IDs, demo mode is ignored and the actor uses your data.

### What it does

- **Merge** any number of datasets, in the order you list them.
- **Dedupe** on a set of keys: rows are duplicates when ALL keys match. Dot paths work (`address.city`). Options: ignore case, ignore extra whitespace, keep first or last. Rows missing a key are kept (or dropped, your choice).
- **Only new items since last run**: output only rows whose key was not seen in earlier runs. Memory is kept as short hashes in a named key-value store (`dataset-merge-dedupe-state`), one record per **State name**, so no row data is stored. Use the same State name every run of the same job.
- **Filter** rows: `equals, notEquals, contains, notContains, gt, gte, lt, lte, in, exists, notExists`.
- **Rename / keep / drop fields**, optional `_sourceDataset` field.
- **Export** CSV (UTF-8 with BOM) and/or XLSX to the key-value store as `OUTPUT.csv` and `OUTPUT.xlsx`. Cells starting with `= + - @` are escaped to block spreadsheet formula injection.

### Input example

```json
{
  "datasetIds": ["<dataset id A>", "<dataset id B>"],
  "dedupeKeys": ["url"],
  "filters": [{ "field": "price", "op": "gte", "value": 10 }],
  "renameFields": { "title": "name" },
  "onlyNewItems": false,
  "exportFormats": ["csv", "xlsx"]
}
```

### Output

Rows are your own data, so no fixed output fields are declared: each row keeps the fields of the source dataset (after your keep, drop and rename settings). One row per kept item in the default dataset, plus `RUN_SUMMARY` (rows read, duplicates, filtered out, already seen, delivered).

### Pricing

$0.50 per 1,000 rows delivered (pay per event, `row` = $0.0005). No start fee, no export or webhook fee.

### Limits and notes

- Order of steps: filter, then dedupe, then only-new check, then field changes. Dedupe compares the original values, before renaming or dropping.
- Rows are held in memory until the run ends (needed for CSV/XLSX and keep-last). About 1M small rows fit in 4 GB.
- "Only new items" remembers keys as 16-character hashes in records of 200,000, so state has no practical size limit.
- If the max-charge limit stops the run early, state for "only new items" is not advanced, so the next run returns the same rows.
- Only public Apify datasets or ones your token can read. No web scraping is done.

### FAQ

**How does "only new items" remember what it has seen?** It stores 16-character hashes of each row's key in a named key-value store (`dataset-merge-dedupe-state`), one record per State name. No row data is stored. Use the same State name for every run of the same job.

**Are duplicates charged?** No. Only rows delivered to the output are charged; duplicates, filtered-out and already-seen rows are free, and the demo is free.

### Use it from code (API)

```bash
curl -X POST "https://api.apify.com/v2/acts/mossfetch~dataset-merge-dedupe/run-sync-get-dataset-items?token=$APIFY_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"datasetIds":["<dataset id A>","<dataset id B>"],"dedupeKeys":["url"]}'
```

Or with the JavaScript client: `await new ApifyClient({ token }).actor('mossfetch/dataset-merge-dedupe').call(input)`, then read `defaultDatasetId`.

### Use in Make, n8n or Zapier

Run this Actor from Make, n8n or Zapier with an Apify account: add the Apify "Run Actor" step and select or enter the Actor `mossfetch/dataset-merge-dedupe` (Actor ID `kGH0siJabVGv7mvtW`). Pass the input as JSON, then read the dataset in the next step. Nothing else to install.

# Actor input Schema

## `demo` (type: `boolean`):

Run on 2 built-in sample datasets (about 200 rows). Free, needs no dataset IDs. Ignored when you add dataset IDs, so your own data always wins.

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

Apify datasets to merge, in order. Pick datasets from your account or paste dataset IDs. The actor gets read access to these datasets only. When you add any, demo mode is ignored. Example: \["Zq1abc...", "Xy2def..."].

## `dedupeKeys` (type: `array`):

Rows with the same values in ALL these fields are duplicates. Dot paths work (address.city). Leave empty for no dedupe (unless 'Dedupe on all fields' is on).

## `dedupeAllFields` (type: `boolean`):

With no dedupe keys, treat rows as duplicates only when every field matches.

## `keepOnly` (type: `string`):

Keep the first or the last row of each duplicate group. 'last' holds all rows in memory.

## `caseInsensitive` (type: `boolean`):

Treat "ACME" and "acme" as the same key value.

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

Trim and collapse spaces in key values before comparing, so " a  b " matches "a b".

## `dropRowsMissingKey` (type: `boolean`):

Rows where a dedupe key field is empty cannot be compared. By default they are kept; switch on to drop them.

## `onlyNewItems` (type: `boolean`):

Output only rows whose key was not seen in earlier runs. Keys are remembered as hashes in a named key-value store. With no dedupe keys the whole row is the key.

## `stateKey` (type: `string`):

Separate 'only new items' memory per use case. Use the same name on every run of the same job.

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

Keep only rows matching ALL filters. Each is {"field": "price", "op": "gte", "value": 10}. Ops: equals, notEquals, contains, notContains, gt, gte, lt, lte, in, exists, notExists.

## `keepFields` (type: `array`):

Output only these fields (dot paths allowed). Leave empty to keep all. Example: \["url", "title"].

## `dropFields` (type: `array`):

Remove these fields from every row. Ignored when 'Keep only these fields' is set. Example: \["url", "title"].

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

Map old names to new names, e.g. {"title": "name"}.

## `addSourceField` (type: `boolean`):

Add \_sourceDataset to each row.

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

Save the result as CSV and/or XLSX in the key-value store (OUTPUT.csv, OUTPUT.xlsx). The dataset is always written. Example: \["csv", "xlsx"].

## `maxRows` (type: `integer`):

Stop after this many output rows. 0 means no limit.

## Actor input object example

```json
{
  "demo": true,
  "dedupeKeys": [
    "url"
  ],
  "dedupeAllFields": false,
  "keepOnly": "first",
  "caseInsensitive": false,
  "trimWhitespace": true,
  "dropRowsMissingKey": false,
  "onlyNewItems": false,
  "stateKey": "default",
  "addSourceField": false,
  "maxRows": 0
}
```

# Actor output Schema

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

The merged, deduplicated and transformed rows.

## `runSummary` (type: `string`):

Rows read, duplicates removed, rows filtered out, rows already seen and rows delivered.

## `csv` (type: `string`):

Present when csv is chosen in exportFormats.

## `xlsx` (type: `string`):

Present when xlsx is chosen in exportFormats.

# 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 = {
    "demo": true,
    "dedupeKeys": [
        "url"
    ]
};

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

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

```

## MCP server setup

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