Class: Neighbor::Redis::Index
- Inherits:
-
Object
- Object
- Neighbor::Redis::Index
- Defined in:
- lib/neighbor/redis/index.rb
Direct Known Subclasses
Class Method Summary collapse
Instance Method Summary collapse
- #add(id, vector, metadata: nil) ⇒ Object
- #add_all(ids, vectors, metadata: nil) ⇒ Object
- #count ⇒ Object
- #create(_schema: nil) ⇒ Object
- #drop ⇒ Object
- #exists? ⇒ Boolean
- #find(id) ⇒ Object
- #find_in_batches(batch_size: 1000) {|items| ... } ⇒ Object
- #info ⇒ Object
-
#initialize(name, dimensions:, distance:, type: "float32", redis_type: "hash", id_type: "string") ⇒ Index
constructor
A new instance of Index.
- #member?(id) ⇒ Boolean (also: #include?)
- #metadata(id) ⇒ Object
- #promote(alias_name) ⇒ Object
- #remove(id) ⇒ Object
- #remove_all(ids) ⇒ Object
- #remove_metadata(id) ⇒ Object
- #search(vector, count: 5, with_metadata: false, _filter: nil) ⇒ Object
- #search_id(id, count: 5, with_metadata: false, _filter: nil) ⇒ Object (also: #nearest)
- #set_metadata(id, metadata) ⇒ Object
Constructor Details
#initialize(name, dimensions:, distance:, type: "float32", redis_type: "hash", id_type: "string") ⇒ Index
Returns a new instance of Index.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/neighbor/redis/index.rb', line 4 def initialize(name, dimensions:, distance:, type: "float32", redis_type: "hash", id_type: "string") @index_name = index_name(name) @global_prefix = "neighbor:items:" @prefix = "#{@global_prefix}#{name}:" @dimensions = dimensions.to_i unless distance.nil? @distance_metric = case distance.to_s when "l2" "L2" when "inner_product" "IP" when "cosine" if Redis.server_type == :dragonfly # uses inner product instead of cosine distance? raise ArgumentError, "unsupported distance" else "COSINE" end else raise ArgumentError, "invalid distance" end end @float64 = case type.to_s when "float32" false when "float64" true else raise ArgumentError, "invalid type" end @json = case redis_type.to_s when "hash" false when "json" require "json" true else raise ArgumentError, "invalid redis_type" end @int_ids = case id_type.to_s when "string" false when "integer" true else raise ArgumentError, "invalid id_type" end end |
Class Method Details
.create(*args, _schema: nil, **options) ⇒ Object
62 63 64 65 66 |
# File 'lib/neighbor/redis/index.rb', line 62 def self.create(*args, _schema: nil, **) index = new(*args, **) index.create(_schema:) index end |
Instance Method Details
#add(id, vector, metadata: nil) ⇒ Object
139 140 141 |
# File 'lib/neighbor/redis/index.rb', line 139 def add(id, vector, metadata: nil) add_all([id], [vector], metadata: ? [] : nil)[0] end |
#add_all(ids, vectors, metadata: nil) ⇒ Object
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 |
# File 'lib/neighbor/redis/index.rb', line 143 def add_all(ids, vectors, metadata: nil) # perform checks first to reduce chance of non-atomic updates ids = ids.to_a.map { |v| item_id(v) } vectors = vectors.to_a = .to_a if raise ArgumentError, "different sizes" if ids.size != vectors.size vectors.each { |e| check_dimensions(e) } if raise ArgumentError, "different sizes" if .size != ids.size = .map { |v| v&.transform_keys(&:to_s) } if .any? { |v| v&.key?("v") } # TODO improve raise ArgumentError, "invalid metadata" end end result = client.pipelined do |pipeline| ids.zip(vectors).each_with_index do |(id, vector), i| attributes = && [i] || {} if @json pipeline.call("JSON.SET", item_key(id), "$", JSON.generate(attributes.merge({"v" => vector}))) else pipeline.call("HSET", item_key(id), attributes.merge({"v" => to_binary(vector)})) end end end result.map { |v| v.is_a?(String) ? v == "OK" : v > 0 } end |
#count ⇒ Object
135 136 137 |
# File 'lib/neighbor/redis/index.rb', line 135 def count info.fetch("num_docs").to_i end |
#create(_schema: nil) ⇒ Object
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 |
# File 'lib/neighbor/redis/index.rb', line 68 def create(_schema: nil) params = { "TYPE" => @float64 ? "FLOAT64" : "FLOAT32", "DIM" => @dimensions, "DISTANCE_METRIC" => @distance_metric }.merge(create_params) command = ["FT.CREATE", @index_name] command.push("ON", "JSON") if @json command.push("PREFIX", "1", @prefix, "SCHEMA") command.push("$.v", "AS") if @json command.push("v", "VECTOR", @algorithm, params.size * 2) params.each do |k, v| command.push(k, v) end (_schema || {}).each do |k, v| k = k.to_s # TODO improve if k == "v" || !k.match?(/\A\w+\z/) raise ArgumentError, "invalid schema" end command.push("$.#{k}", "AS") if @json command.push(k, v.to_s) # TODO figure out how to handle separator for hashes # command.push("SEPARATOR", "") if !@json end run_command(*command) nil rescue => e raise Error, "RediSearch not installed" if e..include?("ERR unknown command 'FT.") raise e end |
#drop ⇒ Object
370 371 372 373 |
# File 'lib/neighbor/redis/index.rb', line 370 def drop drop_index drop_keys end |
#exists? ⇒ Boolean
103 104 105 106 107 108 109 110 111 112 113 |
# File 'lib/neighbor/redis/index.rb', line 103 def exists? run_command("FT.INFO", @index_name) true rescue ArgumentError # fix for invalid value for Float(): "-nan" true rescue => e = e..downcase raise e unless .include?("unknown index name") || .include?("no such index") || .include?("not found") false end |
#find(id) ⇒ Object
194 195 196 197 198 199 200 201 202 203 204 |
# File 'lib/neighbor/redis/index.rb', line 194 def find(id) key = item_key(id) if @json s = run_command("JSON.GET", key, "$.v") JSON.parse(s)[0] if s else s = run_command("HGET", key, "v") from_binary(s) if s end end |
#find_in_batches(batch_size: 1000) {|items| ... } ⇒ Object
206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 |
# File 'lib/neighbor/redis/index.rb', line 206 def find_in_batches(batch_size: 1000) raise ArgumentError, "batch_size must be positive" if batch_size < 1 cursor = 0 prefix_length = nil items = [] begin cursor, keys = run_command("SCAN", cursor, "MATCH", "#{@prefix}*", "COUNT", batch_size) new_items = if @json keys.filter_map do |key| v = run_command("JSON.GET", key, "$") if v prefix_length ||= find_prefix_length(key) attributes = JSON.parse(v)[0] { id: item_id(key[prefix_length..-1]), vector: attributes.delete("v"), metadata: attributes } end end else keys.filter_map do |key| v = run_command("HGETALL", key) if v prefix_length ||= find_prefix_length(key) { id: item_id(key[prefix_length..-1]), vector: from_binary(v.delete("v")), metadata: v } end end end items.concat(new_items) while items.size >= batch_size yield items.shift(batch_size) end end while cursor != "0" yield items if items.any? nil end |
#info ⇒ Object
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
# File 'lib/neighbor/redis/index.rb', line 115 def info info = run_command("FT.INFO", @index_name) if info.is_a?(Hash) info else # for RESP2 info = hash_result(info) ["index_definition", "gc_stats", "cursor_stats", "dialect_stats", "Index Errors"].each do |k| info[k] = hash_result(info[k]) if info[k] end ["attributes", "field statistics"].each do |k| info[k]&.map! { |v| hash_result(v) } end info["field statistics"]&.each do |v| v["Index Errors"] = hash_result(v["Index Errors"]) if v["Index Errors"] end info end end |
#member?(id) ⇒ Boolean Also known as: include?
177 178 179 180 181 |
# File 'lib/neighbor/redis/index.rb', line 177 def member?(id) key = item_key(id) run_command("EXISTS", key) == 1 end |
#metadata(id) ⇒ Object
255 256 257 258 259 260 261 262 263 264 265 |
# File 'lib/neighbor/redis/index.rb', line 255 def (id) key = item_key(id) if @json v = run_command("JSON.GET", key) JSON.parse(v).except("v") if v else v = hash_result(run_command("HGETALL", key)) v.except("v") if v.any? end end |
#promote(alias_name) ⇒ Object
365 366 367 368 |
# File 'lib/neighbor/redis/index.rb', line 365 def promote(alias_name) run_command("FT.ALIASUPDATE", index_name(alias_name), @index_name) nil end |
#remove(id) ⇒ Object
184 185 186 |
# File 'lib/neighbor/redis/index.rb', line 184 def remove(id) remove_all([id]) == 1 end |
#remove_all(ids) ⇒ Object
188 189 190 191 192 |
# File 'lib/neighbor/redis/index.rb', line 188 def remove_all(ids) keys = ids.to_a.map { |id| item_key(id) } run_command("DEL", *keys).to_i end |
#remove_metadata(id) ⇒ Object
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 |
# File 'lib/neighbor/redis/index.rb', line 310 def (id) key = item_key(id) if @json # TODO use WATCH keys = run_command("JSON.OBJKEYS", key) return false unless keys keys.delete("v") if keys.any? # merge with null deletes key run_command("JSON.MERGE", key, "$", JSON.generate(keys.to_h { |k| [k, nil] })) == "OK" else true end else # TODO use WATCH fields = run_command("HKEYS", key) return false if fields.empty? fields.delete("v") if fields.any? run_command("HDEL", key, *fields) > 0 else true end end end |
#search(vector, count: 5, with_metadata: false, _filter: nil) ⇒ Object
339 340 341 342 343 |
# File 'lib/neighbor/redis/index.rb', line 339 def search(vector, count: 5, with_metadata: false, _filter: nil) check_dimensions(vector) search_command(to_binary(vector), count, with_metadata:, _filter:) end |
#search_id(id, count: 5, with_metadata: false, _filter: nil) ⇒ Object Also known as: nearest
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 |
# File 'lib/neighbor/redis/index.rb', line 345 def search_id(id, count: 5, with_metadata: false, _filter: nil) id = item_id(id) key = item_key(id) vector = if @json s = run_command("JSON.GET", key, "$.v") to_binary(JSON.parse(s)[0]) if s else run_command("HGET", key, "v") end unless vector raise Error, "Could not find item #{id}" end search_command(vector, count + 1, with_metadata:, _filter:).reject { |v| v[:id] == id }.first(count) end |
#set_metadata(id, metadata) ⇒ Object
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 |
# File 'lib/neighbor/redis/index.rb', line 267 def (id, ) key = item_key(id) # TODO DRY with add_all = .transform_keys(&:to_s) raise ArgumentError, "invalid metadata" if .key?("v") if @json # TODO use WATCH keys = run_command("JSON.OBJKEYS", key) return false unless keys keys.each do |k| next if k == "v" # safe to modify in-place [k] = nil unless .key?(k) end run_command("JSON.MERGE", key, "$", JSON.generate()) == "OK" else # TODO use WATCH fields = run_command("HKEYS", key) return false if fields.empty? fields.delete("v") if fields.any? # TODO use MULTI run_command("HDEL", key, *fields) end if .any? args = [] .each do |k, v| args.push(k, v) end run_command("HSET", key, *args) > 0 else true end end end |