pgvector support for C++
Supports libpqxx
Add the headers to your project (supports C++17 and greater).
There is also support for CMake and FetchContent:
include(FetchContent)
FetchContent_Declare(pgvector GIT_REPOSITORY https://github.com/pgvector/pgvector-cpp.git GIT_TAG v0.2.1)
FetchContent_MakeAvailable(pgvector)
target_link_libraries(app PRIVATE pgvector::pgvector)
Follow the instructions for your database library:
Or check out some examples:
- Embeddings with OpenAI
- Binary embeddings with Cohere
- Hybrid search with llama.cpp (Reciprocal Rank Fusion)
- Sparse search with Text Embeddings Inference
- Morgan fingerprints with RDKit
- Recommendations with Disco
- Bulk loading with
COPY
Include the header
#include <pgvector/pqxx.hpp>
Enable the extension
tx.exec("CREATE EXTENSION IF NOT EXISTS vector");
Create a table
tx.exec("CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3))");
Insert a vector
auto embedding = pgvector::Vector({1, 2, 3});
tx.exec("INSERT INTO items (embedding) VALUES ($1)", {embedding});
Get the nearest neighbors
pqxx::result r = tx.exec("SELECT * FROM items ORDER BY embedding <-> $1 LIMIT 5", {embedding});
Retrieve a vector
auto row = tx.exec("SELECT embedding FROM items LIMIT 1").one_row();
auto embedding = row[0].as<pgvector::Vector>();
Use std::optional<pgvector::Vector>
if the value could be NULL
Convert a vector to a std::vector<float>
auto float_vec = static_cast<std::vector<float>>(embedding);
View the changelog
Everyone is encouraged to help improve this project. Here are a few ways you can help:
- Report bugs
- Fix bugs and submit pull requests
- Write, clarify, or fix documentation
- Suggest or add new features
To get started with development:
git clone https://github.com/pgvector/pgvector-cpp.git
cd pgvector-cpp
createdb pgvector_cpp_test
g++ -std=c++17 -Wall -Wextra -Wno-unknown-attributes -Werror -o test/pqxx test/pqxx_test.cpp -lpqxx -lpq
test/pqxx
To run an example:
cd examples/loading
createdb pgvector_example
cmake -S . -B build
cmake --build build
build/example