# Firestore Import (`apify/firestore-import`) Actor

Seamlessly import data from Apify datasets into Firebase Firestore database. This integration allows full control over document IDs, conflict resolution (overwrite, merge, skip), and data transformation using a custom JavaScript function.

- **URL**: https://apify.com/apify/firestore-import.md
- **Developed by:** [Apify](https://apify.com/apify) (Apify)
- **Categories:** Automation, Integrations, Open source
- **Features:** Full permissions
- **Stats:** 15 total users, 2 monthly users, 83.9% runs succeeded, 5 bookmarks
- **User rating**: 5.00 out of 5 stars

## 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

## Firestore Import

The Firestore Import is Apify integration [Actor](https://docs.apify.com/platform/actors#what-is-an-actor) that import data into [Firebase Firestore](https://firebase.google.com/docs/firestore)
(NoSQL cloud database build on Google Cloud infrastructure) from [Apify dataset](https://docs.apify.com/platform/storage/dataset).
It allows you to configure various options, such as the target collection, handling conflicts in data,
and transforming the dataset item before importing it into Firestore.

### Features

The Firestore Import Actor takes a dataset, applies transformations, and imports the data into a Firestore database.
This Actor is highly customizable, you can control how the data are imported such as:

- Selecting Firestore database and collection.
- Automatically generating document IDs or using a field from the dataset for the document ID.
- Handling document conflicts by either overwriting, merging, or skipping documents with existing ID.
- Transforming data before it gets imported using a customizable JavaScript function.
- One dataset item can lead to multiple Firestore inserts/updates.
- Each document can have its own configuration, such as a custom collection or document ID.

### Input

The actor requires several input fields to work correctly. Below is a detailed description of each input field:

| **Field Name**               | **Type**                                          | **Description**                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
|------------------------------|---------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| `serviceAccountKey`          | `string` (secret, *required*)                     | Service account key in JSON format.<br/>You can get it from *Firebase Console* -> *Project Settings* -> *Service accounts* -> *Generate new private key*.<br/><br/>Paste the whole JSON string here, don't worry this is [secret input](https://docs.apify.com/platform/actors/development/actor-definition/input-schema/secret-input) which store the value in encrypted form.                                                                                                          |
| `datasetId`                  | `string` (*required*)                             | ID of the Apify dataset to import data from.                                                                                                                                                                                                                                                                                                                                                                                                                                             |
| `collection`                 | `string` (*required*)                             | Firestore collection to import data to. If it doesn't exist, it will be created.<br/><br/>*Note:* you can customize the collection for each record by using the `transformFunction` input. This can be useful when you want to import data to sub-collections.                                                                                                                                                                                                                           |
| `databaseName`               | `string` (*optional*)                             | Name of the Firestore database.<br/>If not provided, the default database (`"(default)"`) will be used.                                                                                                                                                                                                                                                                                                                                                                                  |
| `idField`                    | `string` (*optional*)                             | Field in the dataset item that will be used as a Firestore document ID. It must be `string` or `number`.<br/>If not provided, all documents will be created with a random ID generated by Firestore (it means that value of `documentConflictResolution` is ignored in that case).<br/><br/>This is useful when you want to update existing documents in Firestore.<br/><br/>*Note:* you can customize the ID for each document independently using the `transformFunction` input field. |
| `documentConflictResolution` | `enum`: `overwrite`, `merge`, `skip` (*required*) | How to handle conflicts when importing data to Firestore:<br>  - ***overwrite***: replace existing Firestore documents with the same ID.<br>  - ***merge***: merge data from the dataset items with existing Firestore documents.<br>  - ***skip***: documents with existing IDs will be skipped.<br/><br/>⚠️ Please note that the *skip* resolution has really bad performance on large scale and can't use batch writes (it makes request to Firestore for each document separately).  |
| `transformFunction`          | `string` (javascript, *optional*)                 | Javascript function that transforms each item from the dataset before importing it to Firestore.<br/><br/>The function must return an object (or array of objects) with the `data` key that contains the transformed record and other optional fields. See examples below.                                                                                                                                                                                                               |
| `batchSize`                  | `number` (*optional*)                             | Number of items to import in a single batch. Lower values are safer but slower, see [Firestore limits](https://firebase.google.com/docs/firestore/quotas) (10 MiB batch write). Please note that *skip* conflict resolution does not use batch writes and will always import one item at a time.<br/>Defaults to `500`.                                                                                                                                                                  |

### Transformation Function

The option `transformFunction` input field allows you to transform each dataset item before importing it to Firestore.
The field accepts a JavaScript function that takes one dataset item as a parameter and returns an object (or array of objects) with the following keys:

- `data` (required): transformed document that will be imported to Firestore.
- `id` (optional): custom document ID. If not provided, the `idField` input field will be used to resolve document id or if not provided the document will be created with a random ID generated by Firestore.
- `collection` (optional): custom collection name. If not provided, the `collection` input field will be used.
- `documentConflictResolution` (optional): custom conflict resolution for the document. If not provided, the `documentConflictResolution` input field will be used.

```javascript
(item) => {
    return {
        data: item,                           // transformed document
        id: item.id,                          // custom document ID
        collection: "customCollection",       // custom collection name
        documentConflictResolution: "merge",  // custom conflict resolution
    };
}
```

#### Examples

1. **Simple transformation function:**

   The function below increments the value of the `oldField` by 1 and removes the `unused` field from the dataset item.

   ```javascript
   (item) => {
       item.newField = item.oldField + 1;
       delete item.unused;
       return { data: item };
   }
   ```

2. **Nested objects:**

   The function below transforms the dataset item into a Firestore document with nested objects. It updates the `subdocument.field` field and overwrites the whole `author` sub-document.

   ```javascript
   (item) => {
       return {
           data: {
               title: item.title,
               "subdocument.field": item.name,  // update single field of subdocument
               author: item.author              // overwrite whole subdocument
           },
       };
   }
   ```

3. **Field value functions:**

   The function below demonstrates how to use Firestore `FieldValue` [functions](https://firebase.google.com/docs/reference/node/firebase.firestore.FieldValue).
   It adds new IDs to the existing `ids` array, removes values from the `values` array, increments the `count` field, and deletes the `old` field.

   ```javascript
   (item) => {
       return {
           data: {
               ids: FieldValue.arrayUnion(item.ids),         // add new ids to existing ids array
               values: FieldValue.arrayRemove(item.values),  // remove new values from existing array
               count: FieldValue.increment(item.count),      // increment existing count field by provided value
               old: FieldValue.delete(),                     // removes field
           },
       };
   }
   ```

4. **Data types:**

   The function below demonstrates how to create Firestore data types such as `Timestamp`, `Vector`, `GeoPoint`, and `DocumentReference`.

   ```javascript
   (item) => {
       return {
           data: {
               updatedAt: Timestamp.fromDate(Date.parse(item.date)),          // create Timestamp data type
               vector: FieldValue.VectorValue(item.values),                   // create vector data type
               position: GeoPoint(item.lat, item.lon),                        // create geopoint data type
               reference: DocumentReference("collection", "referenceDocId"),  // create reference type
           },
       };
   }
   ```

5. **Subcollection:**

   The function below demonstrates how to import data to sub-collections.
   It returns an array where the first item is the main document and other items are documents for sub-collection.

   ```javascript
   (item) => {
       const subDocuments = item.items.map((subItem) => ({
           id: subItem.id,
           collection: `records/${item.customId}/items`,
           documentConflictResolution: "skip",
           data: {
               weight: subItem.weight,
               length: subItem.length,
               name: subItem.name,
           },
       }));

       return [
           {
               id: item.customId,
               collection: "records",
               documentConflictResolution: "merge",
               data: {
                   title: item.title,
                   description: item.description,
               },
           },
           ...subDocuments,
       ];
   }
   ```

### Output

The Actor outputs statistics about the import to Key-Value store key `Statistics` with the following structure:

- `imported`: total number of processed Firestore documents (either created, updated or skipped).
- `skipped`: number of skipped Firestore documents.
- `overwritten`: number of overwritten Firestore documents.
- `merged`: number of merged Firestore documents.
- `created`: number of created Firestore documents (counts written document if `documentConflictResolution` is `skip`).
- `failed`: number of failed writes to Firestore documents.
- `itemsProcessed`: total number of processed dataset items (including failed items).
- `itemsFailed`: number of failed dataset items.
- `executionTimeMs`: time in milliseconds it took to import the data.
- `startTime`: timestamp when the import started.
- `endTime`: timestamp when the import ended.

```json
{
  "imported": 59278,
  "skipped": 0,
  "overwritten": 0,
  "merged": 59278,
  "created": 0,
  "failed": 0,
  "itemsProcessed": 1136,
  "itemsFailed": 0,
  "executionTimeMs": 19725,
  "startTime": "2025-02-26T17:56:22.652Z",
  "endTime": "2025-02-26T17:56:42.377Z"
}
```

# Actor input Schema

## `serviceAccountKey` (type: `string`):

Service account key in JSON format. You can get it from *Firebase Console* -> *Project Settings* -> *Service accounts* -> *Generate new private key*. Paste the whole JSON string here.

## `datasetId` (type: `string`):

ID of the Apify dataset to import data from.

## `collection` (type: `string`):

Firestore collection to import data to. If it doesn't exist, it will be created. Note: you can customize the collection for each document using the `transformFunction` input. This can be useful when you want to import data to sub-collections.

## `databaseName` (type: `string`):

Name of the Firestore database. If not provided, the default database (`"(default)"`) will be used.

## `idField` (type: `string`):

Field in the dataset item that will be used as a Firestore document ID. If not provided, all documents will be created with a random ID generated by Firestore (it means that value of `documentConflictResolution` is ignored in that case). This is useful when you want to update existing documents in Firestore. Note: you can customize the ID for each document independently using the `transformFunction` input field.

## `documentConflictResolution` (type: `string`):

How to handle conflicts when importing data to Firestore:

- *overwrite*: replace existing Firestore documents with the same ID.
- *merge*: merge data from the dataset items with existing Firestore documents.
- *skip*: documents with existing IDs will be skipped.
  ⚠️ Please note that the *skip* resolution has really bad performance on large scale and can't use batch writes.

## `transformFunction` (type: `string`):

Function that transforms each item from the dataset before importing it to Firestore. The function must return an object (or array of objects) with the `data` key that contains the transformed document and other optional fields. See README for more details and examples.

## `batchSize` (type: `integer`):

Number of items to import in a single batch. Lower values are safer but slower, see [Firestore limits](https://firebase.google.com/docs/firestore/quotas) (10 MiB batch write). Please note that *skip* conflict resolution does not use batch writes and will always import one item at a time.

## Actor input object example

```json
{
  "databaseName": "(default)",
  "documentConflictResolution": "overwrite",
  "transformFunction": "(data) => {\n    return { data };\n}",
  "batchSize": 500
}
```

# 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 = {
    "databaseName": "(default)",
    "documentConflictResolution": "overwrite",
    "transformFunction": (data) => {
        return { data };
    }
};

// Run the Actor and wait for it to finish
const run = await client.actor("apify/firestore-import").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 = {
    "databaseName": "(default)",
    "documentConflictResolution": "overwrite",
    "transformFunction": """(data) => {
    return { data };
}""",
}

# Run the Actor and wait for it to finish
run = client.actor("apify/firestore-import").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 '{
  "databaseName": "(default)",
  "documentConflictResolution": "overwrite",
  "transformFunction": "(data) => {\\n    return { data };\\n}"
}' |
apify call apify/firestore-import --silent --output-dataset

```

## MCP server setup

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

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/Z2B65CMPn2aEXnfFk/builds/HKRKFVHz930F7S76y/openapi.json
