How to Add Random Sort to Typesense Search Results

TLDR Fulvio inquired about the possibility of random sorting in Typesense search results. Kishore Nallan suggested a workaround involving geo fields, and Bruno recommended client-side sorting if pagination isn't involved.

Photo of Fulvio
Fulvio
Wed, 18 Aug 2021 15:23:56 UTC

I there i know typesense is an search engine, but my client is also using it as filter for frontend items, but the result are always the same, does typesense have random sort?

Photo of Kishore Nallan
Kishore Nallan
Wed, 18 Aug 2021 15:24:45 UTC

:wave: Can you please elaborate what you mean by "result are always the same"? I don't follow you.

Photo of Fulvio
Fulvio
Wed, 18 Aug 2021 15:26:58 UTC

Hi Kishore Nallan, is using the api call to get results from typesense, but the order of the itens is always the same, i would like to find out if we can add random sort.

Photo of Kishore Nallan
Kishore Nallan
Wed, 18 Aug 2021 15:27:37 UTC

So a wildcard query is made with just filters?

Photo of Fulvio
Fulvio
Wed, 18 Aug 2021 15:27:45 UTC

yep

Photo of Fulvio
Fulvio
Wed, 18 Aug 2021 15:28:03 UTC

1. filters: “NOT image = ‘noimage’ AND relevance = 1 AND elected = ‘Ar Livre’” 2. limit: 10

Photo of Kishore Nallan
Kishore Nallan
Wed, 18 Aug 2021 15:29:03 UTC

Okay, in that case, the documents are sorted by their internal IDs (which are ascending and auto incrementing in nature). There is no way to sort randomly, because I have never seen a use case where a random order helps :slightly_smiling_face:

Photo of Fulvio
Fulvio
Wed, 18 Aug 2021 15:29:04 UTC

im using right now with another seach engine, but moving to typesense after the tests are concluded..

Photo of Fulvio
Fulvio
Wed, 18 Aug 2021 15:29:44 UTC

thats what o thought.

Photo of Fulvio
Fulvio
Wed, 18 Aug 2021 15:30:32 UTC

They found out the calling typesense is faster then quering the DB :smile:

Photo of Kishore Nallan
Kishore Nallan
Wed, 18 Aug 2021 15:31:23 UTC

One way to "generate" randomness if you really want it. But it's one giant hack: 1. Add a geo field with a random value. 2. During sort_by pass a random geo point as reference value. This would sort results on "distance" from the reference point, but since the geo point is random, the computed distance will always change!

Photo of Fulvio
Fulvio
Wed, 18 Aug 2021 15:43:17 UTC

Humm nice hack :smile:

Photo of Bruno
Bruno
Wed, 18 Aug 2021 18:24:19 UTC

If pagination isn't involved, you can always sort the results randomly client-side

Photo of Fulvio
Fulvio
Wed, 18 Aug 2021 18:36:41 UTC

That could be a trick..