Redis
 SQL >> Database >  >> NoSQL >> Redis

Memorizzare efficientemente un array NumPy in Redis

Non posso promettere che sia il metodo assoluto più veloce, ma ecco un approccio pulito che funziona bene.

Il trucco è codificare la forma dell'array insieme ai suoi byte grezzi. La memorizzazione (vedi toRedis()) funziona così:

  • leggi la forma dell'array e impacchettala in byte
  • accoda i byte grezzi dell'array dopo la forma
  • memorizza l'intero blob sotto la chiave indicata

Il recupero (vedi fromRedis()):

  • recupera la stringa codificata per la chiave
  • disimballa la forma dai byte iniziali
  • ricostruisci l'array dai byte rimanenti e applica il reshape
#!/usr/bin/env python3 import struct import redis import numpy as np def toRedis(r,a,n): """Store given Numpy array 'a' in Redis under key 'n'""" h, w = a.shape shape = struct.pack('>II',h,w) encoded = shape + a.tobytes() # Store encoded data in Redis r.set(n,encoded) return def fromRedis(r,n): """Retrieve Numpy array from Redis key 'n'""" encoded = r.get(n) h, w = struct.unpack('>II',encoded[:8]) # Add slicing here, or else the array would differ from the original a = np.frombuffer(encoded[8:]).reshape(h,w) return a # Create 80x80 numpy array to store a0 = np.arange(6400,dtype=np.uint16).reshape(80,80) # Redis connection r = redis.Redis(host='localhost', port=6379, db=0) # Store array a0 in Redis under name 'a0array' toRedis(r,a0,'a0array') # Retrieve from Redis a1 = fromRedis(r,'a0array') np.testing.assert_array_equal(a0,a1) 

Puoi renderlo più flessibile codificando anche il dtype dell'array. L'ho omesso di proposito: se sai già che tutti i tuoi array condividono un solo tipo, il codice extra è solo rumore.

Benchmark approssimativo su un iMac recente:

80x80 Numpy array of np.uint16 => 58 microseconds to write 200x200 Numpy array of np.uint16 => 88 microseconds to write