You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python检查Supabase中指定名称的Collection是否存在?

检查Supabase中PGVector集合是否存在的方法

LangChain的PGVector集成会把集合元数据存储在langchain_pg_collection表中,你可以通过查询这个表判断目标集合是否存在,避免重复创建。以下是两种可行的实现方式:

方式1:使用Supabase客户端查询

利用已创建的Supabase客户端直接查询集合元数据表:

Client = supabase_py.create_client(url, key)

# 检查名为symbol的集合是否存在
collection_exists = Client.table("langchain_pg_collection").select("id").eq("name", symbol).execute().data

if not collection_exists:
    # 集合不存在时才创建并插入数据
    db = PGVector.from_documents(
        embedding=embeddings,
        documents=texts_to_embed,
        collection_name=symbol,
        connection_string=CONNECTION_STRING,
    )
else:
    # 加载已存在的集合
    db = PGVector(
        embedding_function=embeddings,
        collection_name=symbol,
        connection_string=CONNECTION_STRING,
    )

方式2:直接执行SQL查询

通过PostgreSQL连接直接查询,适合不想依赖Supabase客户端的场景:

import psycopg2
from psycopg2 import sql

CONNECTION_STRING = PGVector.connection_string_from_db_params(
    driver=os.environ.get("PGVECTOR_DRIVER", "psycopg2"),
    host=os.environ.get("PGVECTOR_HOST", "db.xxxxxx.supabase.co"),
    port=int(os.environ.get("PGVECTOR_PORT", "XXXX")),
    database=os.environ.get("PGVECTOR_DATABASE", "postgres"),
    user=os.environ.get("PGVECTOR_USER", "postgres"),
    password=os.environ.get("PGVECTOR_PASSWORD", "XXXXXXX"),
)

# 检查集合是否存在
collection_exists = False
conn = psycopg2.connect(CONNECTION_STRING)
try:
    with conn.cursor() as cur:
        cur.execute(
            sql.SQL("SELECT id FROM langchain_pg_collection WHERE name = %s"),
            (symbol,)
        )
        collection_exists = cur.fetchone() is not None
finally:
    conn.close()

if not collection_exists:
    db = PGVector.from_documents(
        embedding=embeddings,
        documents=texts_to_embed,
        collection_name=symbol,
        connection_string=CONNECTION_STRING,
    )
else:
    db = PGVector(
        embedding_function=embeddings,
        collection_name=symbol,
        connection_string=CONNECTION_STRING,
    )

注意事项

  • langchain_pg_collection表是LangChain的PGVector集成自动创建的,第一次运行from_documents时会生成该表及对应的向量数据表。
  • 如果你的PGVector使用了自定义表前缀,需要将查询中的表名替换为带前缀的版本(比如自定义前缀为my_prefix_,则表名为my_prefix_langchain_pg_collection)。

内容的提问来源于stack exchange,提问作者user1123417

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 17:57:44