PostgreSQL 15 + pgvector 安装

1,220 阅读3分钟

前言

最近在学习向量数据库相关的内容,考虑到上手难度和对Java语言的支持,没有直接使用 milvus 这种专业的向量数据库。

除了选择专业的向量数据库,使用传统数据库进行扩展也是一种方法。例如: Redis 提供了Redis Modules 扩展, 基于此我们可以使用 RediSearch 模块来扩展向量搜索的功能。

同理还有今天要介绍的 PostgreSQL, PostgreSQL 提供使用 extension 的方式来扩展数据库的功能, 在此基础上有人 开发了 pgvector 插件来开启向量搜索的功能。

使用传统数据带来的额外好处是,例如 pgvector 它是附加在 PostgreSQL 上的,因此可以利用 PostgreSQL 的所有功能,例如 ACID 事务、 并发控制、备份和恢复等。还拥有所有的 PostgreSQL 客户端库,因此可以使用任何语言的 PostgreSQL 客户端来访问它。 可以减少开发者的学习成本和服务的维护成本。

下面我将自己在 centos 下 安装 PostgreSQL + pgvector 的方式写下来,供大家参考。

在 CentOS 下安装 PostgreSQL + pgvector

安装环境

CentOS:CentOS Linux release 7.9.2009 (Core)
PostgreSQL:PostgreSQL 15
Postgres:v0.5.1

注意:
1、pgvector 需要 Postgres 11+ 版本
2、目前 PostgreSQL 高版本支持 CentOS 7 , 而且只到 PostgreSQL 15版本,PostgreSQL 15+ 版本可以使用Docker安装

PostgreSQL 15 安装

PostgreSQL官网:www.postgresql.org/download/li…

选择 PostgreSQL 15 版本

img_2.png

安装脚本

# Install the repository RPM:
> sudo yum install -y https://download.postgresql.org/pub/repos/yum/reporpms/EL-7-x86_64/pgdg-redhat-repo-latest.noarch.rpm

# Install PostgreSQL:
> sudo yum install -y postgresql15-server

# Optionally initialize the database and enable automatic start:
> sudo /usr/pgsql-15/bin/postgresql-15-setup initdb
> sudo systemctl enable postgresql-15
> sudo systemctl start postgresql-15

其他命令

> sudo systemctl status postgresql-15
> sudo systemctl stop postgresql-15
> sudo systemctl restart postgresql-15

# 卸载
> yum remove postgresql*

安装完成后,登录数据库,设置 postgres 的密码

# 通过su命令切换linux用户为postgres会自动进入命令行
# 安装postgresSQL时,他会自动创建一个postgres用户
> su - postgres

# 启动SQL Shell,
# 缺省用户名的情况下,会把当前系统用户名当作数据库登录用户名,数据库的postgres是超级用户
> psql

# 修改密码
> ALTER USER postgres WITH PASSWORD 'postgres';

#(可选)
# 修改 linux 的 postgres 用户密码
# 注意,这个密码很容易被猜到,被攻击
> sudo  passwd -d postgres
> sudo -u postgres passwd

img_3.png

pgvector 安装

pgvector仓库:github.com/pgvector/pg…

# yum 安装插件
> sudo yum install pgvector_15

创建用户、数据库、授权

# 创建用户
> CREATE USER dbroot WITH PASSWORD '123root';

# 创建数据库
> CREATE DATABASE vectdb OWNER dbroot;

# 赋权
> GRANT ALL PRIVILEGES ON DATABASE vectdb TO dbroot;

# 添加 superuser 权限,用于安装 pgvector 插件
alter user dbroot with superuser;

img_4.png

登录数据库、创建表并测试向量类型

# 本地登录
> psql -U dbroot -h localhost  -p 5432 -d vectdb

# 创建插件
> CREATE EXTENSION 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;

img_5.png

配置PostgreSQL 外网访问

> cd /var/lib/pgsql/15/data/

> vim postgresql.conf
#将监听地址修改为*
#默认listen_addresses配置是注释掉的,所以可以直接在配置文件开头加入该行
listen_addresses='*'

> vim pg_hba.conf
#在文件尾部加入
#注意,开启所有外网都能访问时,服务容易被攻击
host  all  all 0.0.0.0/0 md5

#重启PostgreSQL服务
sudo systemctl restart postgresql-15

其他命令

#查看所有数据库
> \l

#切换当前数据库
> \c vectdb

#查看当前数据库下所有表
> \d

#退出数据库
> \q

# 查询配置文件所在位置
> show config_file;

# 查询数据储存目录
> show data_directory;