For high-performance and compact K-nearest-neighbors (KNN) searches, use the vec0 virtual table. This method is faster than manual SQL searches but requires joining back to your source tables to retrieve non-vector data.
To use vec0:
- Create a virtual table using
vec0 with a defined schema (e.g., float[768]). - Populate the virtual table with vector data.
- Query using the
MATCH operator and specify the number of neighbors with the k parameter.
Note on SQLite versions: If you are using SQLite 3.41+, you can use LIMIT instead of the k = N syntax, but k = N is the standard approach for sqlite-vec.
-- 1. Create the virtual table
create virtual table vec_documents using vec0(
document_id integer primary key,
contents_embedding float[768]
);
-- 2. Populate the table
insert into vec_documents(document_id, contents_embedding)
select id, embed(contents)
from documents;
-- 3. Perform KNN query
select
document_id,
distance
from vec_documents
where contents_embedding match :query
and k = 10;