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

# Delete indices

> Delete an index, including all its settings, records, and links to replicas.

export const Records = () => <Tooltip tip="A record is a searchable object in an Algolia index. Each record consists of named attributes." cta="Algolia records" href="/doc/guides/sending-and-managing-data/prepare-your-data#algolia-records">
    records
  </Tooltip>;

export const Index = () => <Tooltip tip="An Algolia index is a searchable dataset that consists of records and configuration settings. These settings define how the records are searched and ranked.">
    index
  </Tooltip>;

export const Application = () => <Tooltip tip="An Algolia application is a self-contained environment with its own indices, configuration, and API keys. Applications don't share data or settings with each other.">
    application
  </Tooltip>;

export const AlgoliaSearch = () => <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 80 80" width="20" height="20" className="inline" fill="none" role="presentation" ariaLabel="Algolia Search">
    <circle cx="40" cy="32" r="28" fill="#5468FF"></circle>
    <rect x="30" y="22" width="20" height="20" rx="10" fill="#fff"></rect>
    <path d="M43 63.5 54.5 60l6 17h-12L43 63.5Z" fill="#36395A"></path>
  </svg>;

You can either delete the entire <Index /> or only its <Records />:

* [Delete everything](#delete-indices): removes the index, including records, rules, settings, and synonyms.
* [Delete only the records](#clear-indices): keeps rules, settings, and synonyms.

Before you delete an index,
create a backup by [exporting your index](/doc/guides/sending-and-managing-data/manage-indices-and-apps/manage-indices/how-to/export-import-indices).

## Delete indices

Deleting an index removes all records, rules, settings, and synonyms from your Algolia <Application />.
Algolia retains the [associated analytics data](/doc/guides/sending-and-managing-data/manage-indices-and-apps/manage-indices/concepts/indices-analytics) even after index deletion.

<Warning>
  If you delete an index by mistake,
  the [Algolia support](https://support.algolia.com/hc/en-us/requests/new) team might be able to restore it,
  but recovery isn't guaranteed.
  The [Enterprise pricing plan add-on](https://dashboard.algolia.com/info/plans/).
</Warning>

### Indices with replicas

You can't delete a replica index directly.
First, [unlink it](/doc/guides/managing-results/refine-results/sorting/how-to/deleting-replicas) from its primary index.

If you delete a primary index, its replica indices become regular, independent indices.

<Note>
  To delete replica indices directly,
  use the Algolia CLI [`algolia indices delete`](/doc/tools/cli/commands/indices/delete) command:
  it automatically un-links them.
</Note>

### Delete indices in the Algolia dashboard

1. Go to the [Algolia dashboard](https://dashboard.algolia.com/explorer/browse) and select your Algolia application.
2. On the left sidebar, select <AlgoliaSearch /> **Search**.
3. Select your Algolia index.
4. Select **Manage index > Delete**.
5. Type `DELETE` to confirm and click **Delete**.

### Delete indices with the API

To run the code examples on this page, [install the latest API client](/doc/libraries/sdk/install).

Delete an index with either of the following:

* Algolia CLI: [`algolia indices delete`](/doc/tools/cli/commands/indices/delete) (deletes several indices and automatically deletes their replicas)
* API clients: [`deleteIndex`](/doc/libraries/sdk/v1/methods/delete-index)

<CodeGroup>
  ```cs C# theme={"system"}
  var response = await client.DeleteIndexAsync("INDEX_NAME");
  ```

  ```dart Dart theme={"system"}
  final response = await client.deleteIndex(
    indexName: "INDEX_NAME",
  );
  ```

  ```go Go theme={"system"}
  response, err := client.DeleteIndex(client.NewApiDeleteIndexRequest(
    "INDEX_NAME"))
  if err != nil {
    // handle the eventual error
    panic(err)
  }
  ```

  ```java Java theme={"system"}
  DeletedAtResponse response = client.deleteIndex("INDEX_NAME");
  ```

  ```js JavaScript theme={"system"}
  const response = await client.deleteIndex({ indexName: 'theIndexName' });
  ```

  ```kotlin Kotlin theme={"system"}
  var response = client.deleteIndex(indexName = "INDEX_NAME")
  ```

  ```php PHP theme={"system"}
  $response = $client->deleteIndex(
      'INDEX_NAME',
  );
  ```

  ```python Python theme={"system"}
  response = client.delete_index(
      index_name="INDEX_NAME",
  )
  ```

  ```ruby Ruby theme={"system"}
  response = client.delete_index("INDEX_NAME")
  ```

  ```scala Scala theme={"system"}
  val response = Await.result(
    client.deleteIndex(
      indexName = "INDEX_NAME"
    ),
    Duration(100, "sec")
  )
  ```

  ```swift Swift theme={"system"}
  let response = try await client.deleteIndex(indexName: "INDEX_NAME")
  ```
</CodeGroup>

#### Delete multiple indices

To delete more than one index:

1. Use [`listIndices`](/doc/libraries/sdk/v1/methods/list-indices) (API client)
2. Use [`multipleBatch`](/doc/libraries/sdk/v1/methods/batch) to delete several indices with a single request.

To delete replica indices, you must first [delete their primary indices](#indices-with-replicas).

<CodeGroup>
  ```cs C# theme={"system"}
  namespace Algolia;

  using System;
  using System.Collections.Generic;
  using System.Net.Http;
  using System.Text.Json;
  using Algolia.Search.Clients;
  using Algolia.Search.Http;
  using Algolia.Search.Models.Search;

  class DeleteMultipleIndices
  {
    async Task Main(string[] args)
    {
      // You need an API key with `deleteIndex`
      var client = new SearchClient(new SearchConfig("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY"));

      // List all indices
      var indices = await client.ListIndicesAsync();

      // Primary indices don't have a `primary` key
      var primaryIndices = indices.Items.Where(item => item.Primary == null).ToList();
      var replicaIndices = indices.Items.Where(item => item.Primary != null).ToList();

      // Delete primary indices first
      if (primaryIndices.Count > 0)
      {
        var requests = primaryIndices
          .Select(index => new MultipleBatchRequest(Search.Models.Search.Action.Delete, index.Name))
          .ToList();
        await client.MultipleBatchAsync(new BatchParams { Requests = requests });
        Console.WriteLine("Deleted primary indices.");
      }

      // Now, delete replica indices
      if (replicaIndices.Count > 0)
      {
        var requests = replicaIndices
          .Select(index => new MultipleBatchRequest(Search.Models.Search.Action.Delete, index.Name))
          .ToList();
        await client.MultipleBatchAsync(new BatchParams { Requests = requests });
        Console.WriteLine("Deleted replica indices.");
      }
    }
  }

  ```

  ```dart Dart theme={"system"}
  import 'package:algolia_client_search/algolia_client_search.dart';

  void deleteMultipleIndices() async {
    // You need an API key with `deleteIndex`
    final client =
        SearchClient(appId: 'ALGOLIA_APPLICATION_ID', apiKey: 'ALGOLIA_API_KEY');

    // List all indices
    final indices = await client.listIndices();

    // Primary indices don't have a `primary` key
    final primaryIndices =
        indices.items.where((element) => element.primary == null).toList();
    final replicaIndices =
        indices.items.where((element) => element.primary != null).toList();

    // Delete primary indices first
    if (primaryIndices.isNotEmpty) {
      final List<MultipleBatchRequest> requests = primaryIndices
          .map((element) => MultipleBatchRequest(
              action: Action.delete, indexName: element.name))
          .toList();
      await client.multipleBatch(
        batchParams: BatchParams(
          requests: requests,
        ),
      );
      print("Deleted primary indices.");
    }

    // Now, delete replica indices
    if (replicaIndices.isNotEmpty) {
      final List<MultipleBatchRequest> requests = replicaIndices
          .map((element) => MultipleBatchRequest(
              action: Action.delete, indexName: element.name))
          .toList();
      await client.multipleBatch(
        batchParams: BatchParams(
          requests: requests,
        ),
      );
      print("Deleted replica indices.");
    }
  }

  ```

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

  import (
  	"fmt"

  	"github.com/algolia/algoliasearch-client-go/v4/algolia/search"
  )

  func deleteMultipleIndices() {
  	// You need an API key with `deleteIndex`
  	client, err := search.NewClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
  	if err != nil {
  		// The client can fail to initialize if you pass an invalid parameter.
  		panic(err)
  	}

  	// List all indices
  	indices, err := client.ListIndices(client.NewApiListIndicesRequest())
  	if err != nil {
  		panic(err)
  	}

  	// Primary indices don't have a `primary` key
  	primaryIndices := make([]search.FetchedIndex, 0, len(indices.Items))
  	replicaIndices := make([]search.FetchedIndex, 0, len(indices.Items))

  	for _, index := range indices.Items {
  		if index.Primary == nil {
  			primaryIndices = append(primaryIndices, index)
  		} else {
  			replicaIndices = append(replicaIndices, index)
  		}
  	}

  	// Delete primary indices first
  	if len(primaryIndices) > 0 {
  		requests := make([]search.MultipleBatchRequest, 0, len(primaryIndices))

  		for _, index := range primaryIndices {
  			requests = append(requests, search.MultipleBatchRequest{
  				Action:    "delete",
  				IndexName: index.Name,
  			})
  		}

  		_, err = client.MultipleBatch(client.NewApiMultipleBatchRequest(

  			search.NewEmptyBatchParams().SetRequests(requests)))
  		if err != nil {
  			panic(err)
  		}

  		fmt.Println("Deleted primary indices.")
  	}

  	// Now, delete replica indices
  	if len(replicaIndices) > 0 {
  		requests := make([]search.MultipleBatchRequest, 0, len(replicaIndices))

  		for _, index := range primaryIndices {
  			requests = append(requests, search.MultipleBatchRequest{
  				Action:    "delete",
  				IndexName: index.Name,
  			})
  		}

  		_, err = client.MultipleBatch(client.NewApiMultipleBatchRequest(

  			search.NewEmptyBatchParams().SetRequests(requests)))
  		if err != nil {
  			panic(err)
  		}

  		fmt.Println("Deleted replica indices.")
  	}
  }

  ```

  ```java Java theme={"system"}
  package com.algolia;

  import com.algolia.api.SearchClient;
  import com.algolia.config.*;
  import com.algolia.model.search.*;
  import java.util.List;

  public class deleteMultipleIndices {

    public static void main(String[] args) throws Exception {
      // You need an API key with `deleteIndex`
      try (SearchClient client = new SearchClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")) {
        // List all indices
        ListIndicesResponse indices = client.listIndices();

        // Primary indices don't have a `primary` key
        List<FetchedIndex> primaryIndices = indices
          .getItems()
          .stream()
          .filter(item -> item.getPrimary() == null)
          .toList();
        List<FetchedIndex> replicaIndices = indices
          .getItems()
          .stream()
          .filter(item -> item.getPrimary() != null)
          .toList();

        // Delete primary indices first
        if (!primaryIndices.isEmpty()) {
          List<MultipleBatchRequest> requests = primaryIndices
            .stream()
            .map(index -> new MultipleBatchRequest().setAction(Action.DELETE).setIndexName(index.getName()))
            .toList();
          client.multipleBatch(new BatchParams().setRequests(requests));
          System.out.println("Deleted primary indices.");
        }

        // Now, delete replica indices
        if (!replicaIndices.isEmpty()) {
          List<MultipleBatchRequest> requests = replicaIndices
            .stream()
            .map(index -> new MultipleBatchRequest().setAction(Action.DELETE).setIndexName(index.getName()))
            .toList();
          client.multipleBatch(new BatchParams().setRequests(requests));
          System.out.println("Deleted replica indices.");
        }
      } catch (Exception e) {
        System.out.println("An error occurred: " + e.getMessage());
      }
    }
  }

  ```

  ```js JavaScript theme={"system"}
  import { algoliasearch } from 'algoliasearch';

  import type { MultipleBatchRequest } from 'algoliasearch';

  // You need an API key with `deleteIndex`
  const client = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_API_KEY');

  // List all indices
  const indices = await client.listIndices();

  // Primary indices don't have a `primary` key
  const primaryIndices = indices.items.filter((item) => item.primary == null);
  const replicaIndices = indices.items.filter((item) => item.primary != null);

  // Delete primary indices first
  if (primaryIndices.length > 0) {
    const requests: MultipleBatchRequest[] = primaryIndices.map((index) => ({
      action: 'delete',
      indexName: index.name,
    }));
    await client.multipleBatch({ requests: requests });
    console.log('Deleted primary indices.');
  }

  // Now, delete replica indices
  if (replicaIndices.length > 0) {
    const requests: MultipleBatchRequest[] = replicaIndices.map((index) => ({
      action: 'delete',
      indexName: index.name,
    }));
    await client.multipleBatch({ requests: requests });
    console.log('Deleted replica indices.');
  }

  ```

  ```kotlin Kotlin theme={"system"}
  import com.algolia.client.api.SearchClient
  import com.algolia.client.configuration.*
  import com.algolia.client.extensions.*
  import com.algolia.client.model.search.*
  import com.algolia.client.transport.*

  suspend fun deleteMultipleIndices() {
    // You need an API key with `deleteIndex`
    val client = SearchClient(appId = "ALGOLIA_APPLICATION_ID", apiKey = "ALGOLIA_API_KEY")

    // List all indices
    val indices = client.listIndices()

    // Primary indices don't have a `primary` key
    val primaryIndices = indices.items.filter { it.primary == null }
    val replicaIndices = indices.items.filter { it.primary != null }

    // Delete primary indices first
    if (primaryIndices.isNotEmpty()) {
      val requests =
        primaryIndices.map { MultipleBatchRequest(action = Action.Delete, indexName = it.name) }
      client.multipleBatch(batchParams = BatchParams(requests = requests))
      println("Deleted primary indices.")
    }

    // Now, delete replica indices
    if (replicaIndices.isNotEmpty()) {
      val requests =
        replicaIndices.map { MultipleBatchRequest(action = Action.Delete, indexName = it.name) }
      client.multipleBatch(batchParams = BatchParams(requests = requests))
      println("Deleted replica indices.")
    }
  }

  ```

  ```php PHP theme={"system"}
  <?php

  require __DIR__.'/../vendor/autoload.php';
  use Algolia\AlgoliaSearch\Api\SearchClient;
  use Algolia\AlgoliaSearch\Model\Search\Action;
  use Algolia\AlgoliaSearch\Model\Search\MultipleBatchRequest;

  // You need an API key with `deleteIndex`
  $client = SearchClient::create('ALGOLIA_APPLICATION_ID', 'ALGOLIA_API_KEY');

  // List all indices
  $indicesResponse = $client->listIndices();
  $indices = $indicesResponse['items'];

  // Primary indices don't have a `primary` key
  $primaryIndices = array_filter($indices, function ($index) {
      return !isset($index['primary']);
  });
  $replicaIndices = array_filter($indices, function ($index) {
      return isset($index['primary']);
  });

  // Delete primary indices first
  if (!empty($primaryIndices)) {
      $requests = array_map(function ($index) {
          return (new MultipleBatchRequest())
              ->setAction((new Action())::DELETE)
              ->setIndexName($index['name'])
          ;
      }, $primaryIndices);

      $client->multipleBatch(
          ['requests' => $requests,
          ],
      );
      echo "Deleted primary indices.\n";
  }

  // Now, delete replica indices
  if (!empty($replicaIndices)) {
      $requests = array_map(function ($index) {
          return [
              'action' => 'delete',
              'indexName' => $index['name'],
          ];
      }, $replicaIndices);

      $client->multipleBatch(
          ['requests' => $requests,
          ],
      );
      echo "Deleted replica indices.\n";
  }

  ```

  ```python Python theme={"system"}
  from algoliasearch.search.client import SearchClientSync


  # You need an API key with `deleteIndex`
  _client = SearchClientSync("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")


  # List all indices
  indices = _client.list_indices()

  # Primary indices don't have a `primary` key
  primary_indices = [index for index in indices.items if index.primary is None]
  replica_indices = [index for index in indices.items if index.primary is not None]

  # Delete primary indices first
  if primary_indices:
      requests = [
          {"action": "delete", "indexName": index.name} for index in primary_indices
      ]
      _client.multiple_batch(
          batch_params={
              "requests": requests,
          },
      )
      print("Deleted primary indices.")

  # Now, delete replica indices
  if replica_indices:
      requests = [
          {"action": "delete", "indexName": index.name} for index in replica_indices
      ]
      _client.multiple_batch(
          batch_params={
              "requests": requests,
          },
      )
      print("Deleted replica indices.\n")

  ```

  ```ruby Ruby theme={"system"}
  require "algolia"

  # You need an API key with `deleteIndex`
  client = Algolia::SearchClient.create("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")

  # List all indices
  indices = client.list_indices

  # Primary indices don't have a `primary` key
  primary_indices, replica_indices = indices.items.partition { |index| index.primary.nil? }.map(&:to_a)

  # Delete primary indices first
  if primary_indices.any?
    requests = primary_indices.map { |index|
      Algolia::Search::BatchRequest.new(action: Algolia::Search::Action::DELETE, indexName: index.name)
    }
    client.multiple_batch(Algolia::Search::BatchParams.new(requests: requests))
    print("Deleted primary indices.")
  end

  # Now, delete replica indices
  if replica_indices.any?
    requests = replica_indices.map { |index|
      Algolia::Search::BatchRequest.new(action: Algolia::Search::Action::DELETE, indexName: index.name)
    }
    client.multiple_batch(Algolia::Search::BatchParams.new(requests: requests))
    print("Deleted replica indices.\n")
  end

  ```

  ```scala Scala theme={"system"}
  import scala.concurrent.ExecutionContext.Implicits.global
  import scala.concurrent.Future

  import algoliasearch.api.SearchClient
  import algoliasearch.config.*
  import algoliasearch.extension.SearchClientExtensions
  import algoliasearch.search.{Action, BatchParams, MultipleBatchRequest}

  def deleteMultipleIndices(): Future[Unit] = {
    // You need an API key with `deleteIndex`
    val client = SearchClient(appId = "ALGOLIA_APPLICATION_ID", apiKey = "ALGOLIA_API_KEY")

    client
      .listIndices(
      )
      .flatMap { indices =>
        val (primaryIndices, replicaIndices) = indices.items.partition(_.primary.isEmpty)

        val deletePrimary = if (primaryIndices.nonEmpty) {
          val requests = primaryIndices.map(index => MultipleBatchRequest(Action.Delete, None, index.name))
          client
            .multipleBatch(
              batchParams = BatchParams(
                requests = requests
              )
            )
            .map { _ =>
              println("Deleted primary indices.")
            }
        } else Future.unit

        val deleteReplica = if (replicaIndices.nonEmpty) {
          val requests = replicaIndices.map(index => MultipleBatchRequest(Action.Delete, None, index.name))
          client
            .multipleBatch(
              batchParams = BatchParams(
                requests = requests
              )
            )
            .map { _ =>
              println("Deleted replica indices.")
            }
        } else Future.unit

        for {
          _ <- deletePrimary
          _ <- deleteReplica
        } yield ()
      }
      .recover { case ex: Exception =>
        println(s"An error occurred: ${ex.getMessage}")
      }
  }

  ```

  ```swift Swift theme={"system"}
  import Foundation
  #if os(Linux) // For linux interop
      import FoundationNetworking
  #endif

  import AlgoliaCore
  import AlgoliaSearch

  func deleteMultipleIndices() async throws {
      do {
          // You need an API key with `deleteIndex`
          let client = try SearchClient(appID: "ALGOLIA_APPLICATION_ID", apiKey: "ALGOLIA_API_KEY")

          // List all indices
          let indices = try await client.listIndices()

          // Primary indices don't have a `primary` key
          let primaryIndices = indices.items.filter { $0.primary == nil }
          let replicaIndices = indices.items.filter { $0.primary != nil }

          // Delete primary indices first
          if primaryIndices.isEmpty == false {
              let requests = primaryIndices.map { MultipleBatchRequest(
                  action: .delete,
                  indexName: $0.name
              ) }
              try await client.multipleBatch(batchParams: BatchParams(requests: requests))
              print("Deleted primary indices.")
          }

          // Now, delete replica indices
          if replicaIndices.isEmpty == false {
              let requests = replicaIndices.map { MultipleBatchRequest(
                  action: .delete,
                  indexName: $0.name
              ) }
              try await client.multipleBatch(batchParams: BatchParams(requests: requests))
              print("Deleted replica indices.")
          }
      } catch {
          print(error)
      }
  }

  ```
</CodeGroup>

<Note>
  The `multipleBatch` method expects a list of operations.
  Don't wrap these operations in a `requests` property:
  API clients do this automatically.
  If you pass something like `{ requests: [...] }`, you'll get an error such as:
  "Requests attribute must be an array."
</Note>

## Clear indices

Clearing an index deletes only the records.
Use this option to reindex records but keep your settings, synonyms, and rules.

### Delete all records from an index in the Algolia dashboard

1. Go to the [Algolia dashboard](https://dashboard.algolia.com/explorer/browse) and select your Algolia application.
2. On the left sidebar, select <AlgoliaSearch /> **Search**.
3. Select your Algolia index.
4. Select **Manage index > Clear**.
5. Type `CLEAR` to confirm and click **Clear**.

### Delete all records from an index with the API

To clear an index and delete all records,
use either of the following:

* API clients: [`clearObjects`](/doc/libraries/sdk/v1/methods/clear-objects)
* Algolia CLI: [`algolia indices clear`](/doc/tools/cli/commands/indices/clear)

<CodeGroup>
  ```cs C# theme={"system"}
  var response = await client.ClearObjectsAsync("INDEX_NAME");
  ```

  ```dart Dart theme={"system"}
  final response = await client.clearObjects(
    indexName: "INDEX_NAME",
  );
  ```

  ```go Go theme={"system"}
  response, err := client.ClearObjects(client.NewApiClearObjectsRequest(
    "INDEX_NAME"))
  if err != nil {
    // handle the eventual error
    panic(err)
  }
  ```

  ```java Java theme={"system"}
  UpdatedAtResponse response = client.clearObjects("INDEX_NAME");
  ```

  ```js JavaScript theme={"system"}
  const response = await client.clearObjects({ indexName: 'theIndexName' });
  ```

  ```kotlin Kotlin theme={"system"}
  var response = client.clearObjects(indexName = "INDEX_NAME")
  ```

  ```php PHP theme={"system"}
  $response = $client->clearObjects(
      'INDEX_NAME',
  );
  ```

  ```python Python theme={"system"}
  response = client.clear_objects(
      index_name="INDEX_NAME",
  )
  ```

  ```ruby Ruby theme={"system"}
  response = client.clear_objects("INDEX_NAME")
  ```

  ```scala Scala theme={"system"}
  val response = Await.result(
    client.clearObjects(
      indexName = "INDEX_NAME"
    ),
    Duration(100, "sec")
  )
  ```

  ```swift Swift theme={"system"}
  let response = try await client.clearObjects(indexName: "INDEX_NAME")
  ```
</CodeGroup>
