sqlite-vec: SELECT WITH IN broken.
I have a query
def chunks_for(prompt, k:1024, facets:{}, limit:64, rerank:true)
embedding = local_embedding_for(prompt)
stmts = [
"SELECT id, distance FROM embeddings WHERE embedding MATCH ? AND k = ?"
]
if facets.size > 0
chunk_ids = chunk_ids_for_facets(facets)
stmts.push "AND id IN(#{ chunk_ids.join(',') })"
end
stmts.push "ORDER BY distance"
query =
stmts.join(' ')
rows =
@vec0.execute(
query,
[embedding.pack("f*"), k]
)
rows =
rows.sort do |a, b|
b.last <=> a.last # ORDER BY distance DESC
end
ids =
rows.map{|row| row.first}
chunks =
@chunks.where(id: ids).to_a
if rerank
reranked = rerank(prompt, chunks)
chunks = reranked
end
chunks = chunks.first(limit)
return chunks
end
but, running this seems to always return the results of the IN query in that order. meaning, this seems to mess up the query planner. instead of returning matched rows that also are in a set of IDs, it returns only the set of IDS, in that exact order.
About this issue
- Original URL
- State: closed
- Created 2 years ago
- Comments: 17 (6 by maintainers)
sqlite-vecwill apply metadata filters before performing the KNN query, so something seems off here.I’m trying to reproduce what you’re seeing on my end, and I’m having trouble:
(removed some of the other metadata columns that weren’t needed)
Could you try running an
EXPLAIN QUERY PLANon your KNN SQL query? the output should love something like this:It’s a bit hard to read, but I can use that to debug this further.
Alternatively if you’re ok sharing the database itself I can try to debug that too (feel free to email it to me)
I’d also try to confirm a few other things:
subreddit = 'r/science') has values in the table (ex run `select id from rag where subreddit = ‘r/science’ limit 5) to ensure they exist in the table)kto see if that effects results (it shouldnt, if it does that indicates a bug on sqlite-vec’s side)JOINs other otherWHEREclauses in the KNN query