# Sorting

## Parameters

The **`sortBy`** parameter allows to control the sorting of the results with a list of different values (and order for each value). In order to sort by an attribute, it must be defined as a **Sortable attribute** in the XO Console.

| **Name**     | Type                   | Is Required ? | Default value |
| ------------ | ---------------------- | ------------- | ------------- |
| **`sortBy`** | `array` of `SortValue` | ✖             | empty array   |

### `sortBy`

Sort results by a list of values. Each `SortValue` must be a *JSON* object with the following properties:

| Property    | Type                | Description                                                      |
| ----------- | ------------------- | ---------------------------------------------------------------- |
| `attribute` | `string`            | Name of the value to sort by. Must be defined in the XO Console. |
| `order`     | `'asc'` or `'desc'` | <p>Order of the results</p><p>(ascending / descending)</p>       |

#### Notes

* By default, `order` is set to `'asc'` if not specified
* `SortValue` objects are evaluated by order of appearance. ie. The first `SortValue` takes precedence over the second, etc...
* **The sort order depends on the attribute type**: numeric values are sorted in numeric order, strings are sorted in alphanumeric order, dates in chronological order ...
* If one of the attributes is not registered as a **Sortable attribute** in the XO Console, an error is returned.

## Response

All responses from XO Search uses the same format.\
Check [API Reference](https://crownpeak.gitbook.io/product-discovery/resources/archived-pages/introduction/api) page for a more detailed description of this format.

{% content-ref url="../api" %}
[api](https://crownpeak.gitbook.io/product-discovery/resources/archived-pages/introduction/api)
{% endcontent-ref %}

## Usage example

* Sort results by decreasing price order

{% tabs %}
{% tab title="SDK - JS" %}
**NodeJS / NPM example**

```javascript
import { search } from '@attraqt/search';

const query = 'T-shirt';

search.init({ token: SEARCH_API_TOKEN });

const response = await search.query(query, {
  sortBy: [
    {
      attribute: 'price',
      order: 'desc'
    }
  ]
});

console.log(response);
```

**HTML example**

```markup
<script type="text/javascript">
    xo.init({
        search: {
            token: 'SEARCH_API_TOKEN'
        }
    });

    xo.search.query('T-Shirt', {
        sortBy: [
            {
                attribute: 'price',
                order: 'desc'
            }
        ]
    }).then((response) => {
        console.log(response);
    });
</script>
```

{% endtab %}

{% tab title="API - POST" %}
**HTTP example**

```http
POST https://api-eu.attraqt.io/search HTTP/1.1
Content-Type: application/json; charset=UTF-8

{
  "token": "SEARCH_API_TOKEN",
  "query": "T-Shirt",
  "options": {
    "sortBy": [
      {
        "attribute": "price",
        "order": "desc" 
      }
    ]
  }
}
```

**`curl` example**

```bash
curl -d "{\"token\":\"${SEARCH_API_TOKEN}\", \"query\":\"T-Shirt\", \"options\":{\"sortBy\":[{\"attribute\":\"price\", \"order\":\"desc\"}]}}" \
     -H "Content-Type: application/json; charset=UTF-8"                                                                                        \
     -X POST "https://api-eu.attraqt.io/search"
```

**JavaScript example**

```javascript
const response = await fetch('https://api-eu.attraqt.io/search', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json; charset=UTF-8'
  },
  body: JSON.stringify({
    token: SEARCH_API_TOKEN,
    query: 'T-Shirt',
    options: {
      sortBy: [
        {
          attribute: 'price',
          order: 'desc'
        }
      ]
    }
  })
});

if (response.ok) {
  console.log(await response.json());
}
```

{% endtab %}

{% tab title="API - GET" %}
**HTTP example**

```http
GET https://api-eu.attraqt.io/search/:token?encoded=:encodedParams HTTP/1.1
```

**`curl` example**

```bash
curl "https://api-eu.attraqt.io/search/${SEARCH_API_TOKEN}?encoded=%7B%22query%22%3A%22T-Shirt%22%2C%20%22options%22%3A%7B%22sortBy%22%3A%5B%7B%22attribute%22%3A%22price%22%2C%22order%22%3A%22desc%22%7D%5D%7D%7D"
```

**JavaScript example**

```javascript
const token = SEARCH_API_TOKEN;
const params = encodeURIComponent(JSON.stringify({
  query: 'T-shirt',
  options: {
    sortBy: [
      {
        'attribute': 'price',
        'order': 'desc'
      }
    ]
  }
}));

const response = await fetch(
  `https://api-eu.attraqt.io/search/${token}?encoded=${params}`
);

if (response.ok) {
  console.log(await response.json());
}
```

{% endtab %}
{% endtabs %}
