Telegram Group & Telegram Channel
🔢 PGVector: векторный поиск прямо в PostgreSQL — гайд

Если ты работаешь с embedding'ами (OpenAI, HuggingFace, LLMs) и хочешь делать семантический поиск в SQL — тебе нужен pgvector. Это расширение позволяет сохранять и сравнивать векторы прямо внутри PostgreSQL.

📦 Установка PGVector (Linux)


git clone --branch v0.8.0 https://github.com/pgvector/pgvector.git
cd pgvector
make
sudo make install


Или просто:
• macOS: brew install pgvector
• Docker: pgvector/pgvector:pg17
• PostgreSQL 13+ (через APT/YUM)

🔌 Подключение расширения в базе


CREATE EXTENSION vector;


После этого ты можешь использовать новый тип данных vector.

🧱 Пример использования

Создаём таблицу:


CREATE TABLE items (
id bigserial PRIMARY KEY,
embedding vector(3)
);


Добавляем данные:


INSERT INTO items (embedding) VALUES ('[1,2,3]'), ('[4,5,6]');


Поиск ближайшего вектора:


SELECT * FROM items
ORDER BY embedding <-> '[3,1,2]'
LIMIT 5;


🧠 Операторы сравнения

PGVector поддерживает несколько видов расстояний между векторами:

- <-> — L2 (евклидово расстояние)
- <#> — скалярное произведение
- <=> — косинусное расстояние
- <+> — Manhattan (L1)
- <~> — Хэммингово расстояние (для битовых векторов)
- <%> — Жаккар (для битовых векторов)

Также можно усреднять вектора:


SELECT AVG(embedding) FROM items;


🚀 Индексация для быстрого поиска

HNSW (лучшее качество):


CREATE INDEX ON items USING hnsw (embedding vector_l2_ops);


Параметры можно настраивать:


SET hnsw.ef_search = 40;


#### IVFFlat (быстрее создаётся, но чуть менее точный):


CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100);
SET ivfflat.probes = 10;


🔍 Проверка версии и обновление


SELECT extversion FROM pg_extension WHERE extname='vector';
ALTER EXTENSION vector UPDATE;


📌 Особенности

- Работает с PostgreSQL 13+
- Поддержка до 2000 измерений
- Расширяемый синтаксис
- Можно использовать DISTINCT, JOIN, GROUP BY, ORDER BY и агрегации
- Подходит для RAG-пайплайнов, NLP и встраивания LLM-поиска в обычные SQL-приложения

🔗 Подробнее

💡 Храни embedding'и прямо в PostgreSQL — и делай семантический поиск без внешних векторных БД.



group-telegram.com/machinelearning_books/1023
Create:
Last Update:

🔢 PGVector: векторный поиск прямо в PostgreSQL — гайд

Если ты работаешь с embedding'ами (OpenAI, HuggingFace, LLMs) и хочешь делать семантический поиск в SQL — тебе нужен pgvector. Это расширение позволяет сохранять и сравнивать векторы прямо внутри PostgreSQL.

📦 Установка PGVector (Linux)


git clone --branch v0.8.0 https://github.com/pgvector/pgvector.git
cd pgvector
make
sudo make install


Или просто:
• macOS: brew install pgvector
• Docker: pgvector/pgvector:pg17
• PostgreSQL 13+ (через APT/YUM)

🔌 Подключение расширения в базе


CREATE EXTENSION vector;


После этого ты можешь использовать новый тип данных vector.

🧱 Пример использования

Создаём таблицу:


CREATE TABLE items (
id bigserial PRIMARY KEY,
embedding vector(3)
);


Добавляем данные:


INSERT INTO items (embedding) VALUES ('[1,2,3]'), ('[4,5,6]');


Поиск ближайшего вектора:


SELECT * FROM items
ORDER BY embedding <-> '[3,1,2]'
LIMIT 5;


🧠 Операторы сравнения

PGVector поддерживает несколько видов расстояний между векторами:

- <-> — L2 (евклидово расстояние)
- <#> — скалярное произведение
- <=> — косинусное расстояние
- <+> — Manhattan (L1)
- <~> — Хэммингово расстояние (для битовых векторов)
- <%> — Жаккар (для битовых векторов)

Также можно усреднять вектора:


SELECT AVG(embedding) FROM items;


🚀 Индексация для быстрого поиска

HNSW (лучшее качество):


CREATE INDEX ON items USING hnsw (embedding vector_l2_ops);


Параметры можно настраивать:


SET hnsw.ef_search = 40;


#### IVFFlat (быстрее создаётся, но чуть менее точный):


CREATE INDEX ON items USING ivfflat (embedding vector_l2_ops) WITH (lists = 100);
SET ivfflat.probes = 10;


🔍 Проверка версии и обновление


SELECT extversion FROM pg_extension WHERE extname='vector';
ALTER EXTENSION vector UPDATE;


📌 Особенности

- Работает с PostgreSQL 13+
- Поддержка до 2000 измерений
- Расширяемый синтаксис
- Можно использовать DISTINCT, JOIN, GROUP BY, ORDER BY и агрегации
- Подходит для RAG-пайплайнов, NLP и встраивания LLM-поиска в обычные SQL-приложения

🔗 Подробнее

💡 Храни embedding'и прямо в PostgreSQL — и делай семантический поиск без внешних векторных БД.

BY Машиннное обучение | Наука о данных Библиотека


Warning: Undefined variable $i in /var/www/group-telegram/post.php on line 260

Share with your friend now:
group-telegram.com/machinelearning_books/1023

View MORE
Open in Telegram


Telegram | DID YOU KNOW?

Date: |

Continuing its crackdown against entities allegedly involved in a front-running scam using messaging app Telegram, Sebi on Thursday carried out search and seizure operations at the premises of eight entities in multiple locations across the country. Right now the digital security needs of Russians and Ukrainians are very different, and they lead to very different caveats about how to mitigate the risks associated with using Telegram. For Ukrainians in Ukraine, whose physical safety is at risk because they are in a war zone, digital security is probably not their highest priority. They may value access to news and communication with their loved ones over making sure that all of their communications are encrypted in such a manner that they are indecipherable to Telegram, its employees, or governments with court orders. Since January 2022, the SC has received a total of 47 complaints and enquiries on illegal investment schemes promoted through Telegram. These fraudulent schemes offer non-existent investment opportunities, promising very attractive and risk-free returns within a short span of time. They commonly offer unrealistic returns of as high as 1,000% within 24 hours or even within a few hours. One thing that Telegram now offers to all users is the ability to “disappear” messages or set remote deletion deadlines. That enables users to have much more control over how long people can access what you’re sending them. Given that Russian law enforcement officials are reportedly (via Insider) stopping people in the street and demanding to read their text messages, this could be vital to protect individuals from reprisals. The message was not authentic, with the real Zelenskiy soon denying the claim on his official Telegram channel, but the incident highlighted a major problem: disinformation quickly spreads unchecked on the encrypted app.
from in


Telegram Машиннное обучение | Наука о данных Библиотека
FROM American