# Dataset Merge & Dedup (`black-vikings/dataset-dedup`) Actor

Merge one or more Apify datasets, remove duplicates by any field (nested paths too), keep only items never seen in earlier runs, and output one clean dataset.

- **URL**: https://apify.com/black-vikings/dataset-dedup.md
- **Developed by:** [Black Vikings](https://apify.com/black-vikings) (community)
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

from $0.30 / 1,000 output items

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

Merge one or more Apify datasets into one clean dataset: duplicates removed, optional filters and field cleanup, and an **"only new items"** mode that outputs only what earlier runs have not already delivered.

Built for the step after a scraper: run it from a webhook or integration when your scraper finishes, and send only fresh, unique rows to your sheet, CRM, or database.

### Why use it

- **Handles large datasets.** Items are streamed page by page, so a 1M-item dataset never sits in memory. Only a 16-character hash per unique key is kept.
- **Works with limited permissions.** Pick datasets in the input and Apify grants read access automatically.
- **Clear errors.** A missing dataset, a dataset the run may not read, or empty input stops the run with a message naming the dataset and how to fix it. You are never charged for a silent empty run.
- **Only new items.** Remembers what earlier runs output, so daily runs deliver just the new rows.
- **Safe filters.** Simple declarative conditions. No custom JavaScript is executed.

### Typical use: after a scraper run

1. In your scraper's **Integrations** tab, add *Run another Actor* (or a webhook on `ACTOR.RUN.SUCCEEDED`) that starts this Actor.
2. Pass the finished run's dataset: `{"datasetIds": ["{{resource.defaultDatasetId}}"], "dedupFields": ["url"], "onlyNewSinceLastRun": true, "stateKey": "my-scraper"}`.
3. Connect this Actor's output to Google Sheets, Make, Zapier, or your API.

### Input

| Field | What it does |
|---|---|
| `datasetIds` | Datasets to merge, in order. |
| `actorOrTaskId`, `lastRuns` | Also merge the default datasets of the last N successful runs (needs full permissions). |
| `dedupFields` | Fields that identify an item, nested paths allowed (`address.city`). Empty = compare whole items. |
| `dedupMode` | `keepFirst` (default) or `keepLast`. `keepLast` reads the data twice. |
| `onlyNewSinceLastRun`, `stateKey` | Skip items whose key an earlier run with the same `stateKey` already output. |
| `fields`, `omitFields`, `renameFields` | Keep, drop, or rename fields in the output. |
| `filter` | `{"match": "all", "conditions": [{"field": "status", "operator": "equals", "value": "open"}]}`. Operators: `equals`, `notEquals`, `contains`, `exists`, `notExists`. |
| `outputDatasetName` | Write to a named dataset instead of the run's default dataset. |

Order of operations: merge, then filter, then dedup (on the original fields), then only-new, then pick/omit/rename.

Field paths use dots for nested fields (`address.city`). Array indexes (`tags.0`) are allowed in `dedupFields` and `filter` only; `fields`, `omitFields`, and `renameFields` reject them, so name the whole field instead.

Items that have none of the `dedupFields` are kept as they are (never merged into one), counted as `missingKeyItems`, and reported in the log. If no item has any of the fields, the run fails before charging anything: that is almost always a typo.

### Example

Input:

```json
{
  "datasetIds": ["aBcD1234", "eFgH5678"],
  "dedupFields": ["url"],
  "onlyNewSinceLastRun": true,
  "stateKey": "shops-mx",
  "omitFields": ["debug"],
  "renameFields": { "title": "name" }
}
```

Besides the items, every run stores a summary in the `OUTPUT` record of its key-value store:

```json
{
  "itemsRead": 12000, "filteredOut": 0, "duplicatesRemoved": 3100, "missingKeyItems": 0, "previouslySeen": 8500, "outputItems": 400,
  "datasets": [{ "datasetId": "aBcD1234", "itemsRead": 7000 }, { "datasetId": "eFgH5678", "itemsRead": 5000 }],
  "chargeLimitReached": false, "dedupMode": "keepFirst", "onlyNewSinceLastRun": true,
  "durationMs": 9100
}
```

When does a run fail instead of succeeding with 0 items?

- **Fails:** a dataset is missing or not readable, all input datasets are empty, the filter matched 0 items, no item has the dedup fields, or the maximum charge allows 0 items.
- **Succeeds with 0 items:** everything was already output by earlier runs ("only new items" mode). The log and summary say so.

Failed runs are never charged.

### Pricing

Pay per event: you pay per item written to the output (event `output-item`): **$0.50 per 1,000 items** on the Free and Starter plans, $0.40 on Scale and $0.30 on Business. Duplicates and filtered items are free. A flat **$0.001 per run** (event `run-start`) is charged only once the run is sure to succeed, never for a run that fails on input or access. The run respects your maximum charge per run: it stops cleanly at the limit, saves what it wrote, and reports `chargeLimitReached: true`.

### Limits

- Default memory is 1 GB. Measured peak: about 150 MB for 10k items, 270 MB for 100k, and 620 MB for 1M items with "only new items" (the worst case). Datasets beyond a few million items need more memory.
- Memory: roughly 60 bytes per unique key (measured ~53 B per key in a hash set). With "only new items" or `keepLast`, budget about twice that. 1 GB comfortably handles ~5M unique keys; raise the run memory for more.
- State for "only new items" is stored in the named key-value store `dataset-dedup-state`, in parts of 200,000 hashes per record.
- Hashes are 96-bit; an accidental collision is negligible even at hundreds of millions of keys.
- `keepLast` reads each dataset twice; do not run it on a dataset that is still being written.
- Restarts and migrations: progress is checkpointed in the run's key-value store (`DEDUP_CHECKPOINT`) after every written batch. A restarted run replays what it already delivered without pushing or charging it again. Only a crash in the instant between a push and its checkpoint can repeat that one batch (at most 1,000 items).
- Run one job per `stateKey` at a time. Concurrent runs merge their state when saving, but they do not see each other's items while running, so both may output the same new item.
- With limited permissions, the Actor cannot browse run history (`actorOrTaskId`). Pass dataset IDs instead. A named output dataset must be one this Actor created.

### FAQ

**My run failed with "not allowed to read it".** Select the dataset with the picker in the *Datasets* field, or check that it belongs to the account running the Actor.

**Can I reset "only new items"?** Use a new `stateKey`. Items output under the old key will be output once more.

**Does it change my source datasets?** No. Sources are only read.

# Actor input Schema

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

Datasets to merge, in order. Pick them here so Apify grants this Actor read access. In a webhook or integration, pass the run's defaultDatasetId.

## `datasetIdsText` (type: `array`):

Optional. Paste dataset IDs to merge, added after the ones picked above. Use this for public datasets or when calling the Actor through the API. For your private datasets, prefer the picker above so Apify grants read access. The prefilled ID is a small public example dataset.

## `actorOrTaskId` (type: `string`):

Also merge the default datasets of the last successful runs of this Actor or task, e.g. "username/my-scraper". Needs full permissions; with limited permissions, use Datasets instead.

## `lastRuns` (type: `integer`):

How many of the latest successful runs to merge when an Actor or task is given.

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

Fields whose combined value identifies an item, e.g. "url" or "address.city". Leave empty to compare whole items.

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

Keep the first or the last item for each key, in dataset order.

## `onlyNewSinceLastRun` (type: `boolean`):

Output only items whose key was not output by an earlier run with the same state key.

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

Name of the memory used by "Only new items". Use a different key per workflow. Letters, digits, "-", "\_" and ".".

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

Output only these fields (nested paths allowed). Leave empty to keep all.

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

Fields to drop from every output item.

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

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

## `filter` (type: `object`):

Keep only matching items. Operators: equals, notEquals, contains (text, case-insensitive, or list member), exists, notExists. match is "all" or "any".

## `outputDatasetName` (type: `string`):

Also store results in this named dataset (created if missing). Leave empty to use the run's default dataset.

## Actor input object example

```json
{
  "datasetIdsText": [
    "ZELVRA7VmS6LXd7hX"
  ],
  "lastRuns": 1,
  "dedupFields": [
    "url"
  ],
  "dedupMode": "keepFirst",
  "onlyNewSinceLastRun": false,
  "stateKey": "default",
  "filter": {
    "match": "all",
    "conditions": []
  }
}
```

# Actor output Schema

## `items` (type: `string`):

Merged, deduplicated items written to the default dataset (when no output dataset name is set).

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

Items read per dataset, duplicates removed, filtered, new and output counts, and whether the charge limit was reached.

# 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 = {
    "datasetIdsText": [
        "ZELVRA7VmS6LXd7hX"
    ],
    "dedupFields": [
        "url"
    ],
    "filter": {
        "match": "all",
        "conditions": []
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("black-vikings/dataset-dedup").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 = {
    "datasetIdsText": ["ZELVRA7VmS6LXd7hX"],
    "dedupFields": ["url"],
    "filter": {
        "match": "all",
        "conditions": [],
    },
}

# Run the Actor and wait for it to finish
run = client.actor("black-vikings/dataset-dedup").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 '{
  "datasetIdsText": [
    "ZELVRA7VmS6LXd7hX"
  ],
  "dedupFields": [
    "url"
  ],
  "filter": {
    "match": "all",
    "conditions": []
  }
}' |
apify call black-vikings/dataset-dedup --silent --output-dataset

```

## MCP server setup

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

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/aHk6kFq0Y7Uumrh8L/builds/rFZIPLBSARVydhsiL/openapi.json
