Method: Redis::Commands::SortedSets#zadd

Defined in:
lib/redis/commands/sorted_sets.rb

#zadd(key, *args, nx: nil, xx: nil, lt: nil, gt: nil, ch: nil, incr: nil) ⇒ Boolean, ...

Add one or more members to a sorted set, or update the score for members that already exist.

Examples:

Add a single ‘[score, member]` pair to a sorted set

redis.zadd("zset", 32.0, "member")

Add an array of ‘[score, member]` pairs to a sorted set

redis.zadd("zset", [[32.0, "a"], [64.0, "b"]])

Parameters:

  • key (String)
  • args ([Float, String], Array<[Float, String]>)
    • a single ‘[score, member]` pair

    • an array of ‘[score, member]` pairs

  • options (Hash)
    • ‘:xx => true`: Only update elements that already exist (never

    add elements)

    • ‘:nx => true`: Don’t update already existing elements (always

    add new elements)

    • ‘:lt => true`: Only update existing elements if the new score

    is less than the current score

    • ‘:gt => true`: Only update existing elements if the new score

    is greater than the current score

    • ‘:ch => true`: Modify the return value from the number of new

    elements added, to the total number of elements changed (CH is an abbreviation of changed); changed elements are new elements added and elements already existing for which the score was updated

    • ‘:incr => true`: When this option is specified ZADD acts like

    ZINCRBY; only one score-element pair can be specified in this mode

Returns:

  • (Boolean, Integer, Float)
    • ‘Boolean` when a single pair is specified, holding whether or not it was

    added to the sorted set.

    • ‘Integer` when an array of pairs is specified, holding the number of

    pairs that were added to the sorted set.

    • ‘Float` when option :incr is specified, holding the score of the member

    after incrementing it.



53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/redis/commands/sorted_sets.rb', line 53

def zadd(key, *args, nx: nil, xx: nil, lt: nil, gt: nil, ch: nil, incr: nil)
  command = [:zadd, key]
  command << "NX" if nx
  command << "XX" if xx
  command << "LT" if lt
  command << "GT" if gt
  command << "CH" if ch
  command << "INCR" if incr

  if args.size == 1 && args[0].is_a?(Array)
    members_to_add = args[0]
    return 0 if members_to_add.empty?

    # Variadic: return float if INCR, integer if !INCR
    send_command(command + members_to_add, &(incr ? Floatify : nil))
  elsif args.size == 2
    # Single pair: return float if INCR, boolean if !INCR
    send_command(command + args, &(incr ? Floatify : Boolify))
  else
    raise ArgumentError, "wrong number of arguments"
  end
end