> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Replace all objects

> Replace all records from your index with a new set of records.

export const Legacy = ({title, href}) => {
  return <Note>

    This page documents an earlier version of the API client.
    For the latest version, see <a href={href}>{title}</a>.

    </Note>;
};

<Legacy title="Replace all records" href="/doc/libraries/sdk/methods/search/replace-all-objects" />

**Required ACL:** `addObject`

This method lets you replace all records in your index without downtime.
It performs these operations:

1. Copy settings, synonyms, and rules from your original index to a temporary index.
2. Add your new records to the temporary index.
3. Replace your original index with the temporary index.

* Use the [`safe`](#param-safe) parameter to ensure that these (asynchronous) operations are performed in sequence.

* If there's an error during one of these steps, the temporary index won't be deleted.

* This operation is [rate-limited](/doc/guides/scaling/algolia-service-limits#application-record-and-index-limits).

* This method creates a temporary index: **your record count is temporarily doubled.**
  Algolia doesn't count the three days with the highest number of records towards your monthly usage.

* If you're on a legacy plan (before July 2020), this method counts two operations towards your usage (in addition to the number of records):
  [`copySettings`](/doc/libraries/sdk/v1/methods/copy-settings) and [`moveIndex`](/doc/libraries/sdk/v1/methods/move-index).

* The API key you use for this operation must have access to the index `YourIndex` and the temporary index `YourIndex_tmp`.

## Examples

### Replace all records

<CodeGroup>
  ```cs C# theme={"system"}
  var client = new SearchClient("YourApplicationID", "YourWriteAPIKey");
  var index = client.InitIndex("YourIndexName");

  var objects = /* Fetch your objects */;
  index.ReplaceAllObjects(objects);
  ```

  ```go Go theme={"system"}
  package main

  import "github.com/algolia/algoliasearch-client-go/v3/algolia/search"

  func main() {
      client := search.NewClient("YourApplicationID", "YourWriteAPIKey")
      index := client.InitIndex("YourIndexName")

      objects := []Object{ /* Fetch your objects */ }

      res, err := index.ReplaceAllObjects(objects)
  }
  ```

  ```java Java theme={"system"}
  SearchClient client =
  DefaultSearchClient.create("YourApplicationID", "YourWriteAPIKey");

  SearchIndex<Contact> index = client.initIndex("YourIndexName", Contact.class);

  // Fetch your objects
  List<Contact> objects = new ArrayList<>();

  // Sync version
  index.replaceAllObjects(objects);

  // Async version
  index.replaceAllObjectsAsync(objects);
  ```

  ```js JavaScript theme={"system"}
  const client = algoliasearch('YourApplicationID', 'YourWriteAPIKey');

  const objects = []; // Fetch your objects

  const index = client.initIndex('YourIndexName');

  index.replaceAllObjects(objects).then(({ objectIDs }) => {
    console.log(objectIDs);
  });
  ```

  ```kotlin Kotlin theme={"system"}
  // With JsonObject
  val json = listOf(
      json {
          "firstname" to "Jimmie"
          "lastname" to "Barninger"
      },
      json {
          "firstname" to "Warren"
          "lastname" to "Speach"
      }
  )

  index.replaceAllObjects(json)

  // With serializable class
  @Serializable
  data class Contact(val firstname: String, val lastname: String)

  val contacts = listOf(
      Contact("Jimmie", "Barninger"),
      Contact("Warren", "Speach")
  )

  index.replaceAllObjects(Contact.serializer(), contacts)
  ```

  ```php PHP theme={"system"}
  $client = Algolia\AlgoliaSearch\SearchClient::create(
    'YourApplicationID',
    'YourWriteAPIKey'
  );

  $objects = /* Fetch your objects */;

  $index = $client->initIndex('YourIndexName');
  $index->replaceAllObjects($objects);
  ```

  ```python Python theme={"system"}
  client = SearchClient.create("YourApplicationID", "YourWriteAPIKey")

  objects = [] # Fetch your objects

  index = client.init_index("YourIndexName")
  index.replace_all_objects(objects)
  ```

  ```ruby Ruby theme={"system"}
  client = Algolia::Search::Client.create('YourApplicationID', 'YourWriteAPIKey')

  objects = [
    # your new objects
  ]

  index = client.init_index('YourIndexName')
  index.replace_all_objects(objects)
  ```

  ```scala Scala theme={"system"}
  import algolia.AlgoliaClient
  import algolia.AlgoliaDsl._
  import algolia.responses._

  import scala.concurrent.duration._
  import scala.concurrent.duration.FiniteDuration
  import scala.concurrent.{Await, ExecutionContext, ExecutionContextExecutor, Future}

  case class MyCaseClass(objectID: String, /* ... */) extends ObjectID

  object Main {

    def main(args: Array[String]): Unit = {

      implicit val ec: ExecutionContextExecutor = ExecutionContext.global
      implicit val awaitDuration: FiniteDuration = 10 seconds

      val client = new AlgoliaClient("YourApplicationID", "YourWriteAPIKey")
      val tmpIndexName = "atomic_reindex_tmp"
      val indexName = "atomic_reindex"

      // 1. Copy the settings, synonyms and rules (but not the records)
      // of the target index into the temporary index
      val copyTask = Await.result(
        client.execute(copy index indexName to tmpIndexName scope Seq("settings", "synonyms", "rules")),
        awaitDuration
      )
      client.execute(waitFor task copyTask from indexName)

      // 2. Fetch your data and push it to the temporary index
      val objects: Seq[MyCaseClass] = Seq(/* ... */)

      // Here is where you push your data to the temporary index
      val batchTasks = Await.result(
        Future.sequence(objects.grouped(1000).map(batch => client.execute(index into tmpIndexName objects batch))),
        awaitDuration
      )

      Await.result(
        Future.sequence(batchTasks.map(task => client.execute(waitFor task task from tmpIndexName))),
        awaitDuration
      )

      // 3. Move the temporary index to the target index
      client.execute(move index tmpIndexName to indexName)
    }

  }
  ```

  ```swift Swift theme={"system"}
  struct Contact: Encodable {
    let objectID: ObjectID
    let firstname: String
    let lastname: String
  }

  let client = SearchClient(appID: "YourApplicationID", apiKey: "YourWriteAPIKey")
  let index = client.index(withName: "YourIndexName")

  let objects: [Contact]! = [/*Fetch your objects*/]

  index.replaceAllObjects(with: objects) { result in
    if case .success(let response) = result {
      print("Response: \(response)")
    }
  }
  ```
</CodeGroup>

### Replace all records and wait for operations

<CodeGroup>
  ```cs C# theme={"system"}
  var client = new SearchClient("YourApplicationID", "YourWriteAPIKey");
  var index = client.InitIndex("YourIndexName");

  var objects = /* Fetch your objects */;
  index.ReplaceAllObjects(objects, true);
  ```

  ```go Go theme={"system"}
  package main

  import (
    "github.com/algolia/algoliasearch-client-go/v3/algolia/opt"
    "github.com/algolia/algoliasearch-client-go/v3/algolia/search"
  )

  func main() {
      client := search.NewClient("YourApplicationID", "YourWriteAPIKey")
      index := client.InitIndex("YourIndexName")

      objects := []Object{ /* Fetch your objects */ }

      res, err := index.ReplaceAllObjects(objects, opt.Safe(true))
  }
  ```

  ```java Java theme={"system"}
  SearchClient client =
  DefaultSearchClient.create("YourApplicationID", "YourWriteAPIKey");

  SearchIndex<Contact> index = client.initIndex("YourIndexName", Contact.class);

  // Fetch your objects
  List<Contact> objects = new ArrayList<>();

  index.replaceAllObjects(objects, true);
  ```

  ```js JavaScript theme={"system"}
  const client = algoliasearch('YourApplicationID', 'YourWriteAPIKey');

  const objects = []; // Fetch your objects

  const index = client.initIndex('YourIndexName');

  index.replaceAllObjects(objects, { safe: true }).then(({ objectIDs }) => {
    console.log(objectIDs);
  });
  ```

  ```kotlin Kotlin theme={"system"}
  client.apply {
    val json = listOf(
        json {
            "firstname" to "Jimmie"
            "lastname" to "Barninger"
        },
        json {
            "firstname" to "Warren"
            "lastname" to "Speach"
        }
    )

    index.replaceAllObjects(json).waitAll()
  }
  ```

  ```php PHP theme={"system"}
  $client = Algolia\AlgoliaSearch\SearchClient::create(
    'YourApplicationID',
    'YourWriteAPIKey'
  );

  $objects = /* Fetch your objects */;

  $index = $client->initIndex('YourIndexName');
  $index->replaceAllObjects($objects, [
    'safe' => true,
  ]);
  ```

  ```python Python theme={"system"}
  client = SearchClient.create('YourApplicationID', 'YourWriteAPIKey')

  objects = [] # Fetch your objects

  index = client.init_index('YourIndexName')
  index.replace_all_objects(objects, {
      'safe': True
  })
  ```

  ```ruby Ruby theme={"system"}
  client = Algolia::Search::Client.create('YourApplicationID', 'YourWriteAPIKey')

  objects = [
    # your new objects
  ]

  index = client.init_index('YourIndexName')
  index.replace_all_objects(objects, { safe: true })
  # or: index.replace_all_objects!(objects)
  ```

  ```scala Scala theme={"system"}
  import algolia.AlgoliaClient
  import algolia.AlgoliaDsl._
  import algolia.responses._

  import scala.concurrent.duration._
  import scala.concurrent.duration.FiniteDuration
  import scala.concurrent.{Await, ExecutionContext, ExecutionContextExecutor, Future}

  case class MyCaseClass(objectID: String, /* ... */) extends ObjectID

  object Main {

    def main(args: Array[String]): Unit = {

      implicit val ec: ExecutionContextExecutor = ExecutionContext.global
      implicit val awaitDuration: FiniteDuration = 10 seconds

      val client = new AlgoliaClient("YourApplicationID", "YourWriteAPIKey")
      val tmpIndexName = "atomic_reindex_tmp"
      val indexName = "atomic_reindex"

      // 1. Copy the settings, synonyms and rules (but not the records)
      // of the target index into the temporary index
      val copyTask = Await.result(
        client.execute(copy index indexName to tmpIndexName scope Seq("settings", "synonyms", "rules")),
        awaitDuration
      )
      client.execute(waitFor task copyTask from indexName)

      // 2. Fetch your data and push it to the temporary index
      val objects: Seq[MyCaseClass] = Seq(/* ... */)

      // Here is where you push your data to the temporary index
      val batchTasks = Await.result(
        Future.sequence(objects.grouped(1000).map(batch => client.execute(index into tmpIndexName objects batch))),
        awaitDuration
      )

      Await.result(
        Future.sequence(batchTasks.map(task => client.execute(waitFor task task from tmpIndexName))),
        awaitDuration
      )

      // 3. Move the temporary index to the target index
      client.execute(move index tmpIndexName to indexName)
    }

  }
  ```

  ```swift Swift theme={"system"}
  struct Contact: Encodable {
    let objectID: ObjectID
    let firstname: String
    let lastname: String
  }

  let client = SearchClient(appID: "YourApplicationID", apiKey: "YourWriteAPIKey")
  let index = client.index(withName: "YourIndexName")

  let objects: [Contact]! = [/*Fetch your objects*/]

  index.replaceAllObjects(with: objects, safe: true) { result in
    if case .success(let response) = result {
      print("Response: \(response)")
    }
  }
  ```
</CodeGroup>

## Parameters

<ParamField body="objects" type="list" required>
  List of records.

  **Python:** Use an [iterator](https://wiki.python.org/moin/Iterator) instead of a list to prevent memory issues,
  especially if you want to replace many records.
</ParamField>

<ParamField body="requestOptions" type="object">
  A mapping of request options to send along with the query.
</ParamField>

<ParamField body="safe" type="boolean" default={false}>
  If true, wait after each step before continuing.
</ParamField>
