Skip to content

Instantly share code, notes, and snippets.

@OleksandrKucherenko
Created October 5, 2018 12:07
Show Gist options
  • Save OleksandrKucherenko/fdd8c555dfb3225910ceee037749bd61 to your computer and use it in GitHub Desktop.
Save OleksandrKucherenko/fdd8c555dfb3225910ceee037749bd61 to your computer and use it in GitHub Desktop.
Redis LUA Script. Create from KEYS a list/array/queue.
local list = KEYS[1]
local search = KEYS[2]
local instances = redis.call('KEYS', search)
if nil == instances then return nil end
redis.call('DEL', list)
local counter = 0
for i,instance in ipairs(instances) do
redis.call('LPUSH', list, instance)
counter = counter + 1
end
return counter
@OleksandrKucherenko
Copy link
Author

usage:
redis-cli -h <host> --eval "$(cat keysToList.lua)" 2 my-list-name keys-pattern

Real Life usage:
redis-cli --eval "$(cat keysToList.lua)" 2 instances-queue instance.*

@OleksandrKucherenko
Copy link
Author

OleksandrKucherenko commented Oct 5, 2018

Or from Javascript:

const Redis = require('ioredis')
const REDIS_URL = '{your name of instance}.amazonaws.com'
const QUEUE_AVAILABLE = 'genymotion-queue'

  // Note: LUA scripts executed as atomic operation on Redis side
  const redis = new Redis(6379, REDIS_URL)
  redis.defineCommand('keysToList', {
    numberOfKeys: 2,
    lua: `
local list = KEYS[1]
local search = KEYS[2]
local instances = redis.call('KEYS', search)
if nil == instances then return nil end

redis.call('DEL', list)
local counter = 0
for i,instance in ipairs(instances) do
  redis.call('LPUSH', list, instance)
  counter = counter + 1
end 

return counter
    `,
  })
  const instances = await redis.keysToList(QUEUE_AVAILABLE, 'instance.*')
  redis.quit()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment