Skip to content

Sorting

To sort, Orama uses the properties defined in the schema to know on which properties you want to sort.

javascript
const db = await create({
  schema: {
    title: 'string',
    year: 'number',
    inPromotion: 'boolean',
    meta: {
      tag: 'string',
      rating: 'number',
      favorite: 'boolean',
    },
  }
})
const results = await search(db, {
  term: 'prestige',
  sortBy: {
    property: 'title', // or 'year', 'inPromotion'
  }
})

Orama supports sorting on 'string', 'number' and 'boolean'. The arrays are not supported.

You can also specify nested properties using the '.' notation: 'meta.tag', 'meta.rating' and 'meta.favorite'. For example:

javascript
const results = await search(db, {
  term: 'prestige',
  sortBy: {
    property: 'meta.rating',
  }
})

Reverse order

Orama supports the reverse order specifying the key order:

javascript

const db = await create({
  schema: {
    title: 'string',
    year: 'number',
    inPromotion: 'boolean',
    meta: {
      tag: 'string',
      rating: 'number',
      favorite: 'boolean',
    },
  }
})
const results = await search(db, {
  term: 'prestige',
  sortBy: {
    property: 'title', // or 'year', 'inPromotion'
    order: 'DESC' // default is "ASC"
  }
})

Memory optimization

By default, Orama allows the sort on all properties defined in the schema. This creates an in-memory sort index for each properties. If you want to optimize the memory usage, Orama supports the unsortableProperties list.

javascript
const db = await create({
  schema: {
    title: 'string',
    year: 'number',
    inPromotion: 'boolean',
    meta: {
      tag: 'string',
      rating: 'number',
      favorite: 'boolean',
    },
  },
  sortBy: {
    unsortableProperties: ['year', 'meta.tag']
  },
})

Custom sort

Orama allows you to specify the sort algorithm in the following way:

javascript
const db = await create({
  schema: {
    title: 'string',
    year: 'number',
    inPromotion: 'boolean',
    meta: {
      tag: 'string',
      rating: 'number',
      favorite: 'boolean',
    },
  },
  sortBy: (a, b) => {
    // Implement the custom sort algorithm 
    return a[2].year - b[2].year
  }
})

The function accepts 2 parameter with the following format [string, number, Document] that stands for:

  • id of the document
  • score of the document
  • the document

Disable sort

You can disable the sort functionality using the following snippet:

javascript
const db = await create({
  schema: {
    // The schema
  },
  sort: {
    enabled: false
  },
})