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

相关推荐
冷雨夜中漫步4 小时前
Python快速入门(6)——for/if/while语句
开发语言·经验分享·笔记·python
郝学胜-神的一滴4 小时前
深入解析Python字典的继承关系:从abc模块看设计之美
网络·数据结构·python·程序人生
百锦再4 小时前
Reactive编程入门:Project Reactor 深度指南
前端·javascript·python·react.js·django·前端框架·reactjs
喵手6 小时前
Python爬虫实战:旅游数据采集实战 - 携程&去哪儿酒店机票价格监控完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集结果csv导出·旅游数据采集·携程/去哪儿酒店机票价格监控
2501_944934736 小时前
高职大数据技术专业,CDA和Python认证优先考哪个?
大数据·开发语言·python
helloworldandy6 小时前
使用Pandas进行数据分析:从数据清洗到可视化
jvm·数据库·python
肖永威7 小时前
macOS环境安装/卸载python实践笔记
笔记·python·macos
TechWJ8 小时前
PyPTO编程范式深度解读:让NPU开发像写Python一样简单
开发语言·python·cann·pypto
数据知道8 小时前
PostgreSQL 故障排查:如何找出数据库中最耗时的 SQL 语句
数据库·sql·postgresql
枷锁—sha8 小时前
【SRC】SQL注入WAF 绕过应对策略(二)
网络·数据库·python·sql·安全·网络安全