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

# Set or update the "sortingStrategy" configuration for an existing composition

> Updates the "sortingStrategy" field of an existing composition. This endpoint lets you create a new sorting strategy mapping or replace the configured one. The provided sorting indices must be associated indices or replicas of the main targeted index.

This endpoint can't validate whether the sort index is related to the composition's main index.
Validation fails at runtime if the index you updated isn't related.

The update is applied to the specified composition within the current Algolia application and returns a taskID that can be used to track the operation’s completion.

**Required ACL:** `editSettings`


## OpenAPI

````yaml specs/composition.yml post /1/compositions/{compositionID}/sortingStrategy
openapi: 3.1.0
info:
  title: Composition API
  summary: >-
    The Algolia Composition API lets you run composed search requests on your
    Compositions
  description: >
    ## Client libraries


    Use Algolia's API clients and libraries to reliably integrate Algolia's APIs
    with your apps.


    For more information, see [Algolia's
    ecosystem](https://www.algolia.com/doc/libraries).


    ## Base URLs


    Base URLs for the Composition API:


    - `https://{APPLICATION_ID}.algolia.net`

    - `https://{APPLICATION_ID}-dsn.algolia.net`.
      If your subscription includes a [Distributed Search Network](https://dashboard.algolia.com/infra),
      this ensures that requests are sent to servers closest to users.

    Both URLs provide high availability by distributing requests with load
    balancing.


    **All requests must use HTTPS.**


    ## Retry strategy


    To guarantee high availability, implement a retry strategy for all API
    requests using the URLs of your servers as fallbacks:


    - `https://{APPLICATION_ID}-1.algolianet.com`

    - `https://{APPLICATION_ID}-2.algolianet.com`

    - `https://{APPLICATION_ID}-3.algolianet.com`


    These URLs use a different DNS provider than the primary URLs.

    Randomize this list to ensure an even load across the three servers.


    All Algolia API clients implement this retry strategy.


    ## Authentication


    Add these headers to authenticate requests:


    - `x-algolia-application-id`. Your Algolia application ID.

    - `x-algolia-api-key`. An API key with the necessary permissions to make the
    request.
      The required access control list (ACL) to make a request is listed in each endpoint's reference.

    You can find your application ID and API key in the [Algolia
    dashboard](https://dashboard.algolia.com/account/api-keys).


    ## Request format


    Depending on the endpoint, request bodies are either JSON objects or arrays
    of JSON objects.


    ## Parameters


    Parameters are passed in the request body for POST and PUT requests.


    ## Response status and errors


    The Composition API returns JSON responses.

    Since JSON doesn't guarantee any specific ordering, don't rely on the order
    of attributes in the API response.


    Successful responses return `2xx` statuses. Client errors return `4xx`
    statuses. Server errors return `5xx` statuses.

    Error responses have a `message` property with more information.


    ## Version


    The current version of the Composition API is version 1, indicated by the
    `/1/` in each endpoint's URL.
  version: 1.0.0
servers:
  - url: https://{appId}.algolia.net
    variables:
      appId:
        default: ALGOLIA_APPLICATION_ID
  - url: https://{appId}-1.algolianet.com
    variables:
      appId:
        default: ALGOLIA_APPLICATION_ID
  - url: https://{appId}-2.algolianet.com
    variables:
      appId:
        default: ALGOLIA_APPLICATION_ID
  - url: https://{appId}-3.algolianet.com
    variables:
      appId:
        default: ALGOLIA_APPLICATION_ID
  - url: https://{appId}-dsn.algolia.net
    variables:
      appId:
        default: ALGOLIA_APPLICATION_ID
security:
  - appId: []
    apiKey: []
tags:
  - name: Advanced
    description: Advanced endpoints to manage tasks.
  - name: Composition Rules
    description: Manage your compositions rules.
  - name: Compositions
    description: Manage your compositions and composition settings.
  - name: Search
    description: Search one or more indices for matching records or facet values.
paths:
  /1/compositions/{compositionID}/sortingStrategy:
    post:
      tags:
        - Compositions
      summary: >-
        Set or update the "sortingStrategy" configuration for an existing
        composition
      description: >
        Updates the "sortingStrategy" field of an existing composition.

        This endpoint lets you create a new sorting strategy mapping or replace
        the configured one.

        The provided sorting indices must be associated indices or replicas of
        the main targeted index.


        This endpoint can't validate whether the sort index is related to the
        composition's main index.

        Validation fails at runtime if the index you updated isn't related.


        The update is applied to the specified composition within the current
        Algolia application and returns a taskID that can be used to track the
        operation’s completion.
      operationId: updateSortingStrategyComposition
      parameters:
        - $ref: '#/components/parameters/compositionID'
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/sortingStrategy'
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                title: taskIDResponse
                type: object
                additionalProperties: false
                properties:
                  taskID:
                    $ref: '#/components/schemas/taskID'
                required:
                  - taskID
        '400':
          $ref: '#/components/responses/BadRequest'
        '402':
          $ref: '#/components/responses/FeatureNotEnabled'
        '403':
          $ref: '#/components/responses/MethodNotAllowed'
        '404':
          $ref: '#/components/responses/CompositionNotFound'
      x-codeSamples:
        - lang: csharp
          label: C#
          source: |-
            // Initialize the client
            var client = new CompositionClient(
              new CompositionConfig("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
            );

            // Call the API
            var response = await client.UpdateSortingStrategyCompositionAsync(
              "my-compo",
              new Dictionary<string, string>
              {
                { "Price-asc", "products-low-to-high" },
                { "Price-desc", "products-high-to-low" },
              }
            );

            // print the response
            Console.WriteLine(response);
        - lang: dart
          label: Dart
          source: |-
            // Initialize the client
            final client = CompositionClient(
                appId: 'ALGOLIA_APPLICATION_ID', apiKey: 'ALGOLIA_API_KEY');

            // Call the API
            final response = await client.updateSortingStrategyComposition(
              compositionID: "my-compo",
              requestBody: {
                'Price-asc': "products-low-to-high",
                'Price-desc': "products-high-to-low",
              },
            );

            // print the response
            print(response);
        - lang: go
          label: Go
          source: >-
            // Initialize the client

            client, err := composition.NewClient("ALGOLIA_APPLICATION_ID",
            "ALGOLIA_API_KEY")

            if err != nil {
              // The client can fail to initialize if you pass an invalid parameter.
              panic(err)
            }


            // Call the API

            response, err :=
            client.UpdateSortingStrategyComposition(client.NewApiUpdateSortingStrategyCompositionRequest(
              "my-compo", map[string]string{"Price-asc": "products-low-to-high", "Price-desc": "products-high-to-low"}))
            if err != nil {
              // handle the eventual error
              panic(err)
            }



            // print the response

            print(response)
        - lang: java
          label: Java
          source: >-
            // Initialize the client

            CompositionClient client = new
            CompositionClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY");


            // Call the API

            TaskIDResponse response = client.updateSortingStrategyComposition(
              "my-compo",
              new HashMap() {
                {
                  put("Price-asc", "products-low-to-high");
                  put("Price-desc", "products-high-to-low");
                }
              }
            );


            // print the response

            System.out.println(response);
        - lang: javascript
          label: JavaScript
          source: >-
            // Initialize the client

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


            // Call the API

            const response = await client.updateSortingStrategyComposition({
              compositionID: 'my-compo',
              requestBody: { 'Price-asc': 'products-low-to-high', 'Price-desc': 'products-high-to-low' },
            });



            // print the response

            console.log(response);
        - lang: kotlin
          label: Kotlin
          source: >-
            // Initialize the client

            val client = CompositionClient(appId = "ALGOLIA_APPLICATION_ID",
            apiKey = "ALGOLIA_API_KEY")


            // Call the API

            var response =
              client.updateSortingStrategyComposition(
                compositionID = "my-compo",
                requestBody =
                  mapOf("Price-asc" to "products-low-to-high", "Price-desc" to "products-high-to-low"),
              )


            // print the response

            println(response)
        - lang: php
          label: PHP
          source: >-
            // Initialize the client

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


            // Call the API

            $response = $client->updateSortingStrategyComposition(
                'my-compo',
                ['Price-asc' => 'products-low-to-high',
                    'Price-desc' => 'products-high-to-low',
                ],
            );



            // print the response

            var_dump($response);
        - lang: python
          label: Python
          source: >-
            # Initialize the client

            # In an asynchronous context, you can use CompositionClient instead,
            which exposes the exact same methods.

            client = CompositionClientSync("ALGOLIA_APPLICATION_ID",
            "ALGOLIA_API_KEY")


            # Call the API

            response = client.update_sorting_strategy_composition(
                composition_id="my-compo",
                request_body={
                    "Price-asc": "products-low-to-high",
                    "Price-desc": "products-high-to-low",
                },
            )



            # print the response

            print(response)
        - lang: ruby
          label: Ruby
          source: >-
            # Initialize the client

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


            # Call the API

            response = client.update_sorting_strategy_composition(
              "my-compo",
              {:"Price-asc" => "products-low-to-high", :"Price-desc" => "products-high-to-low"}
            )



            # print the response

            puts(response)
        - lang: scala
          label: Scala
          source: >-
            // Initialize the client

            val client = CompositionClient(appId = "ALGOLIA_APPLICATION_ID",
            apiKey = "ALGOLIA_API_KEY")


            // Call the API

            val response = Await.result(
              client.updateSortingStrategyComposition(
                compositionID = "my-compo",
                requestBody = Map("Price-asc" -> "products-low-to-high", "Price-desc" -> "products-high-to-low")
              ),
              Duration(100, "sec")
            )


            // print the response

            println(response)
        - lang: swift
          label: Swift
          source: >-
            // Initialize the client

            let client = try CompositionClient(appID: "ALGOLIA_APPLICATION_ID",
            apiKey: "ALGOLIA_API_KEY")


            // Call the API

            let response = try await client.updateSortingStrategyComposition(
                compositionID: "my-compo",
                requestBody: ["Price-asc": "products-low-to-high", "Price-desc": "products-high-to-low"]
            )


            // print the response

            print(response)
        - lang: cURL
          label: curl
          source: |-
            curl --request POST \
              --url https://algolia_application_id.algolia.net/1/compositions/my_composition_object_id/sortingStrategy \
              --header 'accept: application/json' \
              --header 'content-type: application/json' \
              --header 'x-algolia-api-key: ALGOLIA_API_KEY' \
              --header 'x-algolia-application-id: ALGOLIA_APPLICATION_ID' \
              --data '
            {
              "Price (asc)": "products-low-to-high",
              "Price (desc)": "products-high-to-low"
            }
            '
components:
  parameters:
    compositionID:
      in: path
      name: compositionID
      description: Unique Composition ObjectID.
      required: true
      schema:
        $ref: '#/components/schemas/compositionObjectID'
  schemas:
    sortingStrategy:
      type: object
      description: >
        A mapping of sorting labels to the indices (or replicas) that implement
        those sorting rules. The sorting indices MUST be related to the
        associated main targeted index in the composition.

        Each key is the label your frontend sends at runtime (for example,
        "Price (asc)"), and each value is the name of the index that should be
        queried when that label is selected.


        When a request includes a "sortBy" parameter, the platform looks up the
        corresponding index in this mapping and uses it to execute the query.
        The main targeted index is replaced

        with the sorting strategy index it is mapped to.


        Up to 20 sorting strategies can be defined.
      additionalProperties:
        type: string
      example:
        Price (asc): products-low-to-high
        Price (desc): products-high-to-low
    taskID:
      type: integer
      format: int64
      example: 1514562690001
      description: >
        Unique identifier of a task.


        A successful API response means that a task was added to a queue.

        It might not run immediately.

        You can check the task's progress with the [`task`
        operation](https://www.algolia.com/doc/rest-api/search/get-task) and
        this task ID.
    compositionObjectID:
      type: string
      example: my_composition_object_id
      description: Composition unique identifier.
    ErrorBase:
      description: Error.
      type: object
      x-keep-model: true
      additionalProperties: true
      properties:
        message:
          type: string
          example: Invalid Application-Id or API-Key
  responses:
    BadRequest:
      description: Bad request or request arguments.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorBase'
    FeatureNotEnabled:
      description: This feature is not enabled on your Algolia account.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorBase'
    MethodNotAllowed:
      description: Method not allowed with this API key.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorBase'
    CompositionNotFound:
      description: Composition not found.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorBase'
  securitySchemes:
    appId:
      type: apiKey
      in: header
      name: x-algolia-application-id
      description: Your Algolia application ID.
    apiKey:
      type: apiKey
      in: header
      name: x-algolia-api-key
      description: >
        Your Algolia API key with the necessary permissions to make the request.

        Permissions are controlled through access control lists (ACL) and access
        restrictions.

        The required ACL to make a request is listed in each endpoint's
        reference.

````