(二)PosrgreSQL: Python3 连接Pgvector出错排查

在使用 Python 连接到 PostgreSQL 数据库,特别是当涉及到 pgvector 扩展以处理向量数据时,可能会遇到一些问题。本文针对psycopg2连接pgvector进行插入和查询操作失败问题,分享了一种可行的解决方案。

1. 安装并启用pgvector扩展

确保PostgreSQL数据库已经安装了 pgvector 扩展,并且该扩展已在你要使用的数据库中启用。你可以通过以下 SQL 命令来启用它:

sql 复制代码
CREATE EXTENSION IF NOT EXISTS pgvector;

创建启用pgvector的表items

sql 复制代码
CREATE TABLE items (
  id SERIAL PRIMARY KEY,
  embedding vector(3)
);

2. python脚本操作pgvector表

在Python环境中,需要安装python模块psycopg2支持对PostgreSQL的访问。采用(pgvector Tutorial: Integrate Vector Search into PostgreSQL)[https://www.datacamp.com/tutorial/pgvector-tutorial\] 所展示的连接pgvecyor的python3代码块进行测试

python 复制代码
import psycopg2
import numpy as np

# Connect to the database
conn = psycopg2.connect("dbname=your_database user=your_username")
cur = conn.cursor()

# Insert a vector
embedding = np.array([1.5, 2.5, 3.5])
cur.execute("INSERT INTO items (embedding) VALUES (%s)", (embedding.tolist(),))

# Perform a similarity search
query_vector = np.array([2, 3, 4])
cur.execute("SELECT * FROM items ORDER BY embedding <-> %s LIMIT 1", (query_vector.tolist(),))
result = cur.fetchone()
print(f"Nearest neighbor: {result}")

conn.commit()
cur.close()
conn.close()

运行python代码抛错如下

shell 复制代码
---------------------------------------------------------------------------
UndefinedFunction                         Traceback (most recent call last)
Cell In[4], line 14
     12 # Perform a similarity search
     13 query_vector = np.array([2, 3, 4])
---> 14 cur.execute("SELECT * FROM items ORDER BY embedding <-> %s LIMIT 1", (query_vector.tolist(),))
     15 result = cur.fetchone()
     16 print(f"Nearest neighbor: {result}")

UndefinedFunction: operator does not exist: vector <-> integer[]
LINE 1: SELECT * FROM items ORDER BY embedding <-> ARRAY[2,3,4] LIMI...
                                               ^
HINT:  No operator matches the given name and argument types. You might need to add explicit type casts.

修改出错行为如下值,再次运行依然报错。

python 复制代码
cur.execute("SELECT * FROM items ORDER BY embedding <-> %s LIMIT 1", (query_vector,))

错误日志

shell 复制代码
---------------------------------------------------------------------------
ProgrammingError                          Traceback (most recent call last)
Cell In[5], line 14
     12 # Perform a similarity search
     13 query_vector = np.array([2, 3, 4])
---> 14 cur.execute("SELECT * FROM items ORDER BY embedding <-> %s LIMIT 1", (query_vector,))
     15 result = cur.fetchone()
     16 print(f"Nearest neighbor: {result}")

ProgrammingError: can't adapt type 'numpy.ndarray'

3. 引入python pgvector模块

为了使psycopg2能够支持PostgreSQL中的向量类型,你需要通过pgvector中的register_vector方法,对psycopg2进行注册,可以在SQL语句中支持使用Numpy数组,或者numpy array转换后的列表变量。修改后的代码如下:

python 复制代码
import psycopg2
import numpy as np
from pgvector.psycopg2 import register_vector

# Connect to the database
conn = psycopg2.connect("dbname=postgres user=hbu host=localhost")
register_vector(conn)
cur = conn.cursor()

# Insert a vector
embedding = np.array([1.5, 2.5, 3.5])
cur.execute("INSERT INTO items (embedding) VALUES (%s)", (embedding.tolist(),))

# Perform a similarity search
query_vector = np.array([2, 3, 4])
cur.execute("SELECT * FROM items ORDER BY embedding <-> %s LIMIT 1", (query_vector,))
result = cur.fetchone()
print(f"Nearest neighbor: {result}")

conn.commit()
cur.close()
conn.close()

运行结果如下:

shell 复制代码
Nearest neighbor: (9, None, None, array([1.5, 2.5, 3.5], dtype=float32))

总结

采用Python操作pgvector表时,主要启用pgvector模块对连接进行而外操作才行。以下是一些注意要点:

  • 确保pgvector扩展已安装并启用
  • 仔细检查代码中的方法名和SQL语句
  • 正确安装和导入Python依赖模块psycopg2和pgvector
  • 使用python模块pgvector中register_vector方法,对创建的psycopg2连接变量进行注册
  • 使用numpy array类型,个别情况不需要转换为list(即不需要query_vector.tolist()转换numpy array)

通过以上步骤,我顺利解决连接pgvector 表,查询失败的问题,并成功执行PostgreSQL pgvector向量扩展的插入与查询操作。

相关推荐
我的xiaodoujiao6 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 38--Allure 测试报告
python·学习·测试工具·pytest
沈浩(种子思维作者)12 小时前
真的能精准医疗吗?癌症能提前发现吗?
人工智能·python·网络安全·健康医疗·量子计算
njsgcs13 小时前
ue python二次开发启动教程+ 导入fbx到指定文件夹
开发语言·python·unreal engine·ue
io_T_T13 小时前
迭代器 iteration、iter 与 多线程 concurrent 交叉实践(详细)
python
华研前沿标杆游学14 小时前
2026年走进洛阳格力工厂参观游学
python
Carl_奕然14 小时前
【数据挖掘】数据挖掘必会技能之:A/B测试
人工智能·python·数据挖掘·数据分析
AI小怪兽14 小时前
基于YOLOv13的汽车零件分割系统(Python源码+数据集+Pyside6界面)
开发语言·python·yolo·无人机
wszy180914 小时前
新文章标签:让用户一眼发现最新内容
java·python·harmonyos
Eric.Lee202114 小时前
python实现 mp4转gif文件
开发语言·python·手势识别·手势交互·手势建模·xr混合现实
EntyIU14 小时前
python开发中虚拟环境配置
开发语言·python