在当今AI驱动的世界中,处理向量数据变得越来越重要。pgvector作为PostgreSQL的扩展插件,使传统的关系型数据库具备了存储和查询向量数据的能力,为以下场景提供了强大支持:
-
实现相似性搜索(如推荐系统)
-
存储和查询AI模型生成的嵌入向量
-
构建智能搜索应用
-
创建基于内容的推荐引擎
一、安装PostgreSQL数据库
1、进入PostgreSQL官网获取执行命令
进入官网选择下载版本
执行下面命令
命令解释
# 安装仓库RPM
yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm# 安装PostgreSQL server
yum install -y postgresql15-server# 初始化
/usr/pgsql-15/bin/postgresql-15-setup initdb
# 启动
systemctl start postgresql-15# 设置为开机自启动
systemctl enable postgresql-15
2、修改PostgreSQL配置
修改postgresql.conf文件
vi /var/lib/pgsql/15/data/postgresql.conf
# 默认:
listen_addresses = 'localhost' ,仅允许本机连接
listen_addresses = '*'
修改pg_hba.conf文件
vi /var/lib/pgsql/15/data/pg_hba.conf
# 默认:
host all all 127.0.0.1/32 scram-sha-256
# 修改为
host all all 0.0.0.0/0 scram-sha-256
重启数据库
systemctl restart postgresql-15
3、修改PostgreSQL密码
# 切换到 PostgreSQL 系统用户
su - postgres
# 使用linux用户进入PostgreSQL交互终端
psql -U postgres
# 设置密码命令
\password
# 然后填入密码
4、开放防火墙端口
阿里云可在控制台开启
测试远程连接,在本地通过Navicat测试是否能连接
二、安装pgvector向量插件
1、安装PostgreSQL15开发工具包
# 安装PostgreSQL15开发工具包
yum install -y postgresql15-devel
# 如果上一步执行时报错,那么请先安装centos-release-scl-rh包,再安装PostgreSQL开发工具包 Error: Package: postgresql15-devel-15.5-1PGDG.rhel7.x86_64 (pgdg15) Requires: llvm-toolset-7-clang >= 4.0.1
# 安装centos-release-scl-rh包
yum install -y centos-release-scl-rh
如果安装有以下报错
Loaded plugins: fastestmirror Loading mirror speeds from cached hostfile Could not retrieve mirrorlist http://mirrorlist.centos.org?arch=x86_64&release=7&repo=sclo-rh error was 14: curl#6 - "Could not resolve host: mirrorlist.centos.org; Unknown error"
执行下面命令
sudo sed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*
sudo sed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*
sudo yum clean all
sudo yum makecache
安装完后使用命令查看是否能获取pg_config
which pg_config
如未获取到,配置工具环境
# 安装默认地址为:/usr/pgsql-15/bin/
export PATH=$PATH:/usr/pgsql-15/bin/
再次执行,查看能否获取pg_config
2、安装插件vector
# 先安装git
yum install -y git
# 切换到/tmp目录,下载源码包
cd /tmp git clone --branch v0.5.1 https://github.com/pgvector/pgvector.git
# 进入/tmp/pgvector目录
cd pgvector
#进行编译安装
make & make install
3、数据库使用vector,并测试
# 切换到 PostgreSQL 系统用户
sudo -i -u postgres
# 进入 PostgreSQL 交互终端
psql
# 创建demo数据库
create database demo;
# 切换到demo数据库
\c demo
# 安装vector扩展
CREATE EXTENSION vector;
# 创建测试表
CREATE TABLE test (id bigserial PRIMARY KEY, embedding vector(3));
# 插入测试数据
INSERT INTO test (embedding) VALUES ('[1,2,3]'), ('[4,5,6]');
# 按与给定向量相似度(L2 distance)排序,显示前5条
SELECT * FROM test ORDER BY embedding <-> '[3,1,2]' LIMIT 5;
执行如下: