Window function 😊. CTE with window function 😮. Hierarchical recursive CTE 🤯. Recommended all the way. Can’t wait to see the rest of the videos!M Wildan Zulfikar
Shorten dev cycles with branching and zero-downtime schema migrations.
In the last video, I was terribly excited, right? We created a related products or related articles feature in I think it was under maybe seven or eight minutes. Kind of wild. We're going to make it a little bit more robust here, a little bit more production ready by using an upsert. Because imagine your articles change or your product descriptions change, or your product photos are updated. You need to update the embeddings. We've already learned how we can do upcerts.
We're going to combine that knowledge to up cert our vector embeddings. We're just running this as a single command. You have to imagine this is being run as a background job or some sort of listener or some sort of evented hook, something like that. Whatever your framework or language provides. The situation would be, what if we update an article? If we update an article, we update a product description, we change an image, we need to cue some sort of background job to go get new embeddings and then update the database. We can use the fact that Slug is unique. We can use that to accomplish an upsert.
Let's hop down here and make some space. We'll make some space here. This is our initial statement. These question marks are for bind parameters. We're not just injecting strings in here, which can lead to SQL injection. We're going to say on conflict. Then you pass through the column name. When there is a conflict on the column slug, which is unique, we're going to do update set embedding equal to excluded, which is that keyword that says, hey, you were trying to insert this, but we disallowed it because there was a conflict. Here it is if you want to access it. Excluded.embedding. That should accomplish our upsert. If we hop back over here, we can't just null it out. What I'm going to do is I'm going to say, let's go, let's put the first three values as zero. We'll say 000. Save that, save that.
If we refresh, so you'll see the first three values are zero. I've mucked up the vector embeddings, and now we want to run our worker again and we'll say, AR embed and reputation is portable. That's the very first one. Reputation is portable right here. If we run that again, we see, boom, the upsert worked. So in the real world, you would run this, in the real world, you would run this as the result of saving the model probably, you would save the model. You would check to see, are the contents dirty? Did I change the contents of my blog post or my product description or my image? If so, let's fire off a job to go out, get some new embeddings and then insert it, so you can use those upserts that we learned a long time ago, we can use that to keep those embeddings fresh.