# Merge & Deduplicate Datasets (works with limited permissions) (`metal_spinney/dataset-merge-dedup`) Actor

Merge several Apify datasets (and public JSON files) into one and remove duplicates by any fields, with case/whitespace/URL normalization, keep first or last, only-new mode and field projection. Requests read-only access only to the datasets you pick.

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

## Pricing

Pay per usage

This Actor is paid per platform usage. The Actor is free to use, and you only pay for the Apify platform usage, which gets cheaper the higher subscription plan you have.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-usage

## 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 & Deduplicate Datasets (works with limited permissions)

Merge several **Apify datasets** (for example the outputs of many scraper runs) and public JSON files into **one clean dataset**, and **remove duplicates** by the fields you choose. Works under Apify's **limited permissions** and on accounts with **restricted resource access**: the dataset picker asks for **read-only access to just the datasets you select**, so runs don't fail with permission errors.

No scraping happens. The Actor only reads the datasets / JSON URLs you give it and writes the result to its own default dataset.

### Features

- **Merge** any number of datasets (picker or IDs via API) plus optional **public JSON / JSON Lines URLs**.
- **Dedup by fields**: one field (`url`) or a combination (`name` + `address`), **nested paths** (`location.city`, `images.0`), objects/arrays compared by value. Or dedup by **whole item**, or **merge only**.
- **Normalization** before comparing: ignore letter case, extra whitespace, and URL noise (http/https, `www.`, trailing slash, `#fragment`, `utm_*`/`fbclid`/`gclid`).
- **Keep first or last** occurrence (list datasets oldest → newest and keep last to get the freshest copy).
- **Only new items**: exclude anything whose key already exists in other datasets (e.g. last week's output) for incremental pipelines.
- **Output** unique items, only the duplicates (audit), or just a duplicate-count summary.
- **Field projection**: output only chosen fields, or drop fields; optional `__source` field with the origin dataset.
- `SUMMARY` record: items loaded per source, unique, duplicates, excluded, output, errors.
- Clear per-source errors: an unreadable or missing dataset is skipped with a message, the rest still merges.

### Input example

```json
{
  "datasetIds": ["<datasetIdRun1>", "<datasetIdRun2>", "<datasetIdRun3>"],
  "dedupFields": ["url"],
  "normalizeUrls": true,
  "keep": "last",
  "excludeItemsInDatasetIds": ["<lastWeeksMergedDatasetId>"],
  "outputFields": ["url", "title", "price"]
}
```

### Performance (local test, 28 Oct 2026)

- 92,820 items → 4,641 unique (dedup on 3 fields) in 3.0 s.
- 12,345 items read through the paginated dataset API (with one simulated HTTP 429 retry, a 403 and a 404 source skipped) → 10,000 unique in 3.5 s.
- 17 local test runs: 15 succeeded, 2 invalid inputs (empty, all sources missing) failed by design with a clear message. 10 outputs (merge, keep-last, only-new, duplicates-only, summary, projection + case-folding, whole-item, nested-path, 92k scale, URL normalization + nulls) were cross-checked against an independent reference implementation and all matched. See `samples/`.

### Limits (honest list)

- Dedup keys for every unique item are kept in memory (~100 bytes each): fine for tens of millions of items at 4 GB; `keep: last` also keeps the unique items themselves in memory.
- Output always goes to this run's default dataset (no writing into your other datasets, so no write permission is requested). Use Apify integrations or the API to copy it onward.
- Named datasets: pass them with the picker, or as `username~dataset-name` via API.
- No JavaScript transform functions (keeps runs safe and predictable); use field projection or post-process downstream.

### Pricing

Free to use for now: you only pay Apify's normal platform usage for the run. Pay-per-event pricing may be added later, with Apify's standard advance notice.

*By Open Registry Data.*

# Actor input Schema

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

Pick one or more datasets (from your runs or saved datasets). Via API pass dataset IDs (or 'username~dataset-name'). Read-only access is requested only for the datasets you select, so this works under limited permissions and on accounts with restricted resource access.

## `jsonUrls` (type: `array`):

Also merge any public JSON / JSON Lines file: a JSON array of objects, an object with an 'items' or 'data' array, or JSONL. Useful for public Apify dataset export links or files from other tools.

## `dedupBy` (type: `string`):

fields = items with the same values in the chosen fields are duplicates; fullItem = only exact duplicate items; none = just merge.

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

Field names whose combined values must be unique, e.g. 'url', or 'name' + 'address'. Nested paths with dots work ('location.city', 'images.0'). Objects/arrays are compared by value.

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

'ACME Inc' and 'acme inc' count as the same value.

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

Trim and collapse whitespace in text values before comparing.

## `normalizeUrls` (type: `boolean`):

Treat http/https, www., trailing slash, #fragment and utm\_/fbclid/gclid parameters as the same URL.

## `nullAsUnique` (type: `boolean`):

If on, items missing a dedup field (null/empty) are never treated as duplicates. If off, all items with the field missing count as one value.

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

first = first occurrence in source order (streaming, low memory); last = last occurrence, e.g. the newest run if you list datasets oldest to newest (holds unique items in memory).

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

unique = merged, deduplicated items; duplicates = only the removed duplicates (for auditing); summary = no items, only duplicate counts in the SUMMARY record (costs nothing per item).

## `excludeItemsInDatasetIds` (type: `array`):

Items whose dedup key already exists in these datasets (e.g. last week's merged output) are dropped, so you get only new items. Read-only access.

## `outputFields` (type: `array`):

Field projection. Leave empty to keep whole items. Nested paths ('address.city') are output as flat 'address.city' keys.

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

Fields to drop from output items (nested paths allowed).

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

Add '\_\_source' with the dataset ID / URL each item came from.

## `cleanItems` (type: `boolean`):

Skip empty items and hidden '#' fields (Apify 'clean' format) when reading datasets.

## `maxItems` (type: `integer`):

Hard cap on output items (and cost). 0 = no limit.

## Actor input object example

```json
{
  "jsonUrls": [
    "https://jsonplaceholder.typicode.com/posts",
    "https://jsonplaceholder.typicode.com/posts?userId=1"
  ],
  "dedupBy": "fields",
  "dedupFields": [
    "id"
  ],
  "caseInsensitive": false,
  "trimWhitespace": true,
  "normalizeUrls": false,
  "nullAsUnique": false,
  "keep": "first",
  "output": "unique",
  "addSourceField": false,
  "cleanItems": true,
  "maxItems": 0
}
```

# Actor output Schema

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

No description

## `resultsView` (type: `string`):

No description

## `summary` (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 = {
    "jsonUrls": [
        "https://jsonplaceholder.typicode.com/posts",
        "https://jsonplaceholder.typicode.com/posts?userId=1"
    ],
    "dedupBy": "fields",
    "dedupFields": [
        "id"
    ]
};

// Run the Actor and wait for it to finish
const run = await client.actor("metal_spinney/dataset-merge-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 = {
    "jsonUrls": [
        "https://jsonplaceholder.typicode.com/posts",
        "https://jsonplaceholder.typicode.com/posts?userId=1",
    ],
    "dedupBy": "fields",
    "dedupFields": ["id"],
}

# Run the Actor and wait for it to finish
run = client.actor("metal_spinney/dataset-merge-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 '{
  "jsonUrls": [
    "https://jsonplaceholder.typicode.com/posts",
    "https://jsonplaceholder.typicode.com/posts?userId=1"
  ],
  "dedupBy": "fields",
  "dedupFields": [
    "id"
  ]
}' |
apify call metal_spinney/dataset-merge-dedup --silent --output-dataset

```

## MCP server setup

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