|
| 1 | +package com.example; |
| 2 | + |
| 3 | +import java.io.IOException; |
| 4 | +import java.sql.Connection; |
| 5 | +import java.sql.DriverManager; |
| 6 | +import java.sql.PreparedStatement; |
| 7 | +import java.sql.ResultSet; |
| 8 | +import java.sql.SQLException; |
| 9 | +import java.sql.Statement; |
| 10 | +import java.util.ArrayList; |
| 11 | +import java.util.List; |
| 12 | +import ai.djl.ModelException; |
| 13 | +import ai.djl.huggingface.translator.TextEmbeddingTranslatorFactory; |
| 14 | +import ai.djl.inference.Predictor; |
| 15 | +import ai.djl.repository.zoo.Criteria; |
| 16 | +import ai.djl.repository.zoo.ZooModel; |
| 17 | +import ai.djl.translate.TranslateException; |
| 18 | +import com.pgvector.PGvector; |
| 19 | + |
| 20 | +public class Example { |
| 21 | + public static void main(String[] args) throws IOException, ModelException, SQLException, TranslateException { |
| 22 | + Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/pgvector_example"); |
| 23 | + |
| 24 | + Statement setupStmt = conn.createStatement(); |
| 25 | + setupStmt.executeUpdate("CREATE EXTENSION IF NOT EXISTS vector"); |
| 26 | + setupStmt.executeUpdate("DROP TABLE IF EXISTS documents"); |
| 27 | + |
| 28 | + PGvector.addVectorType(conn); |
| 29 | + |
| 30 | + Statement createStmt = conn.createStatement(); |
| 31 | + createStmt.executeUpdate("CREATE TABLE documents (id bigserial PRIMARY KEY, content text, embedding vector(384))"); |
| 32 | + |
| 33 | + ZooModel<String, float[]> model = loadModel("sentence-transformers/multi-qa-MiniLM-L6-cos-v1"); |
| 34 | + |
| 35 | + String[] input = { |
| 36 | + "The dog is barking", |
| 37 | + "The cat is purring", |
| 38 | + "The bear is growling" |
| 39 | + }; |
| 40 | + List<float[]> embeddings = generateEmbeddings(model, input); |
| 41 | + |
| 42 | + for (int i = 0; i < input.length; i++) { |
| 43 | + PreparedStatement insertStmt = conn.prepareStatement("INSERT INTO documents (content, embedding) VALUES (?, ?)"); |
| 44 | + insertStmt.setString(1, input[i]); |
| 45 | + insertStmt.setObject(2, new PGvector(embeddings.get(i))); |
| 46 | + insertStmt.executeUpdate(); |
| 47 | + } |
| 48 | + |
| 49 | + String query = "growling bear"; |
| 50 | + float[] queryEmbedding = generateEmbeddings(model, new String[] {query}).get(0); |
| 51 | + double k = 60; |
| 52 | + |
| 53 | + PreparedStatement queryStmt = conn.prepareStatement(HYBRID_SQL); |
| 54 | + queryStmt.setObject(1, new PGvector(queryEmbedding)); |
| 55 | + queryStmt.setObject(2, new PGvector(queryEmbedding)); |
| 56 | + queryStmt.setString(3, query); |
| 57 | + queryStmt.setDouble(4, k); |
| 58 | + queryStmt.setDouble(5, k); |
| 59 | + ResultSet rs = queryStmt.executeQuery(); |
| 60 | + while (rs.next()) { |
| 61 | + System.out.println(String.format("document: %d, RRF score: %f", rs.getLong("id"), rs.getDouble("score"))); |
| 62 | + } |
| 63 | + |
| 64 | + conn.close(); |
| 65 | + } |
| 66 | + |
| 67 | + private static ZooModel<String, float[]> loadModel(String id) throws IOException, ModelException { |
| 68 | + return Criteria.builder() |
| 69 | + .setTypes(String.class, float[].class) |
| 70 | + .optModelUrls("djl://ai.djl.huggingface.pytorch/" + id) |
| 71 | + .optEngine("PyTorch") |
| 72 | + .optTranslatorFactory(new TextEmbeddingTranslatorFactory()) |
| 73 | + .build() |
| 74 | + .loadModel(); |
| 75 | + } |
| 76 | + |
| 77 | + private static List<float[]> generateEmbeddings(ZooModel<String, float[]> model, String[] input) throws TranslateException { |
| 78 | + Predictor<String, float[]> predictor = model.newPredictor(); |
| 79 | + List<float[]> embeddings = new ArrayList<>(input.length); |
| 80 | + for (String text : input) { |
| 81 | + embeddings.add(predictor.predict(text)); |
| 82 | + } |
| 83 | + return embeddings; |
| 84 | + } |
| 85 | + |
| 86 | + public static final String HYBRID_SQL = """ |
| 87 | + WITH semantic_search AS ( |
| 88 | + SELECT id, RANK () OVER (ORDER BY embedding <=> ?) AS rank |
| 89 | + FROM documents |
| 90 | + ORDER BY embedding <=> ? |
| 91 | + LIMIT 20 |
| 92 | + ), |
| 93 | + keyword_search AS ( |
| 94 | + SELECT id, RANK () OVER (ORDER BY ts_rank_cd(to_tsvector('english', content), query) DESC) |
| 95 | + FROM documents, plainto_tsquery('english', ?) query |
| 96 | + WHERE to_tsvector('english', content) @@ query |
| 97 | + ORDER BY ts_rank_cd(to_tsvector('english', content), query) DESC |
| 98 | + LIMIT 20 |
| 99 | + ) |
| 100 | + SELECT |
| 101 | + COALESCE(semantic_search.id, keyword_search.id) AS id, |
| 102 | + COALESCE(1.0 / (? + semantic_search.rank), 0.0) + |
| 103 | + COALESCE(1.0 / (? + keyword_search.rank), 0.0) AS score |
| 104 | + FROM semantic_search |
| 105 | + FULL OUTER JOIN keyword_search ON semantic_search.id = keyword_search.id |
| 106 | + ORDER BY score DESC |
| 107 | + LIMIT 5 |
| 108 | + """; |
| 109 | +} |
0 commit comments