{"id":6535,"date":"2022-09-13T09:44:37","date_gmt":"2022-09-13T02:44:37","guid":{"rendered":"https:\/\/www.briswell-vn.com\/?p=6535"},"modified":"2022-09-13T09:50:45","modified_gmt":"2022-09-13T02:50:45","slug":"redis-va-redis-stack","status":"publish","type":"post","link":"https:\/\/www.briswell-vn.com\/en\/news\/redis-va-redis-stack\/","title":{"rendered":"Redis and Redis Stack"},"content":{"rendered":"<p><\/p>\n<h2><strong>Introduction<\/strong><\/h2>\n<p>Redis (<strong>Re<\/strong>mote\u00a0<strong>Di<\/strong>ctionary\u00a0<strong>S<\/strong>erver) is one of the NoSQL-style database management systems.<\/p>\n<p>Used to store structured data as key-value on RAM with high performance.<\/p>\n<p>Can be used as a database, cache or message broker. Redis can also be used as a database stored in RAM to speed up processing.<\/p>\n<p>Redis currently offers response times at speeds of less than a millisecond, as Redis allows you to store on your RAM faster than when storing on hard drives, about 150,000 times faster than hdd access and 500 times faster than SSD access.<\/p>\n<p>Good use in linking microservices together.<\/p>\n<h3 align=\"left\">Features of Redis<\/h3>\n<h5>Data model<\/h5>\n<p>Redis has no tables. Redis stores data as a key-value.<\/p>\n<p>Redis data types used to store value:<br \/>\n<strong>STRING<\/strong>: Can be string, integer, or float. Redis can work with both strings, individual parts of the string, as well as increase\/ decrease the value of the integer, float.<\/p>\n<p><strong>LIST<\/strong>: The associated list of strings. Redis supports push, pop operations from both sides of the list, trim based on offset, read 1 or more items of the list, search and delete values.<\/p>\n<p><strong>SET<\/strong>: Set of strings (not sorted). Redis supports operations that add, read, delete each element, check the appearance of the element in the set. Redis also supports set operations, including intersect\/union\/difference.<\/p>\n<p><strong>HASH<\/strong>: Stores hash tables of key-value pairs, in which keys are randomly sorted, in no order at all. Redis supports operations to add, read, delete each element individually, as well as read all values.<\/p>\n<p><strong>ZSET<\/strong>\u00a0(sorted set): Is a list, in which each element is a map of 1 string (member) and 1 floating-point number (score), the list is sorted by this score. Redis supports adding, reading, deleting each element, taking out elements based on the range of the score or string.<\/p>\n<h5>Replication \u2013 Persistence:<\/h5>\n<p>Redis uses a primary-replica architecture and supports asynchronous replication, data can be copied to many different servers. This makes for improved read performance (as requests can be split between servers) and faster recovery when the main server experiences an outage. For maintenance, Redis supports point-in-time backups (copying Redis data to disk).<\/p>\n<h5>In-Memory Data Store<\/h5>\n<p>Redis stores data on RAM, so reading and writing data is much faster than on a hard drive.<\/p>\n<p>But also because all the data on RAM will be lost when turning off server, However, one solution was to use Redis Persistence.<\/p>\n<h5>Persistent redis<\/h5>\n<p>Although working with key-value data stored on RAM, Redis still needs to store data on the hard drive to ensure data integrity when something goes wrong (the server is powered off) as well as recreate the dataset when restarting the server. Redis provides 2 main methods for backing up data to hard drives, namely RDB and AOF.<\/p>\n<p><em><strong>RDB (Redis Database)<\/strong><\/em><\/p>\n<p>RDB creates and backs up a snapshot of the DB to the hard drive every certain period of time.<\/p>\n<p><em>Advantages of RDB<\/em><br \/>\nRDB allows users to save different versions of the DB, which is very convenient when something goes wrong.<\/p>\n<p>RDB helps optimize Redis performance.\u00a0The main Redis process will only do the work on RAM, including the basic operations required from the client side such as add\/read\/delete, while a child process will take care of disk I\/O operations. .\u00a0This organization helps maximize Redis performance.<\/p>\n<p><em>Disadvantages of RDB<\/em><br \/>\nUsually users will set up to create RDB snapshot every 5 minutes (or more).\u00a0Therefore, in the event of a problem, Redis cannot operate, data in the last minutes will be lost.<\/p>\n<p>RDB needs to use fork to create child processes for disk I\/O operations.\u00a0In case the data is too large, the fork process can be time consuming and the server will not be able to respond to the request from the client for several milliseconds or even 1 second depending on the amount of data and CPU performance.<\/p>\n<p id=\"_aof-append-only-file-11\"><em><strong>AOF (Append Only File)<\/strong><\/em><\/p>\n<p>AOF saves all write operations received by the server, these operations will be rerun when restarting the server or resetting the original dataset.<\/p>\n<p><em>Advantages of AOF<\/em><br \/>\nAOF Redis ensures that the dataset is more stable.\u00a0Users can configure Redis to log once a second or every query.<\/p>\n<p>Redis logs AOF in an append-to-end of an existing file, so a seek process on an existing file is unnecessary.\u00a0Even if the log ends with a half-written command for some reason (disk is full or other reasons), the redis-check-aof tool can still fix it easily.<\/p>\n<p>Redis provides a background process, allowing to record AOF files when the file size is too large.\u00a0The rewrite is completely safe because while Redis continues to add to the old file, a completely new file is created with the minimal set of operations required to create the current dataset, and when this second file is ready, Redis transfers two files and starts adding a new file.<\/p>\n<p><em>Disadvantages of AOF<\/em><br \/>\nAOF files are often larger than equivalent RDB files for the same data set.<\/p>\n<p>AOF may be slower than RDB depending on fsync policy.\u00a0Generally with fsync set to second, performance is still very high, and with fsync disabled it will be exactly as fast as RDB.\u00a0RDB can still provide more guarantees about maximum latency even in case of very large write load.<\/p>\n<h3>Performance<\/h3>\n<p>Compared to a traditional on-disk database in which most tasks require repeated access to the drive, Redis only needs to get the calculated result. Therefore, Redis performance is remarkably fast for conventional read or write tasks along with low latency and high throughput.<\/p>\n<p>Supports more operations and 10x faster response times. The average read and write operations take less than a millisecond and support millions of operations per second.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-6568\" src=\"https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2022\/08\/05151236\/nosql-benchmark-200000-300x208.png\" alt=\"\" width=\"703\" height=\"487\" srcset=\"https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2022\/08\/05151236\/nosql-benchmark-200000-300x208.png 300w, https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2022\/08\/05151236\/nosql-benchmark-200000.png 484w\" sizes=\"auto, (max-width: 703px) 100vw, 703px\" \/><\/p>\n<h3>Common use cases of Redis<\/h3>\n<p>Caching<\/p>\n<p>Save the pending task list<\/p>\n<p>Game leaderboards<\/p>\n<p>Session archive<\/p>\n<p>Machine Learning<\/p>\n<p>Real-time analytics<\/p>\n<p>\u2026<\/p>\n<h2>Redis Stack<\/h2>\n<p>The Redis Stack was created to enable developers to build real-time applications with a backend data platform that can reliably handle requests in milliseconds by extending Redis with data models and data processing tools.<\/p>\n<p>Redis Stack has 5 module packages:\u00a0<strong>RedisJSON<\/strong>,\u00a0<strong>RediSearch<\/strong>,\u00a0<strong>RedisGraph<\/strong>,\u00a0<strong>RedisTimeSeries<\/strong>\u00a0and\u00a0<strong>RedisBloom<\/strong>.<\/p>\n<p>In addition, the Redis Stack also\u00a0includes <strong>RedisInsight<\/strong>, a visualization tool for understanding and optimizing data.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"alignnone wp-image-6602\" src=\"https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2022\/08\/10104316\/RedisInsight-300x160.png\" alt=\"\" width=\"831\" height=\"443\" srcset=\"https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2022\/08\/10104316\/RedisInsight-300x160.png 300w, https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2022\/08\/10104316\/RedisInsight-1024x545.png 1024w, https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2022\/08\/10104316\/RedisInsight-768x409.png 768w, https:\/\/s3-ap-southeast-1.amazonaws.com\/homepage-media\/wp-content\/uploads\/2022\/08\/10104316\/RedisInsight.png 1366w\" sizes=\"auto, (max-width: 831px) 100vw, 831px\" \/><\/p>\n<p style=\"text-align: center;\"><em>RedisInsight interface<\/em><\/p>\n<p>To easily understand how the Redis Stack works, we will start to learn how to use 2 modules\u00a0<strong>RedisJSON<\/strong>\u00a0and\u00a0<strong>RediSearch<\/strong>\u00a0with\u00a0<strong>the node-redis<\/strong>\u00a0library.<\/p>\n<p>Install\u00a0<strong>node-redis<\/strong>\u00a0library<\/p>\n<pre>npm install redis<\/pre>\n<p>Connect to Redis Server<\/p>\n<pre>import { createClient } from 'redis';\r\n\r\nconst client = <span class=\"pl-en\">createClient<\/span><span class=\"pl-kos\">(<\/span><span class=\"pl-kos\">{<\/span>\r\n  <span class=\"pl-c1\">url<\/span>: <span class=\"pl-s\">'redis[s]:\/\/[[username][:password]@][host][:port][\/db-number]'<\/span>\r\n<span class=\"pl-kos\">}<\/span><span class=\"pl-kos\">)<\/span><span class=\"pl-kos\">;\r\n\r\n<\/span>client.on('error', (err) =&gt; console.log('Redis Client Error', err));\r\n\r\nawait client.connect();<\/pre>\n<h3>RedisJSON<\/h3>\n<p>RedisJSON is a Redis module that provides JSON support in Redis. RedisJSON allows you to store, update, and retrieve JSON values in Redis just like you would with any other Redis data type. RedisJSON also works simultaneously with RediSearch to allow you to index and query your JSON documents.<\/p>\n<p><span class=\"\">The document is stored as binary data in a tree structure, which allows quick access to child elements.<\/span><\/p>\n<p dir=\"auto\"><strong>Storing JSON Documents in Redis<\/strong><\/p>\n<p dir=\"auto\">The <code>JSON.SET<\/code>\u00a0command stores a JSON value at a given JSON Path in a Redis key.<\/p>\n<p dir=\"auto\">Here, we&#8217;ll store a JSON document in the root of the Redis key &#8220;<code>users<\/code>&#8220;:<\/p>\n<p dir=\"auto\"><span style=\"font-family: Consolas, Monaco, monospace;\">await client.json.set(&#8216;noderedis:users&#8217;, &#8216;$&#8217;, {<\/span><\/p>\n<div>\n<div>\n<pre>  \u00a0 name: 'Alice',\r\n  \u00a0 age: 29\r\n});<\/pre>\n<\/div>\n<p dir=\"auto\"><strong>Retrieving JSON Documents from Redis<\/strong><\/p>\n<div>\n<pre>const results = await client.json.get('noderedis:users');<\/pre>\n<p><code>results<\/code>\u00a0will contain the following:<\/p>\n<div class=\"highlight highlight-source-js notranslate position-relative overflow-auto rgh-observing-whitespace rgh-linkified-code\">\n<pre class=\"rgh-observing-whitespace rgh-linkified-code\">{ name: 'Alice', age: 29 }<\/pre>\n<\/div>\n<\/div>\n<\/div>\n<h3>RediSearch<\/h3>\n<p>RediSearch is a Redis module that provides query, sub-indexing, and search capabilities for Redis. To use RediSearch, you first declare indexes on your Redis data. You can then use the RediSearch query language to query that data.<\/p>\n<p>RediSearch uses compressed, inverted indexes to index quickly with low memory capacity.<\/p>\n<p>RediSearch provides accurate phrase comparison, fuzzy search (search for &#8220;approximation&#8221;), numeric filtering,&#8230;<\/p>\n<h6><span class=\"\">Indexing and Querying Data in Redis Hashes<\/span><\/h6>\n<p dir=\"auto\"><strong>Creating an Index<\/strong><\/p>\n<p>Before we can perform any searches, we need to tell RediSearch how to index our data, and which Redis keys to find that data in. The\u00a0<strong>FT.CREATE\u00a0<\/strong>command creates a RediSearch index. Here&#8217;s how to use it to create an index we&#8217;ll call\u00a0<code>idx:animals<\/code>\u00a0where we want to index hashes containing\u00a0<code>name<\/code>,\u00a0<code>species<\/code>\u00a0and\u00a0<code>age<\/code>\u00a0fields, and whose key names in Redis begin with the prefix\u00a0<code>noderedis:animals<\/code>:<\/p>\n<pre>await client.ft.create('idx:animals', {\r\n  name: {\r\n    type: SchemaFieldTypes.TEXT,\r\n    sortable: true\r\n  },\r\n    species: SchemaFieldTypes.TAG,\r\n    age: SchemaFieldTypes.NUMERIC\r\n  }, {\r\n    ON: 'HASH',\r\n    PREFIX: 'noderedis:animals'\r\n  }\r\n);<\/pre>\n<p>Once we&#8217;ve created an index, and added some data to Redis hashes whose keys begin with the prefix\u00a0<code>noderedis:animals<\/code><\/p>\n<p><strong>Add a document<\/strong><\/p>\n<p>Use the\u00a0<strong>HSET<\/strong>\u00a0command to create a new hash document and add it to the index:<\/p>\n<pre>await client.hSet('noderedis:animals:1', {name: 'Fluffy', species: 'cat', age: 3});\r\nawait client.hSet('noderedis:animals:2', {name: 'Ginger', species: 'dog', age: 4});<\/pre>\n<p dir=\"auto\"><strong>Querying the Index<\/strong><\/p>\n<p>To search the index for documents containing specific words, use\u00a0<strong>FT. SEARCH<\/strong><\/p>\n<pre class=\"rgh-observing-whitespace rgh-linkified-code\">const results = await client.ft.search(\r\n    'idx:animals', \r\n    '@species:{dog}',\r\n    {\r\n      SORTBY: {\r\n        BY: 'age',\r\n        DIRECTION: 'DESC' \/\/ or 'ASC' (default if DIRECTION is not present)\r\n      }\r\n    }\r\n  );<\/pre>\n<p><code>results<\/code>\u00a0will look like this:<\/p>\n<pre class=\"rgh-observing-whitespace rgh-linkified-code\"><span class=\"pl-kos\">{<\/span>\r\n  <span class=\"pl-c1\">total<\/span>: 1<span class=\"pl-kos\">,<\/span>\r\n  <span class=\"pl-c1\">documents<\/span>: <span class=\"pl-kos\">[<\/span>\r\n    <span class=\"pl-kos\">{<\/span>\r\n      <span class=\"pl-c1\">id<\/span>: <span class=\"pl-s\">'noderedis:animals:2'<\/span><span class=\"pl-kos\">,<\/span>\r\n      <span class=\"pl-c1\">value<\/span>: <span class=\"pl-kos\">{<\/span>\r\n        <span class=\"pl-c1\">name<\/span>: <span class=\"pl-s\">'Ginger'<\/span><span class=\"pl-kos\">,<\/span>\r\n        <span class=\"pl-c1\">species<\/span>: <span class=\"pl-s\">'dog'<\/span><span class=\"pl-kos\">,<\/span>\r\n        <span class=\"pl-c1\">age<\/span>: <span class=\"pl-s\">'4'<\/span>\r\n      <span class=\"pl-kos\">}<\/span>\r\n    <span class=\"pl-kos\">}\r\n<\/span><span class=\"pl-kos\">  ]<\/span>\r\n<span class=\"pl-kos\">}<\/span><\/pre>\n<h6>Indexing and Querying Data with RedisJSON<\/h6>\n<p dir=\"auto\"><strong>Creating an Index<\/strong><\/p>\n<p dir=\"auto\">To create an index for a JSON document<\/p>\n<div>\n<pre>await client.ft.create('idx:users', {\r\n  \u00a0 '$.name': {\r\n  \u00a0 \u00a0 \u00a0 type: SchemaFieldTypes.TEXT,\r\n  \u00a0 \u00a0 \u00a0 SORTABLE: 'UNF'\r\n  \u00a0 },\r\n  \u00a0 '$.age': {\r\n  \u00a0 \u00a0 \u00a0 type: SchemaFieldTypes.NUMERIC,\r\n  \u00a0 \u00a0 \u00a0 AS: 'age'\r\n  \u00a0 },\r\n}, {\r\n  \u00a0 ON: 'JSON',\r\n  \u00a0 PREFIX: 'noderedis:users'\r\n});<\/pre>\n<p dir=\"auto\"><strong>Querying the Index<\/strong><\/p>\n<p dir=\"auto\"><span class=\"\">We will use the <code>FT.SEARCH<\/code> command and\u00a0RediSearch query language.\u00a0For example, a query to find users under the age of 30:<\/span><\/p>\n<div class=\"highlight highlight-source-js notranslate position-relative overflow-auto rgh-observing-whitespace rgh-linkified-code\">\n<div>\n<pre>const results = <span class=\"pl-k\" style=\"font-family: Consolas, Monaco, monospace;\">await<\/span> <span class=\"pl-s1\" style=\"font-family: Consolas, Monaco, monospace;\">client<\/span><span class=\"pl-kos\" style=\"font-family: Consolas, Monaco, monospace;\">.<\/span><span class=\"pl-c1\" style=\"font-family: Consolas, Monaco, monospace;\">ft<\/span><span class=\"pl-kos\" style=\"font-family: Consolas, Monaco, monospace;\">.<\/span><span class=\"pl-en\" style=\"font-family: Consolas, Monaco, monospace;\">search<\/span><span class=\"pl-kos\" style=\"font-family: Consolas, Monaco, monospace;\">(<\/span><span class=\"pl-s\" style=\"font-family: Consolas, Monaco, monospace;\">'idx:users'<\/span><span class=\"pl-kos\" style=\"font-family: Consolas, Monaco, monospace;\">,<\/span> <span class=\"pl-s\" style=\"font-family: Consolas, Monaco, monospace;\">'@age:[0 30]'<\/span><span class=\"pl-kos\" style=\"font-family: Consolas, Monaco, monospace;\">)<\/span><span class=\"pl-kos\" style=\"font-family: Consolas, Monaco, monospace;\">;<\/span><\/pre>\n<\/div>\n<\/div>\n<p dir=\"auto\"><code>results<\/code> data returned:<\/p>\n<pre>{\r\n  \"total\": 1,\r\n  \"documents\": [\r\n    {\r\n      \"id\": \"noderedis:users\",\r\n      \"value\": {\r\n        \"name\": \"Alice\",\r\n        \"age\": 29\r\n      }\r\n    }\r\n  ]\r\n}<\/pre>\n<h2>Conclusion<\/h2>\n<p>Redis is an open source software package with many advantages, so it is widely used in the software development process.<\/p>\n<p>It&#8217;s super fast, easy to set up and use, and supports flexible data structures.\u00a0Redis is a great choice when it comes to caching data or applications with real-time requirements.<\/p>\n<p>With the same mechanism of storing data on RAM, compared to Memcached\u00a0<strong>,<\/strong>\u00a0Redis supports more data types and more operations on the server side.\u00a0There is also a default mechanism to back up data to disk while Memcached does not have this mechanism.\u00a0So if you want your system to be cacheable but with complex data structures, then Redis will be a better choice.<\/p>\n<h2>References<\/h2>\n<p><a href=\"https:\/\/redis.io\/docs\/\">https:\/\/redis.io\/docs\/<\/a><\/p>\n<p><a href=\"https:\/\/redis.js.org\/\">https:\/\/redis.js.org\/<\/a><\/p>\n<p><a href=\"https:\/\/byterot.blogspot.com\/2012\/11\/nosql-benchmark-redis-mongodb-ravendb-cassandra-sqlserver.html\">https:\/\/byterot.blogspot.com\/2012\/11\/nosql-benchmark-redis-mongodb-ravendb-cassandra-sqlserver<\/a><\/p>\n<p><a href=\"https:\/\/github.com\/redis\/node-redis\">https:\/\/github.com\/redis\/node-redis<\/a><\/p>\n<\/div>\n<p><\/p>","protected":false},"excerpt":{"rendered":"<p>Introduction Redis (Remote\u00a0Dictionary\u00a0Server) is one of the NoSQL-style database management systems. Used to store structured data as key-value on RAM with high performance. Can be used as a database, cache or message broker. Redis can also be used as a database stored in RAM to speed up processing. Redis currently offers response times at speeds of less than a millisecond, as Redis allows you to [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":6537,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_mi_skip_tracking":false,"footnotes":""},"categories":[4,71],"tags":[],"class_list":["post-6535","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-news","category-it-tec"],"_links":{"self":[{"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/posts\/6535","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/comments?post=6535"}],"version-history":[{"count":0,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/posts\/6535\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/media\/6537"}],"wp:attachment":[{"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/media?parent=6535"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/categories?post=6535"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.briswell-vn.com\/en\/wp-json\/wp\/v2\/tags?post=6535"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}