(二)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向量扩展的插入与查询操作。

相关推荐
神仙别闹37 分钟前
基于Python实现上下消化道病历分类
开发语言·python·分类
m0_7403524239 分钟前
Layui如何解决表单select下拉框在移动端点击没反应
jvm·数据库·python
qq_3926906642 分钟前
Scikit-learn怎么实现协同过滤推荐_利用NearestNeighbors找相似用户
jvm·数据库·python
dfdfadffa42 分钟前
C#怎么使用TopLevel顶级语句 C#顶级语句怎么写如何省略Main方法简化控制台程序【语法】
jvm·数据库·python
qq_4135020243 分钟前
Workerman vs Swoole:2026高性能PHP框架怎么选?
jvm·数据库·python
xingpanvip1 小时前
星盘接口开发文档:天象盘接口指南
android·开发语言·python·php·lua
zjy277771 小时前
PHP源码对声卡有依赖吗_音频硬件无关性说明【方法】
jvm·数据库·python
2301_818008441 小时前
PHP函数如何适配高密度服务器机箱_PHP在紧凑硬件布局优化【操作】
jvm·数据库·python
Coisinilove1 小时前
机器学习——线性回归
python·机器学习·线性回归
谢的2元王国1 小时前
直接open source 我自己的py
python