在使用 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向量扩展的插入与查询操作。