Technology

Is Redis the ONLY database you need? // Fullstack app from scratch with Next.js & Redis


Most developers already know that redis is a mega fast in-memory database often used as a cache to make traditional databases faster but what most developers don’t know is that redis can also be used as a primary app database thanks to a suite of modules that add additional data structures and commands

To core redis they can handle json data full text search graph relationships and many other features in today’s video we’ll put this claim to the test by building a full text autocomplete search inspired by something like algolia or elasticsearch where the user can add items to the database and instantly view

The filtered results we’ll build this project from scratch using next.js allowing us to use react on the front end and nodejs to interact with redis on the back end as an added bonus redis just released a brand new sdk called redis ohm that supports object mapping

And nodejs if you’re new here like and subscribe and you can follow along with the full article on fireship io let’s first take a look at what we’re building today we have a form that when submitted we’ll add a new item to the database in redis this data would normally be saved

As a hash data structure but a hash doesn’t support nested objects so instead we’ll be storing this data as native json thanks to the redis json module now after adding a few items to the database we may want to retrieve them later when i type into the search

Form field you can see that it automatically updates the results in the ui after every keystroke that’s made possible by redis search which is an incredibly powerful module that can index all of the fields on your json dataset at which point you can perform complex queries like you would with the

Where clause in sql and aggregations like sum and count now we’re ready to start building there are a few different ways you can get started with redis the easiest option is to sign up for rediscloud i collaborated with redis enterprise cloud to make this video and they’re providing a 200 credit and also

A chance to win a tesla model 3 if you use this code before january 31st so that’s pretty awesome but more importantly redis is consistently the most loved database out there i’ve used it myself for many years and that’s why i decided to work with them on this

Video after you sign in you’ll be prompted to create a new subscription go ahead and do that and you can choose a free fixed plan to play around once that’s done create a database and when creating it make sure to add the add-on modules of redis search and redis json

And you now have your own database that can scale infinitely in the cloud to connect to it you’ll notice this public endpoint url as well as a password for the default user now the question becomes how do we connect to our database this is optional but the first

Thing i would recommend doing is downloading the redis insight tool which gives you a gui to analyze and manage data in the database once installed click the option to add a new database and then paste in the public url that rediscloud provided you with then also enter the username of default and the

Password it generated and then it should automatically connect to your database the cool thing about redis is that it’s really easy to learn because everything is organized into a set of key value pairs here’s a little crash course of the redis basics to add a new item to

The database you create a new key every key is unique and is used to identify a value in the database a key can also have a data type in this case we’ll use a string but there are more complex data types like a hash for objects of

Multiple key value pairs lists and as we’ll see later json data for now let’s go ahead and save a string with a key of hello and a value of world it also gives you the option to specify a ttl or time to live after which point the data will

Be automatically deleted if you want leave it blank to keep the data forever now the unique thing about redis is that when you save data that data is kept in memory as opposed to the disk like it would be on most other traditional database systems what that means is that

Redis is extremely fast there’s no need for a round trip to the disk when retrieving data but on redis cloud this data is also persisted which means there’s never any actual data loss now to make a read to the database let’s go over to the workbench panel and you’ll

Notice a terminal here where we can write commands redis has a bunch of built-in commands that allow us to do different things in the database for example what we just did previously was a set with a command it would look like set followed by hello world now to read

The string we can use the get command followed by the key name of hello now there are tons of other commands we could execute here to interact with our data but that’s enough to give you the general idea now we’re ready to build something cool and in order to do that

We’ll want to first initialize next js from the command line run npx create next app then open it up in vs code the project has only one dependency redis om which you can install with npm this library is brand new so keep in mind that there may be changes or

Enhancements in the near future what it does is map your data into a javascript class or entity making it really easy to build a consistent schema around your data and it simplifies many of the create read update and delete operations that you’ll want to do on the database

First we’ll need to connect to our cloud database and for that i’m creating a file called.env.local that contains environment variables that will automatically be picked up by next.js inside of it we have a value of redis url which is formatted with the username and password along with the url and port

Of the actual database replace these values with the ones provided by redis cloud now from there let’s create a lib directory and a file named redis.js inside the file we have a few imports from redisome the first one we want to think about is the client that’s the

Main entry point for interacting with the database to connect to our database in the cloud we call client open followed by process.env.redisurl that will access the environment variable that we set up earlier now because of the way next.js works i’m also going to create an async function

Called connect that will only open the connection if it’s not already open then the next thing we’ll do is define an entity for our data an entity is basically like a database table we first define a class like car and extend it with entity from there we can give it a

Schema that contains a variety of different properties each with its own specific data type by default this represents a hash in the redis database however when building a more traditional application you might find it easier to work with json to use the redis json module simply add the option of data

Structure json and now redis will operate more like a document oriented database now that we have this entity we’re ready to start creating data to handle the basic process i’m going to export an async function here called create car and then the first thing it does in the body is connect to the

Database client from there we create a repository by combining the schema and the client together if we want to create new data we can use the create entity method with a javascript object which later we’ll get from a form input in the ui and lastly we can call repository

Save with the card data to commit it to the database and redis will return an automatically generated unique id the key is car colon unique id then the value is json data with the schema that you defined now the question becomes how do we run this function for that we’ll

Need two things we need an api route which will give a name of cars.js to handle the right operation on the back end then we’ll need a react component which i’ll give a name of carforum.js in the lib directory that will handle the user input and make a request to that

Api route let’s first implement the api route we first import the createcar function we just defined then every api route in next exports a default function named handler which contains a request and response where the request is the incoming data and the response is the outgoing data you want to send back to

The client in this case we’ll want to use the request body which will be json data from the form to create a new car once redis is done writing that data we can then send a response back to the client letting them know it was successful with the new unique id now

That we have an api endpoint we want to call it from the front end when a form is submitted in carform.js i have a react component and in the jsx we have a standard html form with a few different text inputs it also has a submit button

And we will intercept the submit event by passing a function to the form called handle submit in the handle submit function we’ll first call event prevent default to prevent the page from refreshing on submit and then here’s a cool trick when handling form data in a react component normally to convert the

Form event to json you would have to access each individual property which leads to some really ugly and tedious code a better approach is to convert the event target which is the html form to the form data class which is built into the browser that will organize the form

Fields into a bunch of key value pairs which we can then turn into a plain javascript object by using object from entries now it’s important to point out that the name that you provide to the form input determines the name of the key so you’ll want to make sure that

That name matches the schema that you chose for your redis data now the final step is to make a request to the api endpoint which we can do by using the fetch api in the browser and for the body we pass it the json stringified form data you’ll want to make sure the

Content type is json and the method is post from there we can send the request convert it to json and then console log the result and now there’s just one thing left to do let’s go into the index.js file and declare the car form

There and now we can fire up the next js app by running npm run dev in the ui you should have a form that looks like this mine looks a little prettier because i’ve added bootstrap for styling and when you fill it out and submit it it

Should console log the id that was created by redis in addition you should be able to open up redis inside to see the data there as well at this point we have a very basic full stack application with redis now you might be wondering how do i query and filter this data to

Show it on the front end that’s where redis search comes in it’s a very powerful module that allows you to index and search across your data set to use it though we first need to create an index and to do that i’m going to go back into the redis.js file and create a

New function called createindex all this function needs to do is reference the repository and call the createindex method now before we use this function another thing i want to point out is that we can go up into our schema and add a text search true option to any

Fields that want to enable full text search what this allows us to do is query this data with fuzzy matching where it can recognize typos and common words yet still return the intended result let’s go ahead and add the full text option to the description now creating the index is only something you

Need to do once for convenience i’m going to add another api route here called create index that imports that function and then sends a response back once defined we can then go to the browser and access the url api create index to add the index to the database

Now that we have an index let’s go back to the redis.js file and create a function to search for cars in the database this function will take a query as its input which will be whatever the user types into the form and then it calls the repository search method which

Has all kinds of different capabilities like pagination it can retrieve the first and last items it can get a count of the total items in the database and also perform logical comparisons like greater than less than and so on the first method to call is where which

References one of the properties in the json data in this case we can search the make of the car for exact equality with the eq method and pass it the query as an argument if we also want to search the model of the car at the same time we

Can chain or model and also check that for equality now when it comes to the description we don’t want exact equality but instead we want to check the matches within a full text search context that tells it to return results even if there are typos and things like that and

Finally we tell it to return all the results from that query that takes care of the search logic now once again we need an api route which we can easily set up by adding a search.js file inside of which we export a handler it’ll grab the search query from the url called the

Searchcars method and then return the response which will be an array of cars back to the client and now the last thing we need is a form on the front end to make calls to the search endpoint i’m creating a new file called searchform.js which is a react component and in the

Jsx we have an input that triggers a search function whenever it is changed so that’ll fire whenever the user types into the form now this component will also need to have state to represent the hits or results that we get back from the search engine we can define that

State with the use state hook and initialize it as an empty array in the search function we will first grab the current value of the form and then format it as a url parameter the api route is expecting it in that format to pass the value along to redis now you’ll

Also notice that i’m only going to execute this code if the query length is greater than 2. that’s just to prevent excessive api calls to the database or api route it would also be a good idea to debounce this code because currently it will make an api call for every

Keystroke and that’s probably more api calls than you actually need for something like this from there we can use the fetch api to make a request to the search endpoint along with the parameters the result we get back will be an array of cars that we can set as

The state on this component now let’s display the card data by setting up an unordered list then map each individual hit to a list item i’m using the entity id as the key and then displaying whatever data i want to show in the ui like the make and model and image of the

Car congratulations you just built a full stack full text search feature with redis and next js i’m going to go ahead and wrap things up there if you want to see more redis or next js content let me know in the comments thanks for watching

And i will see you in the next one

#Redis #database #Fullstack #app #scratch #Next.js #Redis
For More Interesting Article Visit : https://mycyberbase.com/

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *