Skip to content

Instantly share code, notes, and snippets.

@roji
Created May 8, 2025 09:38
Show Gist options
  • Select an option

  • Save roji/52dfac165082301adfc0158ef023c5a3 to your computer and use it in GitHub Desktop.

Select an option

Save roji/52dfac165082301adfc0158ef023c5a3 to your computer and use it in GitHub Desktop.
Sample hello world app using Microsoft.Data.Sqlite with sqlite_vec
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Data.Sqlite;
const string PATH = "/tmp/foo.sqlite";
File.Delete(PATH);
await using var connection = new SqliteConnection($"Data Source={PATH}");
connection.LoadVector();
// connection.LoadExtension("vec0");
await connection.OpenAsync();
// Code here is based on the sqlite_vec getting started docs: https://github.com/asg017/sqlite-vec
await using var command = connection.CreateCommand();
command.CommandText =
"""
CREATE VIRTUAL TABLE vec_examples USING vec0 (
sample_embedding float[8]
);
INSERT INTO vec_examples(rowid, sample_embedding)
VALUES
(1, '[-0.200, 0.250, 0.341, -0.211, 0.645, 0.935, -0.316, -0.924]'),
(2, '[0.443, -0.501, 0.355, -0.771, 0.707, -0.708, -0.185, 0.362]'),
(3, '[0.716, -0.927, 0.134, 0.052, -0.669, 0.793, -0.634, -0.162]'),
(4, '[-0.710, 0.330, 0.656, 0.041, -0.990, 0.726, 0.385, -0.958]');
""";
await command.ExecuteNonQueryAsync();
command.CommandText =
"""
SELECT rowid, distance, sample_embedding
FROM vec_examples
WHERE sample_embedding MATCH '[0.890, 0.544, 0.825, 0.961, 0.358, 0.0196, 0.521, 0.175]'
ORDER BY distance
LIMIT 2;
""";
await using var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
var rowId = reader.GetInt64(0);
var distance = reader.GetDouble(1);
var vectorByteArray = reader.GetFieldValue<byte[]>(2);
var floats = MemoryMarshal.Cast<byte, float>(vectorByteArray).ToArray();
Console.WriteLine($"Row ID: {rowId}, Distance: {distance}, First float: {floats[0]}");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment