---
title: "Vectors in SQLite! (with libSQL)"
url: "https://aaronfrancis.com/videos/vectors-in-sqlite-with-libsql"
path: "/videos/vectors-in-sqlite-with-libsql"
type: video
author: Aaron Francis
published: 2024-10-23
topic: Databases
keywords: [sqlite vectors, libsql, embeddings, openai api, nearest neighbors, vector search, sqlite, turso, related articles, semantic search, php, database indexing]
youtube_url: "https://www.youtube.com/watch?v=w0FTWcuyliA"
site_index: "/llms.txt"
keyword_index: "/llms/keywords.txt"
---

# Vectors in SQLite! (with libSQL)

## Chapters

- Introduction and Website Overview
- SQLite Database for the Website
- LibSQL Vector Support Introduction
- Creating Article Embeddings with OpenAI API
- Cleaning Article Contents
- Generating Embeddings from Article Data
- Storing Embeddings in libSQL
- Setting up Database for Embeddings
- Indexing and Storing Embeddings in SQLite
- Writing SQL Query for Related Articles
- Querying Article Embeddings for Nearest Neighbors
- Testing and Fetching Related Articles
- Improved Related Articles Display
- Conclusion and Future Plans

## Transcript

**Aaron Francis:** On my very good website, aaronfrancis.com, you'll see I have some articles. What if you tried hard? It's a question you should ask yourself. Over here on the side, I have more articles. Now, in theory, these should be related articles. However, if we look at the code, we see article query in random order, limit five.

**Aaron Francis:** That's it. That's the best I could do at the time. Uh, we can do a lot better now. So behind my website is a SQLite database. I've talked about this a lot before. I like it 'cause it's nice and compact, and I can ship it anywhere. I'll put a link to another video down in the description where I talk about that. This is not about that, but I am using SQLite under the hood here, and my favorite SQLite provider, Turso, who is not paying me to make this video, Turso has just released experimental support for vectors in their fork of SQLite,

**Aaron Francis:** which is Libsql. And so we're gonna use some vectors. So what-- Here's the plan. We're gonna run the content of the article. We're gonna run the content of the article through OpenAI's API, and we're gonna generate some embeddings. We're gonna store those embeddings in the Libsql database, and then we're gonna use some of these functions to calculate the nearest neighbor of the embeddings, which will give us actual related articles instead of just in random order.

**Aaron Francis:** So let's get started by creating some embeddings. I have just a test command here, which is where I like to do a lot of stuff. So we're gonna say, WHERE NOT NULL markdown file. So we're gonna look for all the articles where we actually have a markdown file, and we'll say, "Get all of those," and then we're just gonna each over them. And so here, we will accept the article as a typed parameter, and so we'll say article, article.

**Aaron Francis:** Now, what I need to do is, let's do, um... let's just first get the contents. So we'll do file get contents, and I think it's in the resource path in views, articles, and then I think it's just, uh, article markdown file. So if we do that and we dump out the contents, we can hop over here and just run it with ART, and there we go.

**Aaron Francis:** So we have all of the contents for this article. I think what I need to do is, I could do something intelligent here, where I parse it and I remove the front matter. Instead, I'm gonna do something stupid because it's very easy and it doesn't matter. So I can do, uh, let's do explode. Um, what is the order of this one? Separator string. So the separator is gonna be that.

**Aaron Francis:** The string is gonna be contents. We're gonna limit it down to three parts only, and then we'll say that the contents, uh, we'll say last of contents. If you don't know last, it's a Laravel helper that does end but without passing it by reference, so it's useful in a lot more places. So we can get, uh, the contents back here, and if we run that, we should see that the front matter has been removed, and the front matter has been removed.

**Aaron Francis:** So we have some clean contents there. Now, the next thing I'm gonna do is I have, um, I've pulled in the OpenAI package, uh, that Nuno Maduro built for Laravel, and so we're gonna use the OpenAI API to create some embeddings based on this content. And the way that we do that is we just say OpenAI, and we'll take the facade embeddings create.

**Aaron Francis:** That's all you have to do. And so then we'll pass in. It's not input. Uh, it is input. It's not content. So the input is contents, and then the model that we're gonna use is this one right here, text embedding three small. It's a little cheaper, it's a little faster, and it's accurate enough for what we are doing. So the response is going to come back there, and I believe the response is, um, does it give us a response here?

**Aaron Francis:** Yeah, it gives us a response. So we have the create response type is already set. So we can say response embeddings, and I think that gives us an array, and so we'll dump this out. So if we get this back, so the first response here, so we're actually gonna hit the OpenAI API. So hopefully it is quick, and it is quick.

**Aaron Francis:** So the, the embeddings that we get back, we get fifteen thirty-six of them 'cause we're zero indexed, and it's a bunch of floats, which is what an embedding looks like. And let's make sure that we have the structure correct up here. Boy, there's a lot of them. Fifteen thirty-six is a lot. So we have a create response embedding, and we wanna chain embedding off of that.

**Aaron Francis:** So if we did that again, and we're just gonna hit the API. Maybe this is an expensive video, but honestly, it should be pretty cheap. So if we run that again, we should just get the float as an array, which we do. Now that we have these embeddings, uh, all as an array, we, we gotta put them somewhere, and where we're going to put them is in a SQLite database, kind of. We're putting them in a Libsql database.

**Aaron Francis:** Libsql is a fork of SQLite by the Turso team so that they can add more stuff on top of it. It remains file compatible with SQLite, but when you fork it, you can add stuff like vectors. And so that's what we're gonna do here. I'm gonna be interacting with this file through, um, uh, Turso's Libsql bindings for PHP, which gives us those access-- gives us that access to those vector functions.

**Aaron Francis:** This has nothing to do with Turso whatsoever. I'm not creating a Turso account. I'm not online at all. This can be completely offline, which is very, very cool, just using Libsql. If you do need something like embedded replicas or backups or something like that, I highly recommend you check out Turso for managed SQLite. But what I'm gonna show you here, totally free, nothing to do with Turso whatsoever.

**Aaron Francis:** Let's take a look. The first thing I'm gonna do is I'm gonna open a connection to a, a file. So it's-- I, I do love that about SQLite. We're, we're, like, creating a new connection, but it's just a file on the file system. So we'll do a db connect there, and then, um, in this command right here, I'm just gonna build up the tables. I am working on a, uh, a Laravel- ...

**Aaron Francis:** specific driver for Turso/LibSQL, and that will be, uh, that will be coming soon. But for now, we're just gonna interact with it through this. So what we're gonna do here is I'm gonna, um, just drop the articles table if it exists, because we're gonna build it up from scratch here. And I'm gonna create an ID primary key, so ID is just an integer. And then this is my slug.

**Aaron Francis:** It's a unique slug that I use to keep track of the articles. And then here's the interesting thing. This is an embedding, and this is a, uh, LibSQL specific function. We're saying, uh, we want it to be, uh, F32, so float 32 as a blob, and we, we're gonna have 1,536 different, uh, dimensions, and that's what we get back from OpenAPI, which is why we picked that number.

**Aaron Francis:** And then we're gonna create a special index. So we're gonna create this LibSQL vector index over this embedding column. So we're gonna put this giant array of floats in there, and then we're gonna put a special index over it that's gonna speed up the search quite a bit. And then I just put a unique index over the article's slug. Because that's a little bit domain specific, I need to do that.

**Aaron Francis:** And so we can go ahead and let's just go ahead and we'll just create this database by just running ART. And so now that database structure is created, and frankly, uh, we don't need this part anymore. And so what we're gonna do now is as we loop through these articles, we're just gonna fill the database up with these embeddings, and then we'll hop over to the article model and figure out how to query, uh, for related articles.

**Aaron Francis:** So inside of our loop here, we're gonna say, not we need to bring this into scope, uh, so we'll hop up here, and we'll say use connection. And so inside of our loop, we'll say, uh, not contents, connection, execute, and we're gonna execute, uh, a string of SQL here, and we're gonna pass in some bindings here. So what is our SQL gonna look like?

**Aaron Francis:** I think we can do something that's kind of interesting. Let's do insert into articles. Uh, we'll say slug and embedding values of... We'll just pass a parameter there, and here we're gonna say vector 32, and then we'll pass a parameter in there.

**Aaron Francis:** But what we can do, an additional thing we can do here, just to make it super, uh, correct, is we can do an upsert. SQLite has upserts. Let's do an upsert. An upsert is defined by saying on conflict. So we'll say on conflict. When there is a conflict of slug, which we've declared as a unique column, we'll say do update set embedding.

**Aaron Francis:** I think it's singular. Didn't we declare it singular? I think we did. Embedding. Set embedding equal to excluded.embedding. So this means that anytime we have a conflict on the slug column, which is unique, we're gonna take the new embedding value and update whatever is in the database, effectively giving us an upsert, which is very cool.

**Aaron Francis:** Now, the last thing we need to do is we need to fill in the slug. And over here, um, the slug is actually just the ID, and then we want to JSON encode to turn it into a string, 'cause that's what that function accepts. JSON encode the actual embedding, and I think with that, we are good to go.

**Aaron Francis:** So let's just do a this line, um, inserted, and we'll do article. I think title is correct. We'll just see what happens. We'll hop back over here, clear this out, and now we should see... There we go. All right. So what we're doing is we're hitting the OpenAI API, generating some embeddings, inserting them into the embeddings.db database, which we can actually pop open in TablePlus.

**Aaron Francis:** It's gonna look like a bunch of nonsense, but let's go ahead and pop it open. So if we do open, uh, embeddings.db in Table, I think it has a space in it, TablePlus. Nope, no space. We open it here, and we see articles. So we have the slug and the embedding just as kind of a big blob. And so that did work.

**Aaron Francis:** We do have all of that data in there, and you'll see that, um, there are a few other tables. These are maintained by LibSQL. Uh, we don't have to worry about those. What we have is we have our information right there. Let's work on creating the new related query that actually takes advantage of these embeddings instead of just doing it at random, which worked for a super long time.

**Aaron Francis:** But now let's make it better. All right. I'm gonna take you, I'm gonna take you over here, and we're gonna come down here, and I'm gonna clean this up just a little bit. I don't need a separate, uh, DB, so we're just gonna say connection equals that. And now we need to write a query. So let's write a query.

**Aaron Francis:** Um, what's our query gonna be? Let's do, um, select articles.slug. So what we're gonna do is, um, we're going to try to find all of the slugs that are, uh, related to the current article that we're reading, and we're gonna bring those slugs back and then pull out the full articles and send those back to whoever called this related function here.

**Aaron Francis:** So we'll start by just selecting the slugs, but the from part is gonna be a little bit interesting. We are gonna not select from the articles table. We're gonna sele- select from this, um, table function that allows us to query those vector embeddings. So we're gonna say vector top K using that index that we created earlier.

**Aaron Francis:** And then this is where you would pass the embedding. So in theory, you could just, like, um, you could pass an embedding as a bind parameter and just put it in there. But what we're gonna do is we're actually gonna use a subquery to figure out what is the embedding of the article that this person is reading, and therefore, what articles are related to the one that this person is reading right now.

**Aaron Francis:** So we'll write that subquery in a second, and we want to select, let's select six of them, which will become clear in a second. So we'll say as vector And then we're gonna join in the articles table. So we'll say JOIN articles on articles.id = vectors.id, and that brings back the entire thing so that we can select articles.slug out of there.

**Aaron Francis:** And then we wanna say WHERE articles.slug does not equal the actual slug that we're on. So we're gonna find six, and then we're gonna say actually eliminate just one of them, and then we can hop down here and say LIMIT 5, which should just be-- that should be, uh, the five related articles that we're looking for. So this is our query save for the subquery.

**Aaron Francis:** So what we need to do in the subquery is we need to look at the articles table, find the article that the person is reading, pull that embedding out, and put it into our search here. Very, very easy. We can say SELECT embedding from articles where, uh, slug equals question mark as vector. And oh, we have a typo there, so that needs to be vector.id, not vectors.id.

**Aaron Francis:** And now we can just run this thing. So let's do, um, connection query. We'll pass our query in, and then here are the parameters. How many do we have? I see one parameter. I see two parameters. In fact, those are the same value, but since we have two positional parameters, we'll say this ID because on, um, this side, the primary key of the article model is in fact the slug.

**Aaron Francis:** And so we're just gonna pass that in twice, and we'll say fetch array, and this is-- we'll call it results. That makes a little more sense. DD results, and everything is gonna blow up, but we should see at the very bottom, we should see... All right, look at that. We got five slugs that presumably are related to this article that we're reading here.

**Aaron Francis:** So let's go ahead and do a little Laravel. We'll do, um, our pluck, the results, pluck the slug out, and DD that again. Now we have five slugs. And so finally, what we can do is we can say WHERE id-- nope, WHERE IN id, uh, our results.

**Aaron Francis:** And in random order is fine, limit is fine, get is fine. That should be, uh, related articles. So what if you tried hard? Related. Argument for logging off, I agree. Year in review, kind of. You're always doing something wrong, definitely. Do literally anything. These feel pretty good to me. Um, I do-- Yep, I do kinda like the random order.

**Aaron Francis:** Let's go to year in review 2023, and hopefully we see, if my CSS was better, you see year in review 2022. Okay, that means it's working. We are getting related articles. Now, what I wanna do is I wanna check, I wanna check an article that is technical. SQLite is not weakly typed.

**Aaron Francis:** That is true, actually. I wanna check this article. There we go. That's what I'm hoping to see. More articles, uh, recursive CTEs, something about SQLite, something about MySQL, MySQL, and Laravel's database locks. I think this is-- I think this is working. Uh, uh, these, these results are much more relevant than the just in random order.

**Aaron Francis:** And so we, we've taken all of my articles, we've sent them off to get, uh, the-- generate these embeddings, we've put them in the database, and then we're using those embeddings to find nearest neighbors, which means articles that are most similar to the one that you're reading. And we're doing all of this locally on my machine. So I would highly encourage you to check out Turso.

**Aaron Francis:** I'll leave some links down below. Turso, LibSQL. I am working on a driver for this for Laravel. If you're interested in the Laravel driver, please leave a comment and let me know. That'll help me rank it in terms of priorities of things that I am working on. But for now, I feel pretty confident in this, and I feel like this is a huge improvement to my related articles section.

**Aaron Francis:** So check out Turso. Let me know what you think. Until the next time, see ya.

---

## Related on aaronfrancis.com

- [Production SQLite with Turso and libSQL](/videos/production-sqlite-with-turso-and-libsql) *(Video · 2024-06-14 · shared: sqlite, libsql, turso)*
- [Teaching Databases, Writing PHP, and Independent Work with Aaron Francis](/podcast/teaching-databases-writing-php-and-independent-work-with-aaron-francis-a22e6b07) *(Podcast · 2024-08-27 · shared: sqlite, php, libsql)*
- [Luck Surface Area | Multithreaded Income Episode 43 with Aaron Francis](/podcast/luck-surface-area-multithreaded-income-episode-43-with-aaron-francis-1c7ae213) *(Podcast · 2024-07-16 · shared: sqlite, turso, php)*
- [Elevate Your Video Developer Brand: Featuring Aaron Francis](/podcast/elevate-your-video-developer-brand-featuring-aaron-francis-4a89ae8f) *(Podcast · 2024-06-07 · shared: php, sqlite, turso)*
- [Rewriting SQLite from scratch (yes, really)](/videos/rewriting-sqlite-from-scratch-yes-really) *(Video · 2025-08-08 · shared: turso, libsql, sqlite)*

## Relevant Resources from Aaron Francis

- **[High Performance SQLite](https://databaseschool.com)** (overview on site: [/courses](/courses)): Comprehensive video course on running SQLite in production: WAL mode, concurrency, FTS5, strict tables, backups, and performance tuning.
- **[MySQL for Developers](https://databaseschool.com)** (overview on site: [/courses](/courses)): Full video course covering MySQL indexing, deferred joins, pagination, query plans, and schema design for application developers.

## Search aaronfrancis.com (2-Hop Static Keyword Index)

Pick the alphabetical shard matching any topic to find exact pages across all articles, newsletters, videos, talks, and podcast transcripts (every shard is < 40 KB):
[A-B](/llms/keywords/a-b.txt) · [C](/llms/keywords/c.txt) · [D-E](/llms/keywords/d-e.txt) · [F-G](/llms/keywords/f-g.txt) · [H-J](/llms/keywords/h-j.txt) · [K-L](/llms/keywords/k-l.txt) · [M-N](/llms/keywords/m-n.txt) · [O-P](/llms/keywords/o-p.txt) · [Q-R](/llms/keywords/q-r.txt) · [S](/llms/keywords/s.txt) · [T-Z](/llms/keywords/t-z.txt) · [Directory](/llms/keywords.txt) · [Site Map](/llms.txt)

Shards for this page's topics: `sqlite vectors` ([S](/llms/keywords/s.txt)), `libsql` ([K-L](/llms/keywords/k-l.txt)), `embeddings` ([D-E](/llms/keywords/d-e.txt)), `openai api` ([O-P](/llms/keywords/o-p.txt)).

## About Aaron Francis (Current Context)

Aaron Francis is VP of Marketing and Community at [Laravel](https://laravel.com), founder of [Try Hard Studios](https://tryhardstudios.com), creator of [Solo](https://soloterm.com), co-host of [Mostly Technical](/podcast), and author of [Mastering Postgres](/courses), [High Performance SQLite](/courses), [MySQL for Developers](/courses), and [Screencasting.com](/courses). Full bio: [/about](/about) · Current focus: [/now](/now).
