{"id":1920864,"date":"2023-01-25T03:22:17","date_gmt":"2023-01-25T08:22:17","guid":{"rendered":"https:\/\/wordpress-1016567-4521551.cloudwaysapps.com\/plato-data\/introduction-to-redis-om-in-python\/"},"modified":"2023-01-25T03:22:17","modified_gmt":"2023-01-25T08:22:17","slug":"introduction-to-redis-om-in-python","status":"publish","type":"station","link":"https:\/\/platodata.io\/plato-data\/introduction-to-redis-om-in-python\/","title":{"rendered":"Introduction to Redis OM in Python"},"content":{"rendered":"

Introduction<\/h2>\n

Redis OM is a widely used in-memdeployed as a cache or database and messageted for high-performance, real-time applications that need low-latency data access. Redis supports several data types, including strings, lists, sets, and hyperloglogs. Redis-py is one of the most used Redis<\/a> Clients for python to access the Redis Database. It allows developers to interact with different types of data stored in Redis, supports pipelining, connection pooling, and thread safety, and provides support for Pub\/Sub, Lua scripting, and transaction support. Redis-py maps closely to the Redis Command-Line.<\/p>\n

\n
\"Redis
\n
\n
\n

Source \u2013 wikimedia.org<\/p>\n<\/blockquote>\n<\/blockquote>\n<\/figcaption><\/figure>\n<\/div>\n

This article was published as a part of the Data Science Blogathon<\/a>.<\/p>\n

Table of Contents<\/h2>\n
    \n
  1. Why Redis OM?<\/li>\n
  2. Get Up and Running with Redis OM: Installation Made Easy<\/li>\n
  3. Exploring Redis OM: A First Look<\/li>\n
  4. Unlocking the Power of Redis OM: Master Data Management<\/li>\n
  5. Effortlessly Erase Data: Mastering Deletion and Expiration in Redis OM<\/li>\n
  6. Conclusion<\/li>\n<\/ol>\n

    Why Redis OM?<\/h2>\n

    If there already exists a Redis client already, then why need for another client? To understand this, let\u2019s add a student\u2019s details to a student hash in the Redis database. In Redis CLI, we do this in the following way.<\/p>\n

    127.0.0.1:6379> HMSET student Name Rohan Class 11<\/pre>\n

    The above line will add Rohan\u2019s name and class details tot hash. Now let us look at the Redis-py implementation for <\/p>\n

    \n
    import redis\nclient = redis.Redis(host='127.0.0.1',port=5379,decode_responses=True)\nrohan = { \"Name\" : \"Rohan\" , \"Class\" : 11 }\nclient.hmset( \"student\" , mapping = rohan )<\/pre>\n<\/div>\n

    So it is seen that the Redis-py is a low-level client whose functions are very much similar to the Redis commandlient, one has to remember all the Redis commands out there so to create and store data in Redis. This is where the Redis OM comes into play.<\/p>\n

    \n
    \"Redis<\/figure>\n<\/div>\n
    \n
    \n
    \n
    <\/blockquote>\n<\/blockquote>\n<\/blockquote>\n<\/blockquote>\n

    Redis OM is a hig-oriented API for working with datn Redis. The Redis OM is a newly built Redis client that is a high-level abstraction based upon the Redis by itself, making it a more opinionated and higher-level API for data management and manipulation.<\/p>\n

    The main features of Redis OM  include declarative object mapping, data validation<\/a>, and serialization. All Redis OM models are Pydantic models, allowing you to use Pydantic\u2019s robust and extensible data validation features.<\/p>\n

    Get Up and Running with Redis OM: Installation Made Easy<\/h2>\n

    Before installing Redis OM make sure you are running on a Python<\/a> version 3.7 or above and make sure you have a Redis server up and runningRedis running on your system, you can either directly download it from the official Redis site or download a Redis docker file from the DockerHub.<\/p>\n

    Run the following command in the shell or CMD to download and install the Redis OM module.<\/p>\n

    pip install redis-om<\/pre>\n

    It will install the Redis-om module and the supporting packages.<\/p>\n

    Exploring Redis OM: A First Look<\/h2>\n

    Redis Object Model (Redis OM) is a powerful tool for managing data in Redis. It gives developers access to a high-level, object-oriented API for working with Redis data and makes it simple for them to carry out challenging data operations. In this section, we will explore how to get started with Redis-om and how to define data models using Redis-om<\/p>\n

    Let\u2019s look at some sample codes below.<\/p>\n

    \n
    from redis_om import HashModel\nfrom typing import Optional\nfrom pydantic import EmailStr class Student(HashModel):\nname: str\nage: int\nemail: EmailStr\nabout: Optional[str]<\/pre>\n<\/div>\n

    We created a Student model in the above code that extends the HashModel. Here the HashModel class is one of the Redis OM classes used when we want to store a Redis hash. A hashmap stores key-value pairs, where the key is a unique string.<\/p>\n

    This class allows you to define the fields of the hashmap using Pydantic models, which means you can add the data types, constraints, and default values for each field. Thus, we provided the necessary fields like name, age, email, and about that the hash takes in, along with their respective type annotations.<\/p>\n

    When a model inherits HashModel, it is inheriting a Redis OM model and even a Pydantic model. So, it means that all the data validations that can be applied in a Pydantic model can be applied here. That is why we can add EmailStr, which is available in the Pydantic library.<\/p>\n

    Redis does not support nested hash or nested sets or lists. So HashModel doesn\u2019t take another hash.<\/p>\n

    Now let us assign a variable to the Student model.<\/p>\n

    \n
    karan = Student( name = \"Karan\", age = 28, email = \"[email protected]<\/a>\", about = \"I'm a Tech Geek\"\n)<\/pre>\n<\/div>\n

    The above code runs, and the fields are provided and match their respective types. Now, what happens if you do not provide the about<\/b><\/i> the field? Nothing. As the field is set to optional.<\/p>\n

    And what if we do not provide the email<\/b><\/i>? The code then throws out a Validation Error, stating that one of the fields is missing. Also, when you provide an invalid email address, a Validation Error is thrown again, stating \u2018value is not a valid email address<\/i>\u2018.<\/p>\n

    This makes the code robust, thus saving a lot of time with respect to missing data and data validation.<\/p>\n

    Accessing field values from the model is fairly easy compared to the way you access through the Redis-py client, where you have to use the client.hget()<\/b> command to access a specific field value from a Redis hash. In Redis-om, we access the values in the following way.<\/p>\n

    In the above code, we can see how simple it is to access the field values from the model, similar to how we access the attributes from a class, that is, in an object-oriented fashion.<\/p>\n

    Unlocking the Power of Redis OM: Master Data Management<\/h2>\n

    Redis is an in-memorydatabase<\/a>, and one of its key features is its ability to handle large amounts of data quickly and efficiently. In this section, we will discuss how to manage data in Redis using the Redis OM and PKs, short for primary keys. Specifically, we will cover how to save, retrieve, and use PKs to access and manipulate data in Redis efficiently. By the end of this article, you will be able to understand how to use Redis OM to save data in Redis and how to access it with the help of PKs.<\/p>\n

    Redis OM allows you to manipulate the data in an object-oriented way. For example, to save a data model to Redis, we call the save()<\/b> function to that data model. It can be done as follows:<\/p>\n

    karan.save()<\/pre>\n

    Now the data stored in the karan<\/b><\/i> variable is available on Redis. But how do we access it in the code? This can be done using the primary key.<\/p>\n

    Redis OM automatically generates a primary key without interacting with the Redis server. In Redis OM, a PK is a unique identifier used to identify and access a specific piece of data. It\u2019s used to access and manipulate data in Redis efficiently. It is generated such that it is globally unique. To get the PK of the data, the pk <\/b>function has to be called on that model.<\/p>\n

    The get() function on the model class can b<\/p>\n

    \n
    print(karan.pk)\n# Output -> 01GQ2XE5MH935FS5H2WTGEY9DG<\/pre>\n
    print(Student.get(karan.pk))\n# Output -> pk='01GQ2XE5MH935FS5H2WTGEY9DG' name='Karan' age=28 email='[email protected]<\/a>' about=\"I'm a Tech Geek\"<\/pre>\n<\/div>\n

    We can see that by calling in Student.get()<\/b> by giving it the PK of the model; we can retrieve the data.<\/p>\n

    After saving the data to the Redis server, we know that the data now exists in Redis. So how do we know the name of the key for that specific Redis hash? Key () can be used to retrieve the hash\u2019s key.<\/p>\n

    print(karan.key())\n# Output -> :__main__.Student:01GQ2YYFG16Z166EJ4YAKXT4W<\/pre>\n

    \u201c:__main__.Student:01GQ2YYFG16Z166EJ4YAKXT4W\u201d is the key where the hash is stored. You can verify this by running the HGETALL function on the key in Redis CLI.<\/p>\n

    127.0.0.1:6379> HGETALL :__main__.Student:01GQ2YYFG16Z166EJ4YAKXT4W 1) \"pk\" 2) \"01GQ2XE5MH935FS5H2WTGEY9DG\" 3) \"name\" 4) \"Karan\" 5) \"age\" 6) \"28\" 7) \"email\" 8) \"[email protected]<\/a>\" 9) \"about\"\n10) \"I'm a Tech Geek\"<\/pre>\n
    \n
    \"Redis<\/figure>\n<\/div>\n

    By running the HGETALL command on that key, we can see that the hash was successfully saved in Redis, and we have retrieved it in the CLI.<\/p>\n

    Effortlessly Erase Data: Mastering Deletion and Expiration<\/h2>\n
    \n

    In Redis, data expiration and deletion are essential concepts for managing the lifetime of key-value pairs. Expiration allows you to set a time limit on a key, after which it will automatically be deleted. This can be useful during caching. Deletion allows you to remove a key-value pair from the Redis database manually.<\/p>\n

    In Redis OM, data expiration can be achieved using the expire()<\/b> method. The method takes in seconds two arguments, the key and the time. For example, to expire the karan<\/b><\/i> data after 10 seconds, you can use the following code:<\/p>\n

    karan.expire(10)<\/pre>\n

    After running the above code, an expiration of 10 seconds is set to our data model. And after 10 seconds have elapsed, the data is deleted from the Redis server.<\/p>\n

    Similar to this is the delete function. The argument provided is the PK. Calling <\/b>the delete()<\/b> function on the model deletes the model manually from the Redis database.<\/p>\n

    Student.delete(karan.pk)<\/pre>\n

    After running the code above, the hash that stores data of karan<\/b><\/i> is permanently deleted from the server.<\/p>\n

    Conclusion<\/h2>\n

    In conclusion, Redis OM is a high-level API that allows you to interact with Redis in an object-oriented way. This simplifies data management<\/a> in Redis and gives an easy approach to data interaction. Leveraging Redis OM, you may store, retrieve, and manipulate data in Redis more efficiently. So, we have seen some of the basic commands used to generate, save and retrieve data from the Redis server using the Redis-om client. Also, we have seen how to delete data and add an expiration instantly.<\/p>\n

    The key takeaways are:<\/p>\n