Get 1 random record from Tarantool space

122 Views Asked by At

I have query with 2 conditions which return 1 record every request 1by1 as inserted in space

box.space.extensions.index.secondary:select(
        {city, 0},
        {limit=1}
    )

Sample:

{1}
{2}
{3}

I need to get random record every request. Sample:

{3}
{1}
{2}
1

There are 1 best solutions below

0
Spar On

According to tarantool API, select returns array of tuples, so that's a regular Lua table you can manipulate by yourself. If you want to randomize the content in the request you need table.Shuffle. If you want to get one random item from the request, you can use tbl[math.random(#tbl)].

Here is example of table.Shuffle code:

function table.Shuffle(tbl)
    for i = #tbl, 2, -1 do
        local j = math.random(i)
        tbl[i], tbl[j] = tbl[j], tbl[i]
    end
end