Sort by null attribute first

Helo guys, hope you’re all doing well!!!

My goal is to sort an index by lack of presence of a field first then by it’s presence, to get something like this:

{
“hits”: [
{
“id”: 163,
“tag_field”: null
},
{
“id”: 12,
“tag_field”: null
}
{
“id”: 1,
“tag_field”: “tag”
}
]
}

I’m using it in a Rails app, i know it does not work at all, but i wanted something like this

    ranking [
      "desc(created_at)",
      *'tag_field '*   < set something that when null put it on top
      'typo',
      'geo',
      'words',
      'filters',
      'proximity',
      'attribute',
      'exact',
      'custom'
    ]

Is there any way i could do it on algolia?

Thank you guys in advance!!!

Hi @alan2,

Thanks for contacting Algolia.

TL; DR - Algolia needs some value to read and cannot filter on null values, therefore you’ll need to enrich your records.

Consider adding another attribute so that your records instead look like:

{
“hits”: [
{
“id”: 163,
“tag_field”: null,
"hasTag": false, // one option
"_tags": ["tag_field_unset"] // another option
},
{
“id”: 12,
“tag_field”: null,
"hasTag": false, // one option
"_tags": ["tag_field_unset"] // another option
}
{
“id”: 1,
“tag_field”: “tag”,
"hasTag": true, // one option
"_tags": ["tag_field_set"] // another option
}
]
}

Then you can actually filter on this "hasTag" or "_tags" attribute. You can consider using optionalFilters to promote the null values first:

optionalFilters: [
    'hasTag:false'
  ]

optionalFilters: [
    'tag_field_unset' // with the _tags field you do not need the attribute
  ]

Or do a customRanking on "asc(hasTag)" because false is read as 0