sqlite-vec icon indicating copy to clipboard operation
sqlite-vec copied to clipboard

Java support

Open raymondjxu opened this issue 1 year ago • 2 comments

Can I use this library with Java? If so, how?

raymondjxu avatar Aug 23 '24 14:08 raymondjxu

Java embedding in plan? or guide how to do it? will be happy to raise a PR

ch8n avatar Nov 09 '24 07:11 ch8n

You can use this library with Java. Here's how:

  1. Using SQLite JDBC: Ensure you have the SQLite JDBC driver in your project. You can include it via Maven or download the .jar file.
  2. Copy vec0.dll: Place the vec0.dll file in a directory accessible to your Java application.
  3. Load vec0 Extension: Use JDBC to load the extension into your SQLite connection.
  4. Write Java Code to Test It:
public static void main(String[] args) {
		// SQLite connection string
		String url = "jdbc:sqlite:sample.db";

		// SQL statements for creating a table and inserting data
		String createTableSQL = """
				create virtual table vec_examples using vec0(
				  sample_embedding float[8]
				);
								""";

		String insertDataSQL1 = """

				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]');
								""";

		String selectSQL = """
				select
				  rowid,
				  distance
				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;
								""";

               // Configure SQLite to enable extension loading
		SQLiteConfig config = new SQLiteConfig();
		config.enableLoadExtension(true);
              // Create database connection with the config
		try (Connection conn = DriverManager.getConnection(url, config.toProperties());
				Statement stmt = conn.createStatement()) {
			// Load the extension
			stmt.execute("SELECT load_extension('vec0.dll');");

			// Create table
			stmt.execute(createTableSQL);

			// Insert data
			stmt.execute(insertDataSQL1);

			// Query data
			ResultSet rs = stmt.executeQuery(selectSQL);

			// Print results
			while (rs.next()) {
				int id = rs.getInt("rowid");
				float a = rs.getFloat("distance");
				System.out.println("Row ID: " + id + " distance: " + a);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
  1. Result:
Row ID: 2 distance: 2.3868737
Row ID: 1 distance: 2.389785

caixg avatar Nov 12 '24 13:11 caixg