|
| 1 | +// good resources |
| 2 | +// https://opensearch.org/blog/improving-document-retrieval-with-sparse-semantic-encoders/ |
| 3 | +// https://huggingface.co/opensearch-project/opensearch-neural-sparse-encoding-v1 |
| 4 | +// |
| 5 | +// run with |
| 6 | +// text-embeddings-router --model-id opensearch-project/opensearch-neural-sparse-encoding-v1 --pooling splade |
| 7 | + |
| 8 | +#include <cstdint> |
| 9 | +#include <iostream> |
| 10 | + |
| 11 | +#include <cpr/cpr.h> |
| 12 | +#include <nlohmann/json.hpp> |
| 13 | +#include <pgvector/pqxx.hpp> |
| 14 | +#include <pqxx/pqxx> |
| 15 | + |
| 16 | +using json = nlohmann::json; |
| 17 | + |
| 18 | +std::vector<pgvector::SparseVector> fetch_embeddings(const std::vector<std::string>& inputs) { |
| 19 | + std::string url = "http://localhost:3000/embed_sparse"; |
| 20 | + json data = { |
| 21 | + {"inputs", inputs} |
| 22 | + }; |
| 23 | + |
| 24 | + cpr::Response r = cpr::Post( |
| 25 | + cpr::Url{url}, |
| 26 | + cpr::Body{data.dump()}, |
| 27 | + cpr::Header{{"Content-Type", "application/json"}} |
| 28 | + ); |
| 29 | + json response = json::parse(r.text); |
| 30 | + |
| 31 | + std::vector<pgvector::SparseVector> embeddings; |
| 32 | + for (auto& item : response) { |
| 33 | + std::vector<int> indices; |
| 34 | + std::vector<float> values; |
| 35 | + for (auto& e : item) { |
| 36 | + indices.emplace_back(e["index"]); |
| 37 | + values.emplace_back(e["value"]); |
| 38 | + } |
| 39 | + embeddings.emplace_back(pgvector::SparseVector(30522, indices, values)); |
| 40 | + } |
| 41 | + return embeddings; |
| 42 | +} |
| 43 | + |
| 44 | +int main() { |
| 45 | + pqxx::connection conn("dbname=pgvector_example"); |
| 46 | + |
| 47 | + pqxx::work tx(conn); |
| 48 | + tx.exec("CREATE EXTENSION IF NOT EXISTS vector"); |
| 49 | + tx.exec("DROP TABLE IF EXISTS documents"); |
| 50 | + tx.exec("CREATE TABLE documents (id bigserial PRIMARY KEY, content text, embedding sparsevec(30522))"); |
| 51 | + tx.commit(); |
| 52 | + |
| 53 | + std::vector<std::string> input = { |
| 54 | + "The dog is barking", |
| 55 | + "The cat is purring", |
| 56 | + "The bear is growling" |
| 57 | + }; |
| 58 | + auto embeddings = fetch_embeddings(input); |
| 59 | + |
| 60 | + for (size_t i = 0; i < input.size(); i++) { |
| 61 | + tx.exec("INSERT INTO documents (content, embedding) VALUES ($1, $2)", pqxx::params{input[i], embeddings[i]}); |
| 62 | + } |
| 63 | + tx.commit(); |
| 64 | + |
| 65 | + std::string query = "forest"; |
| 66 | + auto query_embedding = fetch_embeddings({query})[0]; |
| 67 | + pqxx::result result = tx.exec("SELECT content FROM documents ORDER BY embedding <#> $1 LIMIT 5", pqxx::params{query_embedding}); |
| 68 | + for (const auto& row : result) { |
| 69 | + std::cout << row[0].as<std::string>() << std::endl; |
| 70 | + } |
| 71 | + |
| 72 | + return 0; |
| 73 | +} |
0 commit comments