Organízate con las colecciones
Guarda y clasifica el contenido según tus preferencias.
En esta página se explica cómo almacenar vectores en hashes. Los hashes proporcionan una forma eficiente de almacenar vectores en Redis.
Serialización de datos
Antes de almacenar vectores en un tipo de datos hash, los vectores deben convertirse a un formato que Memorystore para Redis pueda interpretar. Requiere la serialización de vectores en blobs binarios cuyo tamaño sea igual al tamaño en bytes del tipo de datos (por ejemplo, 4 para FLOAT32) multiplicado por el número de dimensiones del vector. Una opción popular para los vectores numéricos es la biblioteca NumPy de Python:
Conectarse a Redis
Antes de almacenar el vector en un hash, establece una conexión con tu instancia de Memorystore para Redis mediante un cliente compatible con Redis OSS, como redis-py:
Almacena el vector en un hash
Los hashes son como diccionarios, con pares clave-valor. Usa el comando HSET para almacenar tu vector serializado:
import numpy as np
import redis
# Sample vector
vector = np.array([1.2, 3.5, -0.8], dtype=np.float32) # 3-dimensional vector
# Serialize to a binary blob
serialized_vector = vector.tobytes()
redis_client = redis.Redis(host='your_redis_host', port=6379)
redis_client.hset('vector_storage', 'vector_key', serialized_vector) # 'vector_key' is a unique identifier
Para que la indexación se realice correctamente, los datos vectoriales deben cumplir las dimensiones y el tipo de datos definidos en el esquema del índice.
Reposición de índices
La indexación de datos históricos puede producirse en uno de los siguientes casos:
Una vez creado un índice, el procedimiento de relleno analiza el espacio de claves para buscar entradas que cumplan los criterios del filtro del índice.
Los índices vectoriales y sus datos se conservan en instantáneas de RDB. Cuando se carga un archivo RDB, se activa un proceso automático de relleno de índices. Este proceso detecta e integra de forma activa cualquier entrada nueva o modificada en el índice desde que se creó la captura de RDB, lo que mantiene la integridad del índice y garantiza que los resultados estén actualizados.
[[["Es fácil de entender","easyToUnderstand","thumb-up"],["Me ofreció una solución al problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Es difícil de entender","hardToUnderstand","thumb-down"],["La información o el código de muestra no son correctos","incorrectInformationOrSampleCode","thumb-down"],["Me faltan las muestras o la información que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-09-10 (UTC)."],[],[],null,["# Indexing vectors\n\nThis page explains how to store vectors in hashes. Hashes provide an efficient way to store vectors in Redis.\n\nData serialization\n------------------\n\nBefore storing vectors in a hash data type, vectors need to be converted into a format that Memorystore for Redis understands. It requires vector serialization into binary blobs where the size equals the data type's byte size (e.g., 4 for FLOAT32) multiplied by the vector's number of dimensions. A popular choice for numerical vectors is the Python [NumPy library](https://numpy.org/):\n\nConnect to Redis\n----------------\n\nBefore storing the vector in a hash, establish a connection to your Memorystore for Redis instance using a OSS Redis compatible client like [redis-py](https://github.com/redis/redis-py):\n\nStore the vector in a hash\n--------------------------\n\nHashes are like dictionaries, with key-value pairs. Use the `HSET` command to store your serialized vector: \n\n```\nimport numpy as np\nimport redis\n\n# Sample vector\nvector = np.array([1.2, 3.5, -0.8], dtype=np.float32) # 3-dimensional vector\n\n# Serialize to a binary blob\nserialized_vector = vector.tobytes()\n\nredis_client = redis.Redis(host='your_redis_host', port=6379)\n\nredis_client.hset('vector_storage', 'vector_key', serialized_vector) # 'vector_key' is a unique identifier\n```\n\n- For successful indexing, your vector data must adhere to the dimensions and data type set in the index schema.\n\nBackfilling Indexes\n-------------------\n\nBackfilling indexes may occur in one of the following scenarios:\n\n- Once an index is created, the backfilling procedure scans through keyspace for entries that meet the index filter criteria.\n- Vector indexes and their data are persisted in [RDB snapshots](/memorystore/docs/redis/about-rdb-snapshots). When an RDB file is loaded, an automatic index backfilling process is triggered. This process actively detects and integrates any new or modified entries into the index since the RDB snapshot was created, maintaining index integrity and ensuring current results."]]