3

My query is like:

/2013-01-01/search?q=(and author:'william' category:'Videos')&q.parser=structured&expr.random=_rand&return=_all_fields&size=1

and returns a video. However, I want a random videoId on every request.

Using the expression &expr.random=_rand; I'm unable to fetch a random result and I have failed to find any solution in documentation.

How can I get a random search result on every request?

Air
  • 8,274
  • 2
  • 53
  • 88
Shelim
  • 141
  • 8

2 Answers2

7

The CloudSearch docs are quite lacking. I needed something similar and came up short with Google so I just started guessing by applying what I already knew about Solr and I found a solution:

/2013-01-01/search?q=what&sort=_rand_1 desc

Note that _rand will also work however after the first search it will always return the same results which is actually ideal if you need to paginate through a random result set (it works the same way in Solr). So, to get random results every time you need to randomly generate an _something and append it to _rand.

dotcomly
  • 2,154
  • 23
  • 29
  • 1
    Just to complete the comment in c# I have done this part of code : var request = new SearchRequest() { ... Sort = string.Format("_rand_{0} desc", DateTime.Now.Ticks) .... }; – M07 Dec 09 '15 at 16:25
3

You can accomplish this through pagination by setting the start param to a random value from 0 to hits.found and requesting size=1:

search?q=matchall&q.parser=structured&size=1&start={yourRandomNumber}

If the number of documents in your index is fluctuating, you'll need to make 2 queries: one to get the max number of results (comes back as hits.found), and another to retrieve the random result.

alexroussos
  • 2,671
  • 1
  • 25
  • 38
  • Thank you for your response. I agree with your answer but i have little confusion about performance on making double request as my number of document is unknown. – Shelim Apr 14 '15 at 06:14