Class: Familia::SortedSet
- Includes:
- DataType::CollectionBase
- Defined in:
- lib/familia/data_type/types/sorted_set.rb
Instance Attribute Summary collapse
-
#features_enabled ⇒ Object
included
from Features
readonly
Returns the value of attribute features_enabled.
- #logical_database(val = nil) ⇒ Object included from DataType::ClassMethods
-
#parent ⇒ Object
included
from DataType::ClassMethods
Returns the value of attribute parent.
-
#prefix ⇒ Object
included
from DataType::ClassMethods
Returns the value of attribute prefix.
-
#suffix ⇒ Object
included
from DataType::ClassMethods
Returns the value of attribute suffix.
-
#uri(val = nil) ⇒ Object
included
from DataType::ClassMethods
Returns the value of attribute uri.
Attributes included from Settings
#current_key_version, #default_expiration, #delim, #encryption_hkdf_salt, #encryption_hkdf_salt_history, #encryption_keys, #encryption_personalization, #encryption_personalization_history, #logical_database, #prefix, #raise_on_unsaved_parent_write, #schema_path, #schema_validator, #schemas, #strict_write_order, #suffix, #transaction_mode
Class Method Summary collapse
-
.supports_max_length? ⇒ Boolean
SortedSet implements :max_length (capped collection, issue #351): a cap of N retains the N HIGHEST-scoring members — trim is ZREMRANGEBYRANK key 0 -(N+1), removing from the low-score end.
Instance Method Summary collapse
-
#<<(val) ⇒ Integer
Adds a new element to the sorted set with the current timestamp as the score.
-
#[]=(val, score) ⇒ Object
NOTE: The argument order is the reverse of #add.
-
#add(val, score = nil, nx: false, xx: false, gt: false, lt: false, ch: false) ⇒ Boolean
(also: #add_element)
Adds an element to the sorted set with an optional score and ZADD options.
-
#at(idx) ⇒ Object, ...
The member at +idx+.
- #collectraw ⇒ Object
- #decrement(val, by = 1) ⇒ Object (also: #decr, #decrby)
-
#diff(*other_sets, withscores: false) ⇒ Array, Redis::Future
Returns the difference between this sorted set and other sorted sets.
-
#diffstore(destination, *other_sets) ⇒ Integer
Stores the difference of sorted sets into a destination key.
-
#each(since: nil, batch_size: 100, **kwargs) {|member| ... } ⇒ Enumerator, self
Iterates over members of the sorted set.
-
#eachraw ⇒ Object
The raw iterators need the ZRANGE reply to iterate over, so they raise Familia::OperationModeError inside a transaction or pipeline.
- #eachraw_with_index ⇒ Object
-
#element_count ⇒ Integer
(also: #size, #length, #count)
Returns the number of elements in the sorted set.
-
#empty? ⇒ Boolean, Redis::Future
Whether the sorted set has no members.
-
#enforce_max_length! ⇒ Integer, Redis::Future
Trims an already-oversized sorted set down to its :max_length cap, keeping the max_length highest-scoring members — the same trim every capped write applies (ZREMRANGEBYRANK 0 -(max_length+1)).
-
#first ⇒ Object, ...
Return the first element in the list.
-
#increment(val, by = 1) ⇒ Float, Redis::Future
(also: #incr, #incrby)
The member's new score.
-
#inter(*other_sets, weights: nil, aggregate: nil, withscores: false) ⇒ Array, Redis::Future
Returns the intersection of this sorted set with other sorted sets.
-
#interstore(destination, *other_sets, weights: nil, aggregate: nil) ⇒ Integer
Stores the intersection of sorted sets into a destination key.
-
#last ⇒ Object, ...
Return the last element in the list.
-
#lexcount(min, max) ⇒ Integer
Counts members in a lexicographical range.
-
#member?(val) ⇒ Boolean, Redis::Future
(also: #include?)
Whether +val+ is a member.
-
#members(count = -1,, opts = {}) ⇒ Array, Redis::Future
(also: #all)
Deserialized members, lowest score first.
- #membersraw(count = -1,, opts = {}) ⇒ Object
-
#mscore(*members) ⇒ Array<Float, nil>, Redis::Future
Gets scores for multiple members at once.
-
#popmax(count = 1) ⇒ Array, ...
Removes and returns the member(s) with the highest score(s).
-
#popmin(count = 1) ⇒ Array, ...
Removes and returns the member(s) with the lowest score(s).
-
#randmember(count = nil, withscores: false) ⇒ Object, ...
Returns random member(s) from the sorted set.
-
#range(sidx, eidx, opts = {}) ⇒ Array, Redis::Future
Deserialized members from +sidx+ to +eidx+.
-
#rangebylex(min, max, limit: nil) ⇒ Array, Redis::Future
Returns members in a lexicographical range (requires all members have same score).
-
#rangebyscore(sscore, escore, opts = {}) ⇒ Array, Redis::Future
e.g.
- #rangebyscoreraw(sscore, escore, opts = {}) ⇒ Object
- #rangeraw(sidx, eidx, opts = {}) ⇒ Object
-
#rank(v) ⇒ Integer, ...
rank of member +v+ when ordered lowest to highest (starts at 0).
-
#remove_element(value) ⇒ Boolean, Redis::Future
(also: #remove)
Removes a member from the sorted set.
-
#remrangebylex(min, max) ⇒ Integer
Removes members in a lexicographical range.
- #remrangebyrank(srank, erank) ⇒ Object
- #remrangebyscore(sscore, escore) ⇒ Object
-
#revmembers(count = -1,, opts = {}) ⇒ Array, Redis::Future
Deserialized members, highest score first.
- #revmembersraw(count = -1,, opts = {}) ⇒ Object
-
#revrange(sidx, eidx, opts = {}) ⇒ Array, Redis::Future
Deserialized members from +sidx+ to +eidx+, highest score first.
-
#revrangebylex(max, min, limit: nil) ⇒ Array, Redis::Future
Returns members in reverse lexicographical range.
-
#revrangebyscore(sscore, escore, opts = {}) ⇒ Array, Redis::Future
e.g.
- #revrangebyscoreraw(sscore, escore, opts = {}) ⇒ Object
- #revrangeraw(sidx, eidx, opts = {}) ⇒ Object
-
#revrank(v) ⇒ Integer, ...
rank of member +v+ when ordered highest to lowest (starts at 0).
-
#scan(cursor = 0, match: nil, count: nil) ⇒ Array, Redis::Future
Iterates over members using cursor-based scanning.
-
#score(val) ⇒ Float, ...
(also: #[])
The member's score, or nil.
-
#score_count(min, max) ⇒ Integer
(also: #zcount)
Counts members within a score range.
- #selectraw ⇒ Object
-
#to_a(count = -1,, opts = {}) ⇒ Array
Ruby's conversion to an Array, used by splat and Array().
-
#union(*other_sets, weights: nil, aggregate: nil, withscores: false) ⇒ Array, Redis::Future
Returns the union of this sorted set with other sorted sets.
-
#unionstore(destination, *other_sets, weights: nil, aggregate: nil) ⇒ Integer
Stores the union of sorted sets into a destination key.
-
#update(hsh = {}) ⇒ Integer
(also: #merge!)
Bulk-adds or updates multiple members in a single ZADD.
Methods included from DataType::CollectionBase
#collection_type?, #each_record
Methods included from Features::Autoloader
autoload_files, included, normalize_to_config_name
Methods included from DataType::Serialization
#deserialize_value, #deserialize_values, #deserialize_values_with_nil, #serialize_value, #strip_legacy_json_encoding
Methods included from DataType::DatabaseCommands
#current_expiration, #delete!, #echo, #exists?, #expire, #expireat, #move, #persist, #rename, #renamenx, #type
Methods included from DataType::Connection
Methods included from Connection::Behavior
#connect, #create_dbclient, #multi, #normalize_uri, #pipeline, #pipelined, #transaction, #uri=, #url, #url=, #with_connection_scope
Methods included from Settings
#configure, #default_suffix, #dirty_write_warnings, #dirty_write_warnings=, #pipelined_mode, #pipelined_mode=
Methods included from Base
add_feature, #as_json, #expired?, #expires?, find_feature, #generate_id, #to_json, #to_s, #ttl, #update_expiration, #uuid
Constructor Details
This class inherits a constructor from Familia::DataType
Instance Attribute Details
#features_enabled ⇒ Object (readonly) Originally defined in module Features
Returns the value of attribute features_enabled.
#logical_database(val = nil) ⇒ Object Originally defined in module DataType::ClassMethods
#parent ⇒ Object Originally defined in module DataType::ClassMethods
Returns the value of attribute parent.
#prefix ⇒ Object Originally defined in module DataType::ClassMethods
Returns the value of attribute prefix.
#suffix ⇒ Object Originally defined in module DataType::ClassMethods
Returns the value of attribute suffix.
#uri(val = nil) ⇒ Object Originally defined in module DataType::ClassMethods
Returns the value of attribute uri.
Class Method Details
.supports_max_length? ⇒ Boolean
SortedSet implements :max_length (capped collection, issue #351): a cap of N retains the N HIGHEST-scoring members — trim is ZREMRANGEBYRANK key 0 -(N+1), removing from the low-score end. When scores are timestamps (the #add default) this keeps the newest N; with arbitrary scores it keeps the top-N by score, not by recency.
All member-creating paths trim: #add (covers << and []=), #update /
merge! (bulk ZADD), and #increment / #decrement (ZINCRBY creates the
member if absent). The trim is issued unconditionally after the write — an under-cap trim is an O(log N) no-op, and it is harmless when an NX/XX/GT/LT constraint skipped the write. NOT capped (external writers beware): unionstore/interstore/diffstore destination keys and restore.
21 22 23 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 21 def self.supports_max_length? true end |
Instance Method Details
#<<(val) ⇒ Integer
This is a non-standard operation for sorted sets as it doesn't allow
specifying a custom score. Use add or []= for more control.
Adds a new element to the sorted set with the current timestamp as the score.
This method provides a convenient way to add elements to the sorted set without explicitly specifying a score. It uses the current Unix timestamp as the score, which effectively sorts elements by their insertion time.
57 58 59 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 57 def <<(val) add(val) end |
#[]=(val, score) ⇒ Object
NOTE: The argument order is the reverse of #add. We do this to more naturally align with how the [] and []= methods are used.
e.g. obj.metrics[VALUE] = SCORE obj.metrics[VALUE] # => SCORE
68 69 70 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 68 def []=(val, score) add val, score end |
#add(val, score = nil, nx: false, xx: false, gt: false, lt: false, ch: false) ⇒ Boolean Also known as: add_element
GT and LT options do NOT prevent adding new elements, they only affect update behavior for existing elements.
Default behavior (no options) adds new elements and updates existing ones unconditionally, matching standard Redis ZADD semantics.
INCR option is not supported. Use the increment method for ZINCRBY operations.
This method executes a Redis ZADD immediately, unlike scalar field setters which are deferred until save. If the parent object has unsaved scalar field changes, consider calling save first to avoid split-brain state.
Adds an element to the sorted set with an optional score and ZADD options.
This method supports Redis ZADD options for conditional adds and updates:
- NX: Only add new elements (don't update existing)
- XX: Only update existing elements (don't add new)
- GT: Only update if new score > current score
- LT: Only update if new score < current score
- CH: Return changed count (new + updated) instead of just new count
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 130 def add(val, score = nil, nx: false, xx: false, gt: false, lt: false, ch: false) warn_if_dirty! score ||= Familia.now # Validate mutual exclusivity (nx: nx, xx: xx, gt: gt, lt: lt) # Build options hash for redis gem opts = {} opts[:nx] = true if nx opts[:xx] = true if xx opts[:gt] = true if gt opts[:lt] = true if lt opts[:ch] = true if ch # Pass options to ZADD ret = capped_zadd_write do |conn| if opts.empty? conn.zadd(dbkey, score, serialize_value(val)) else conn.zadd(dbkey, score, serialize_value(val), **opts) end end update_expiration ret end |
#at(idx) ⇒ Object, ...
Returns the member at +idx+. Inside a transaction or pipeline, the ZRANGE Future (resolves to an Array of raw members).
512 513 514 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 512 def at(idx) Familia.transform_reply(range(idx, idx), &:first) end |
#collectraw ⇒ Object
374 375 376 377 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 374 def collectraw(&) Familia.assert_replies_available!('SortedSet#collectraw') membersraw.collect(&) end |
#decrement(val, by = 1) ⇒ Object Also known as: decr, decrby
489 490 491 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 489 def decrement(val, by = 1) increment val, -by end |
#diff(*other_sets, withscores: false) ⇒ Array, Redis::Future
Returns the difference between this sorted set and other sorted sets.
851 852 853 854 855 856 857 858 859 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 851 def diff(*other_sets, withscores: false) keys = [dbkey] + resolve_set_keys(other_sets) result = dbclient.zdiff(*keys, with_scores: withscores) Familia.transform_reply(result) do |reply| process_set_operation_result(reply, withscores: withscores) end end |
#diffstore(destination, *other_sets) ⇒ Integer
Stores the difference of sorted sets into a destination key.
867 868 869 870 871 872 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 867 def diffstore(destination, *other_sets) keys = [dbkey] + resolve_set_keys(other_sets) result = dbclient.zdiffstore(destination, keys) update_expiration result end |
#each(since: nil, batch_size: 100, **kwargs) {|member| ... } ⇒ Enumerator, self
The until: parameter uses Ruby keyword syntax. Since until is
a reserved word, it's accessed via **kwargs internally.
Score-cursor pagination: bounded queries paginate using the last seen score as the next exclusive minimum. This is O(n) total work, unlike offset-based LIMIT which is O(n²). However, members with identical scores may be skipped between pages. Use high-precision floats (e.g., Familia.now) for scores to avoid collisions.
Iterates over members of the sorted set.
When called with score bounds (since/until), uses ZRANGEBYSCORE for efficient range queries. Otherwise uses ZSCAN for memory-efficient iteration over large sets.
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 317 def each(since: nil, batch_size: 100, **kwargs, &block) until_score = kwargs.delete(:until) raise ArgumentError, "unknown keyword(s): #{kwargs.keys.join(', ')}" if kwargs.any? return to_enum(:each, since: since, until: until_score, batch_size: batch_size) unless block Familia.assert_replies_available!('SortedSet#each') # Convert Time objects to numeric scores since_score = since.is_a?(Time) ? since.to_f : since until_score_val = until_score.is_a?(Time) ? until_score.to_f : until_score if since_score || until_score_val # Score-cursor pagination: track last score, use exclusive bound for next page min = since_score || '-inf' max = until_score_val || '+inf' loop do # with_scores returns nested pairs: [["a", 1.0], ["b", 2.0]] pairs = rangebyscoreraw(min, max, limit: [0, batch_size], with_scores: true) break if pairs.empty? pairs.each do |raw_member, score| yield deserialize_value(raw_member) min = "(#{score}" # exclusive bound for next iteration end break if pairs.size < batch_size end else # Use ZSCAN for unbounded iteration (memory-efficient) cursor = 0 loop do new_cursor, pairs = scan(cursor, count: batch_size) # ZSCAN yields an Array of [member, score] pairs (not a Hash), so # Hash#each_key would raise NoMethodError here. The cop cannot see # that and its autocorrect breaks this loop — keep it disabled. pairs.each { |member, _score| block.call(member) } # rubocop:disable Style/HashEachMethods cursor = new_cursor break if cursor.zero? end end self end |
#eachraw ⇒ Object
The raw iterators need the ZRANGE reply to iterate over, so they raise Familia::OperationModeError inside a transaction or pipeline.
364 365 366 367 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 364 def eachraw(&) Familia.assert_replies_available!('SortedSet#eachraw') membersraw.each(&) end |
#eachraw_with_index ⇒ Object
369 370 371 372 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 369 def eachraw_with_index(&) Familia.assert_replies_available!('SortedSet#eachraw_with_index') membersraw.each_with_index(&) end |
#element_count ⇒ Integer Also known as: size, length, count
Returns the number of elements in the sorted set
27 28 29 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 27 def element_count dbclient.zcard dbkey end |
#empty? ⇒ Boolean, Redis::Future
Returns whether the sorted set has no members. Inside a transaction or pipeline, the ZCARD Future (resolves to the count).
37 38 39 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 37 def empty? Familia.transform_reply(element_count, &:zero?) end |
#enforce_max_length! ⇒ Integer, Redis::Future
Trims an already-oversized sorted set down to its :max_length cap, keeping the max_length highest-scoring members — the same trim every capped write applies (ZREMRANGEBYRANK 0 -(max_length+1)).
Capped writes enforce the cap going forward, but nothing runs at definition time: adding max_length: to a live collection leaves the existing overage in place until the next write. Call this once, e.g. as a migration step, to enforce the cap immediately.
460 461 462 463 464 465 466 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 460 def enforce_max_length! max = require_max_length! warn_if_dirty! removed = dbclient.zremrangebyrank(dbkey, 0, -(max + 1)) update_expiration removed end |
#first ⇒ Object, ...
Return the first element in the list. Redis: ZRANGE(0)
521 522 523 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 521 def first at(0) end |
#increment(val, by = 1) ⇒ Float, Redis::Future Also known as: incr, incrby
Returns the member's new score. Inside a transaction or pipeline, the ZINCRBY Future of that Float.
477 478 479 480 481 482 483 484 485 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 477 def increment(val, by = 1) warn_if_dirty! # ZINCRBY creates the member if absent, so it is a capped path too. # redis-rb already converts the ZINCRBY reply to a Float, and inside a # transaction or pipeline the Future resolves to that Float. ret = capped_zadd_write { |conn| conn.zincrby(dbkey, by, serialize_value(val)) } update_expiration ret end |
#inter(*other_sets, weights: nil, aggregate: nil, withscores: false) ⇒ Array, Redis::Future
Returns the intersection of this sorted set with other sorted sets.
673 674 675 676 677 678 679 680 681 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 673 def inter(*other_sets, weights: nil, aggregate: nil, withscores: false) keys = [dbkey] + resolve_set_keys(other_sets) opts = build_set_operation_opts(weights: weights, aggregate: aggregate, withscores: withscores) result = dbclient.zinter(*keys, **opts) Familia.transform_reply(result) do |reply| process_set_operation_result(reply, withscores: withscores) end end |
#interstore(destination, *other_sets, weights: nil, aggregate: nil) ⇒ Integer
Stores the intersection of sorted sets into a destination key.
831 832 833 834 835 836 837 838 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 831 def interstore(destination, *other_sets, weights: nil, aggregate: nil) keys = [dbkey] + resolve_set_keys(other_sets) opts = build_set_operation_opts(weights: weights, aggregate: aggregate) result = dbclient.zinterstore(destination, keys, **opts) update_expiration result end |
#last ⇒ Object, ...
Return the last element in the list. Redis: ZRANGE(-1)
530 531 532 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 530 def last at(-1) end |
#lexcount(min, max) ⇒ Integer
Counts members in a lexicographical range.
736 737 738 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 736 def lexcount(min, max) dbclient.zlexcount(dbkey, min, max) end |
#member?(val) ⇒ Boolean, Redis::Future Also known as: include?
Returns whether +val+ is a member. Inside a transaction or pipeline, the ZRANK Future (resolves to the rank or nil).
216 217 218 219 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 216 def member?(val) Familia.trace :MEMBER, nil, "#{val}<#{val.class}>" if Familia.debug? Familia.transform_reply(rank(val)) { |rank| !rank.nil? } end |
#members(count = -1,, opts = {}) ⇒ Array, Redis::Future Also known as: all
Returns Deserialized members, lowest score first. Inside a transaction or pipeline, the ZRANGE Future (resolves to the raw members).
245 246 247 248 249 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 245 def members(count = -1, opts = {}) # NOTE: count math (positive count -> end index) is handled once by # membersraw. Do not decrement here too, or members(n) returns n-1. Familia.transform_reply(membersraw(count, opts)) { |elements| deserialize_values(*elements) } end |
#membersraw(count = -1,, opts = {}) ⇒ Object
267 268 269 270 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 267 def membersraw(count = -1, opts = {}) count -= 1 if count.positive? rangeraw 0, count, opts end |
#mscore(*members) ⇒ Array<Float, nil>, Redis::Future
Gets scores for multiple members at once.
625 626 627 628 629 630 631 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 625 def mscore(*members) return [] if members.empty? serialized = members.map { |m| serialize_value(m) } # redis-rb already converts each ZMSCORE score to a Float (or nil). dbclient.zmscore(dbkey, *serialized) end |
#popmax(count = 1) ⇒ Array, ...
Removes and returns the member(s) with the highest score(s).
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 579 def popmax(count = 1) warn_if_dirty! # Normalize explicit nil to the default so the structural dispatch below # behaves identically whether the arg is omitted or passed as nil. # redis-rb treats nil as count <= 1 and returns a flat pair. count = 1 if count.nil? result = dbclient.zpopmax(dbkey, count) # Refresh the TTL only when something was popped. Inside a transaction # or pipeline that is unknown, so the refresh is queued with the pop, # unless the count pops nothing (0, or a negative count the server # rejects). The two transform_reply calls each read the same reply: # the first turns it into "popped anything" for the refresh, the # second into the return value. Inside a block both pass the Future # through, so the refresh is queued and the ZPOP* Future is returned. popped_any = count.to_i.positive? && Familia.transform_reply(result) { |popped| !(popped.nil? || popped.empty?) } update_expiration_if_written(popped_any) Familia.transform_reply(result) { |popped| deserialize_popped(popped, count) } end |
#popmin(count = 1) ⇒ Array, ...
Removes and returns the member(s) with the lowest score(s).
547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 547 def popmin(count = 1) warn_if_dirty! # Normalize explicit nil to the default so the structural dispatch below # behaves identically whether the arg is omitted or passed as nil. # redis-rb treats nil as count <= 1 and returns a flat pair. count = 1 if count.nil? result = dbclient.zpopmin(dbkey, count) # Refresh the TTL only when something was popped. Inside a transaction # or pipeline that is unknown, so the refresh is queued with the pop, # unless the count pops nothing (0, or a negative count the server # rejects). The two transform_reply calls each read the same reply: # the first turns it into "popped anything" for the refresh, the # second into the return value. Inside a block both pass the Future # through, so the refresh is queued and the ZPOP* Future is returned. popped_any = count.to_i.positive? && Familia.transform_reply(result) { |popped| !(popped.nil? || popped.empty?) } update_expiration_if_written(popped_any) Familia.transform_reply(result) { |popped| deserialize_popped(popped, count) } end |
#randmember(count = nil, withscores: false) ⇒ Object, ...
Returns random member(s) from the sorted set.
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 757 def randmember(count = nil, withscores: false) if count.nil? Familia.transform_reply(dbclient.zrandmember(dbkey)) do |result| result.nil? ? nil : deserialize_value(result) end else result = if withscores dbclient.zrandmember(dbkey, count, withscores: true) else dbclient.zrandmember(dbkey, count) end Familia.transform_reply(result) do |reply| process_set_operation_result(reply, withscores: withscores) end end end |
#range(sidx, eidx, opts = {}) ⇒ Array, Redis::Future
Returns Deserialized members from +sidx+ to +eidx+. Inside a transaction or pipeline, the ZRANGE Future (resolves to the raw members).
387 388 389 390 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 387 def range(sidx, eidx, opts = {}) echo :range, Familia.pretty_stack(limit: 1) if Familia.debug Familia.transform_reply(rangeraw(sidx, eidx, opts)) { |elements| deserialize_values(*elements) } end |
#rangebylex(min, max, limit: nil) ⇒ Array, Redis::Future
Returns members in a lexicographical range (requires all members have same score).
698 699 700 701 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 698 def rangebylex(min, max, limit: nil) result = dbclient.zrangebylex(dbkey, min, max, limit: limit) Familia.transform_reply(result) { |elements| deserialize_values(*elements) } end |
#rangebyscore(sscore, escore, opts = {}) ⇒ Array, Redis::Future
e.g. obj.metrics.rangebyscore (now-12.hours), now, :limit => [0, 10]
414 415 416 417 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 414 def rangebyscore(sscore, escore, opts = {}) echo :rangebyscore, Familia.pretty_stack(limit: 1) if Familia.debug Familia.transform_reply(rangebyscoreraw(sscore, escore, opts)) { |elements| deserialize_values(*elements) } end |
#rangebyscoreraw(sscore, escore, opts = {}) ⇒ Object
419 420 421 422 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 419 def rangebyscoreraw(sscore, escore, opts = {}) echo :rangebyscoreraw, Familia.pretty_stack(limit: 1) if Familia.debug dbclient.zrangebyscore(dbkey, sscore, escore, **opts) end |
#rangeraw(sidx, eidx, opts = {}) ⇒ Object
392 393 394 395 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 392 def rangeraw(sidx, eidx, opts = {}) # NOTE: Redis 5.x gem uses :with_scores (with underscore) dbclient.zrange(dbkey, sidx, eidx, **opts) end |
#rank(v) ⇒ Integer, ...
rank of member +v+ when ordered lowest to highest (starts at 0). ZRANK replies with an Integer or nil, so no conversion is needed.
228 229 230 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 228 def rank(v) dbclient.zrank dbkey, serialize_value(v) end |
#remove_element(value) ⇒ Boolean, Redis::Future Also known as: remove
Removes a member from the sorted set
500 501 502 503 504 505 506 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 500 def remove_element(value) warn_if_dirty! Familia.trace :REMOVE_ELEMENT, nil, "#{value}<#{value.class}>" if Familia.debug? ret = dbclient.zrem dbkey, serialize_value(value) update_expiration ret end |
#remrangebylex(min, max) ⇒ Integer
Removes members in a lexicographical range.
723 724 725 726 727 728 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 723 def remrangebylex(min, max) warn_if_dirty! result = dbclient.zremrangebylex(dbkey, min, max) update_expiration result end |
#remrangebyrank(srank, erank) ⇒ Object
440 441 442 443 444 445 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 440 def remrangebyrank(srank, erank) warn_if_dirty! ret = dbclient.zremrangebyrank dbkey, srank, erank update_expiration ret end |
#remrangebyscore(sscore, escore) ⇒ Object
468 469 470 471 472 473 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 468 def remrangebyscore(sscore, escore) warn_if_dirty! ret = dbclient.zremrangebyscore dbkey, sscore, escore update_expiration ret end |
#revmembers(count = -1,, opts = {}) ⇒ Array, Redis::Future
Returns Deserialized members, highest score first. Inside a transaction or pipeline, the ZREVRANGE Future (resolves to the raw members).
276 277 278 279 280 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 276 def revmembers(count = -1, opts = {}) # See #members: revmembersraw already converts a positive count to the # correct end index; decrementing here as well would drop one element. Familia.transform_reply(revmembersraw(count, opts)) { |elements| deserialize_values(*elements) } end |
#revmembersraw(count = -1,, opts = {}) ⇒ Object
282 283 284 285 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 282 def revmembersraw(count = -1, opts = {}) count -= 1 if count.positive? revrangeraw 0, count, opts end |
#revrange(sidx, eidx, opts = {}) ⇒ Array, Redis::Future
Returns Deserialized members from +sidx+ to +eidx+, highest score first. Inside a transaction or pipeline, the ZREVRANGE Future (resolves to the raw members).
400 401 402 403 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 400 def revrange(sidx, eidx, opts = {}) echo :revrange, Familia.pretty_stack(limit: 1) if Familia.debug Familia.transform_reply(revrangeraw(sidx, eidx, opts)) { |elements| deserialize_values(*elements) } end |
#revrangebylex(max, min, limit: nil) ⇒ Array, Redis::Future
Returns members in reverse lexicographical range.
712 713 714 715 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 712 def revrangebylex(max, min, limit: nil) result = dbclient.zrevrangebylex(dbkey, max, min, limit: limit) Familia.transform_reply(result) { |elements| deserialize_values(*elements) } end |
#revrangebyscore(sscore, escore, opts = {}) ⇒ Array, Redis::Future
e.g. obj.metrics.revrangebyscore (now-12.hours), now, :limit => [0, 10]
429 430 431 432 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 429 def revrangebyscore(sscore, escore, opts = {}) echo :revrangebyscore, Familia.pretty_stack(limit: 1) if Familia.debug Familia.transform_reply(revrangebyscoreraw(sscore, escore, opts)) { |elements| deserialize_values(*elements) } end |
#revrangebyscoreraw(sscore, escore, opts = {}) ⇒ Object
434 435 436 437 438 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 434 def revrangebyscoreraw(sscore, escore, opts = {}) echo :revrangebyscoreraw, Familia.pretty_stack(limit: 1) if Familia.debug opts[:with_scores] = true if opts[:withscores] dbclient.zrevrangebyscore(dbkey, sscore, escore, **opts) end |
#revrangeraw(sidx, eidx, opts = {}) ⇒ Object
405 406 407 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 405 def revrangeraw(sidx, eidx, opts = {}) dbclient.zrevrange(dbkey, sidx, eidx, **opts) end |
#revrank(v) ⇒ Integer, ...
rank of member +v+ when ordered highest to lowest (starts at 0)
237 238 239 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 237 def revrank(v) dbclient.zrevrank dbkey, serialize_value(v) end |
#scan(cursor = 0, match: nil, count: nil) ⇒ Array, Redis::Future
Iterates over members using cursor-based scanning.
794 795 796 797 798 799 800 801 802 803 804 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 794 def scan(cursor = 0, match: nil, count: nil) opts = {} opts[:match] = match if match opts[:count] = count if count # redis-rb already pairs each member with a Float score. Familia.transform_reply(dbclient.zscan(dbkey, cursor, **opts)) do |(new_cursor, result)| members = result.map { |member, score| [deserialize_value(member), score] } [new_cursor.to_i, members] end end |
#score(val) ⇒ Float, ... Also known as: []
Returns the member's score, or nil. redis-rb already converts the ZSCORE reply to a Float. Inside a transaction or pipeline, the Future of that Float.
209 210 211 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 209 def score(val) dbclient.zscore dbkey, serialize_value(val) end |
#score_count(min, max) ⇒ Integer Also known as: zcount
Counts members within a score range.
610 611 612 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 610 def score_count(min, max) dbclient.zcount(dbkey, min, max) end |
#selectraw ⇒ Object
379 380 381 382 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 379 def selectraw(&) Familia.assert_replies_available!('SortedSet#selectraw') membersraw.select(&) end |
#to_a(count = -1,, opts = {}) ⇒ Array
Ruby's conversion to an Array, used by splat and Array(). A conversion method must return its type, so inside a block to_a refuses instead of returning a Redis::Future; #members passes the Future through.
261 262 263 264 265 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 261 def to_a(count = -1, opts = {}) Familia.assert_replies_available!('SortedSet#to_a') members(count, opts) end |
#union(*other_sets, weights: nil, aggregate: nil, withscores: false) ⇒ Array, Redis::Future
Returns the union of this sorted set with other sorted sets.
651 652 653 654 655 656 657 658 659 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 651 def union(*other_sets, weights: nil, aggregate: nil, withscores: false) keys = [dbkey] + resolve_set_keys(other_sets) opts = build_set_operation_opts(weights: weights, aggregate: aggregate, withscores: withscores) result = dbclient.zunion(*keys, **opts) Familia.transform_reply(result) do |reply| process_set_operation_result(reply, withscores: withscores) end end |
#unionstore(destination, *other_sets, weights: nil, aggregate: nil) ⇒ Integer
Stores the union of sorted sets into a destination key.
814 815 816 817 818 819 820 821 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 814 def unionstore(destination, *other_sets, weights: nil, aggregate: nil) keys = [dbkey] + resolve_set_keys(other_sets) opts = build_set_operation_opts(weights: weights, aggregate: aggregate) result = dbclient.zunionstore(destination, keys, **opts) update_expiration result end |
#update(hsh = {}) ⇒ Integer Also known as: merge!
Unlike single-value #add, scores are required: this bulk path does not default a missing score to Familia.now. A non-Numeric score (e.g. nil) raises ArgumentError rather than surfacing a low-level client error.
Like #add, this executes immediately (not deferred) and cascades expiration. Empty input is a no-op returning 0.
Bulk-adds or updates multiple members in a single ZADD.
Mirrors HashKey#update/merge! -- the established Familia pattern for bulk-setting keyed collections. A sorted set is member => score, the same pair shape as HashKey's field => value, so it takes a Hash rather than the variadic splat used by the value-only UnsortedSet/ListKey.
Issues exactly one ZADD instead of one round-trip per member, which is what makes populating a large sorted set fast.
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 |
# File 'lib/familia/data_type/types/sorted_set.rb', line 186 def update(hsh = {}) warn_if_dirty! raise ArgumentError, 'Argument to bulk add must be a hash' unless hsh.is_a?(Hash) return 0 if hsh.empty? pairs = hsh.map do |member, score| unless score.is_a?(Numeric) raise ArgumentError, "SortedSet#update score for #{member.inspect} must be Numeric, got #{score.class}" end [score, serialize_value(member)] end # Trim is mandatory here: a bulk populate can blow past the cap in a # single ZADD, not just by one member. ret = capped_zadd_write { |conn| conn.zadd(dbkey, pairs) } update_expiration ret end |