Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Scanning a Vector from SQLite Back to Go #171

Open
wjkoh opened this issue Jan 15, 2025 · 3 comments
Open

Scanning a Vector from SQLite Back to Go #171

wjkoh opened this issue Jan 15, 2025 · 3 comments

Comments

@wjkoh
Copy link

wjkoh commented Jan 15, 2025

I store []float32 data using sqlite_vec's SerializeFloat32 function and am wondering how I can retrieve it from SQLite into Go. I've been using vec_to_json and unmarshaling the JSON on the Go side as the following code, but I suspect there might be a better approach. Could you please advise?

	var embeddingJson string
	row := db.QueryRowContext(
		ctx,
		`SELECT vec_to_json(embedding) FROM documents WHERE document_id = ?`,
		id,
	)
	err := row.Scan(&embeddingJson)
	if err != nil {
		return nil, err
	}
	var embedding []float32
	err = json.Unmarshal([]byte(embeddingJson), &embedding)
	if err != nil {
		return nil, err
	}
	return embedding, nil
@asg017
Copy link
Owner

asg017 commented Jan 15, 2025

@wjkoh does something like this work?

func DeserializeFloat32(data []byte) ([]float32, error) {
    if len(data)%4 != 0 {
        return nil, fmt.Errorf("invalid data length: must be a multiple of 4")
    }

    // Create a slice to hold the deserialized float32 values
    count := len(data) / 4
    vector := make([]float32, count)

    buf := bytes.NewReader(data)
    err := binary.Read(buf, binary.LittleEndian, &vector)
    if err != nil {
        return nil, err
    }

    return vector, nil
}

This compliments the SerializeFloat32() method, but I haven't tested it yet.

If it works, I'll add it to the Go library bindings

@wjkoh
Copy link
Author

wjkoh commented Jan 16, 2025

Thanks for your reply, @asg017! I think that your function and https://pkg.go.dev/database/sql#RawBytes can work together for this use case. I'll give it a try soon!

@wjkoh
Copy link
Author

wjkoh commented Feb 2, 2025

@asg017 Thank you for the function! It works as intended and is very helpful for unit testing and debugging. I hope you add the function to the next release.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants