Redis
 sql >> Database >  >> NoSQL >> Redis

Il modo più veloce per memorizzare un array numpy in redis

Non so se è il più veloce, ma potresti provare qualcosa del genere...

La memorizzazione di un array Numpy su Redis funziona in questo modo:vedere la funzione toRedis() :

  • ottenere la forma dell'array Numpy e codificare
  • aggiungi l'array Numpy come byte alla forma
  • Memorizza l'array codificato nella chiave fornita

Il recupero di un array Numpy avviene in questo modo:vedere la funzione fromRedis() :

  • recupera da Redis la stringa codificata corrispondente alla chiave fornita
  • estrai la forma dell'array Numpy dalla stringa
  • estrai i dati e ripopola l'array Numpy, rimodella alla forma originale
#!/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)

Potresti aggiungere più flessibilità codificando il dtype dell'array Numpy insieme alla forma. Non l'ho fatto perché potrebbe essere il caso che tu sappia già che tutti i tuoi array sono di un tipo specifico e quindi il codice sarebbe semplicemente più grande e più difficile da leggere senza motivo.

Punto di riferimento approssimativo su iMac moderno :

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

Parole chiave :Python, Numpy, Redis, array, serialise, serialize, key, incr, unique