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

# Search in a replica index

> How to search a replica index, to create different sorting options for your users.

A [replica index](/doc/guides/managing-results/refine-results/sorting/in-depth/replicas) is a copy of your primary index that sorts results in alternative ways.
For instance, on an ecommerce site, you might want to sort search results by default from cheapest to most expensive.
You also offer a drop-down menu to let users sort from most expensive to cheapest.

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

<Note>
  If you're using InstantSearch,
  use the [`sortBy`](/doc/api-reference/widgets/sort-by/js) widget to let users choose their sorting strategy.
</Note>

## Create replica indices

Let users sort results in various ways by [creating a replica](/doc/guides/managing-results/refine-results/sorting/how-to/creating-replicas) for each sorting strategy.
That sorting strategy might order results by price, date, relevance, or any other criteria you provide.

## Switch index as required

When users change the sorting strategy, ensure you switch to the appropriate index (primary or replica).

<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 SearchInReplicaIndex
  {
    async Task Main(string[] args)
    {
      var client = new SearchClient(new SearchConfig("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY"));

      var query = "query";

      // 1. Change the sort dynamically based on the UI events
      var sortByPrice = false;

      // 2. Get the index name based on sortByPrice
      var indexName = sortByPrice ? "products_price_desc" : "products";

      // 3. Search on dynamic index name (primary or replica)
      await client.SearchSingleIndexAsync<Hit>(
        indexName,
        new SearchParams(new SearchParamsObject { Query = "query" })
      );
    }
  }

  ```

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

  void searchInReplicaIndex() async {
    final client =
        SearchClient(appId: 'ALGOLIA_APPLICATION_ID', apiKey: 'ALGOLIA_API_KEY');

    // 1. Change the sort dynamically based on the UI events
    final sortByPrice = false;

    // 2. Get the index name based on sortByPrice
    // ignore: dead_code
    final indexName = sortByPrice ? "products_price_desc" : "products";

    // 3. Search on dynamic index name (primary or replica)
    await client.searchSingleIndex(
      indexName: indexName,
      searchParams: SearchParamsObject(
        query: "query",
      ),
    );
  }

  ```

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

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

  func searchInReplicaIndex() {
  	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)
  	}

  	// 1. Change the sort dynamically based on the UI events
  	sortByPrice := false

  	// 2. Get the index name based on sortByPrice
  	indexName := "products"
  	if sortByPrice {
  		indexName = "products_price_desc"
  	}

  	// 3. Search on dynamic index name (primary or replica)
  	_, err = client.SearchSingleIndex(client.NewApiSearchSingleIndexRequest(
  		indexName).WithSearchParams(search.SearchParamsObjectAsSearchParams(
  		search.NewEmptySearchParamsObject().SetQuery("query"))))
  	if err != nil {
  		panic(err)
  	}
  }

  ```

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

  import com.algolia.api.SearchClient;
  import com.algolia.config.*;
  import com.algolia.model.search.*;

  public class searchInReplicaIndex {

    public static void main(String[] args) throws Exception {
      try (SearchClient client = new SearchClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")) {
        String query = "query";

        // 1. Change the sort dynamically based on the UI events
        boolean sortByPrice = false;

        // 2. Get the index name based on sortByPrice
        String indexName = sortByPrice ? "products_price_desc" : "products";

        // 3. Search on dynamic index name (primary or replica)
        client.searchSingleIndex(indexName, new SearchParamsObject().setQuery("query"), Hit.class);
      } catch (Exception e) {
        System.out.println("An error occurred: " + e.getMessage());
      }
    }
  }

  ```

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

  const client = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_API_KEY');

  // 1. Change the sort dynamically based on the UI events
  const sortByPrice = false;

  // 2. Get the index name based on sortByPrice
  const indexName = sortByPrice ? 'products_price_desc' : 'products';

  // 3. Search on dynamic index name (primary or replica)
  await client.searchSingleIndex({ indexName: indexName, searchParams: { query: 'query' } });

  ```

  ```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 searchInReplicaIndex() {
    val client = SearchClient(appId = "ALGOLIA_APPLICATION_ID", apiKey = "ALGOLIA_API_KEY")

    // 1. Change the sort dynamically based on the UI events
    val sortByPrice = false

    // 2. Get the index name based on sortByPrice
    val indexName = if (sortByPrice) "products_price_desc" else "products"

    // 3. Search on dynamic index name (primary or replica)
    client.searchSingleIndex(
      indexName = indexName,
      searchParams = SearchParamsObject(query = "query"),
    )
  }

  ```

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

  require __DIR__.'/../vendor/autoload.php';
  use Algolia\AlgoliaSearch\Api\SearchClient;

  $client = SearchClient::create('ALGOLIA_APPLICATION_ID', 'ALGOLIA_API_KEY');

  $query = 'query';

  // 1. Change the sort dynamically based on the UI events
  $sortByPrice = false;

  // 2. Get the index name based on sortByPrice
  $indexName = $sortByPrice ? 'products_price_desc' : 'products';

  // 3. Search on dynamic index name (primary or replica)
  $client->searchSingleIndex(
      $indexName,
      ['query' => 'query',
      ],
  );

  ```

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


  _client = SearchClientSync("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")


  query = "query"

  # 1. Change the sort dynamically based on the UI events
  sort_by_price = False

  # 2. Get the index name based on sortByPrice
  index_name = "products_price_desc" if sort_by_price else "products"

  # 3. Search on dynamic index name (primary or replica)
  _client.search_single_index(
      index_name=index_name,
      search_params={
          "query": "query",
      },
  )

  ```

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

  client = Algolia::SearchClient.create("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")

  query = "query"

  # 1. Change the sort dynamically based on the UI events
  sort_by_price = false

  # 2. Get the index name based on sortByPrice
  index_name = sort_by_price ? "products_price_desc" : "products"

  # 3. Search on dynamic index name (primary or replica)
  client.search_single_index(index_name, Algolia::Search::SearchParamsObject.new(query: "query"))

  ```

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

  import algoliasearch.api.SearchClient
  import algoliasearch.config.*
  import algoliasearch.extension.SearchClientExtensions
  import algoliasearch.search.SearchParamsObject

  def searchInReplicaIndex(): Future[Unit] = {
    val client = SearchClient(appId = "ALGOLIA_APPLICATION_ID", apiKey = "ALGOLIA_API_KEY")

    // 1. Change the sort dynamically based on the UI events
    val sortByPrice = false

    // 2. Get the index name based on sortByPrice
    val indexName = if sortByPrice then "products_price_desc" else "products"

    // 3. Search on dynamic index name (primary or replica)
    client
      .searchSingleIndex(
        indexName = indexName,
        searchParams = Some(
          SearchParamsObject(
            query = Some("query")
          )
        )
      )
      .map { response =>
        println(response)
      }
      .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 searchInReplicaIndex() async throws {
      let client = try SearchClient(appID: "ALGOLIA_APPLICATION_ID", apiKey: "ALGOLIA_API_KEY")

      // 1. Change the sort dynamically based on the UI events
      let sortByPrice = false

      // 2. Get the index name based on sortByPrice
      let indexName = sortByPrice ? "products_price_desc" : "products"

      // 3. Search on dynamic index name (primary or replica)
      let response: SearchResponse<Hit> = try await client.searchSingleIndex(
          indexName: indexName,
          searchParams: SearchSearchParams.searchSearchParamsObject(SearchSearchParamsObject(query: "query"))
      )
      print(response)
  }

  ```
</CodeGroup>
