Google AlloyDB for PostgreSQL - AlloyDBDocumentStore
和 AlloyDBIndexStore
¶
AlloyDB 是一种完全托管的关系型数据库服务,提供高性能、无缝集成和出色的可扩展性。AlloyDB 与 PostgreSQL 100%兼容。利用 AlloyDB 的 LlamaIndex 集成,扩展您的数据库应用以构建由AI驱动的体验。
本笔记本介绍了如何使用 AlloyDB for PostgreSQL
,借助 AlloyDBDocumentStore
和 AlloyDBIndexStore
类来存储文档和索引。
在 GitHub 上了解更多关于该包的信息。
开始之前¶
要运行此笔记本,您需要执行以下操作:
🦙 库安装¶
安装集成库 llama-index-alloydb-pg
以及嵌入服务库 llama-index-embeddings-vertex
。
%pip install --upgrade --quiet llama-index-alloydb-pg llama-index-llms-vertex llama-index
仅限 Colab:取消注释以下单元格以重新启动内核,或使用按钮重新启动内核。对于 Vertex AI Workbench,您可以使用顶部的按钮重新启动终端。
# # Automatically restart kernel after installs so that your environment can access the new packages
# import IPython
# app = IPython.Application.instance()
# app.kernel.do_shutdown(True)
from google.colab import auth
auth.authenticate_user()
# @markdown Please fill in the value below with your Google Cloud project ID and then run the cell.
PROJECT_ID = "my-project-id" # @param {type:"string"}
# Set the project id
!gcloud config set project {PROJECT_ID}
PROJECT_ID = "my-project-id" # @param {type:"string"}
# 设置项目 ID
!gcloud config set project {PROJECT_ID}
基本用法¶
设置 AlloyDB 数据库值¶
在 AlloyDB 实例页面查找您的数据库值。
# @title Set Your Values Here { display-mode: "form" }
REGION = "us-central1" # @param {type: "string"}
CLUSTER = "my-cluster" # @param {type: "string"}
INSTANCE = "my-primary" # @param {type: "string"}
DATABASE = "my-database" # @param {type: "string"}
TABLE_NAME = "document_store" # @param {type: "string"}
USER = "postgres" # @param {type: "string"}
PASSWORD = "my-password" # @param {type: "string"}
REGION = "us-central1" # @param {type: "string"}
CLUSTER = "my-cluster" # @param {type: "string"}
INSTANCE = "my-primary" # @param {type: "string"}
DATABASE = "my-database" # @param {type: "string"}
TABLE_NAME = "document_store" # @param {type: "string"}
USER = "postgres" # @param {type: "string"}
PASSWORD = "my-password" # @param {type: "string"}
AlloyDBEngine 连接池¶
将 AlloyDB 设置为文档存储的要求和参数之一是 AlloyDBEngine
对象。AlloyDBEngine
配置了到 AlloyDB 数据库的连接池,使您的应用程序能够成功连接并遵循行业最佳实践。
使用 AlloyDBEngine.from_instance()
创建 AlloyDBEngine
只需提供 5 项信息:
project_id
:AlloyDB 实例所在的 Google Cloud 项目的项目 ID。region
:AlloyDB 实例所在的区域。cluster
:AlloyDB 集群的名称。instance
:AlloyDB 实例的名称。database
:要连接的 AlloyDB 实例上的数据库名称。
默认情况下,将使用 IAM 数据库认证作为数据库认证方法。此库使用从环境获取的应用程序默认凭据 (ADC) 所属的 IAM 主体。
或者,也可以使用内置数据库认证,通过用户名和密码访问 AlloyDB 数据库。只需向 AlloyDBEngine.from_instance()
提供可选的 user
和 password
参数即可。
user
:用于内置数据库认证和登录的数据库用户password
:用于内置数据库认证和登录的数据库密码。
注意:本教程演示了异步接口。所有异步方法都有对应的同步方法。
from llama_index_alloydb_pg import AlloyDBEngine
engine = await AlloyDBEngine.afrom_instance(
project_id=PROJECT_ID,
region=REGION,
cluster=CLUSTER,
instance=INSTANCE,
database=DATABASE,
user=USER,
password=PASSWORD,
)
AlloyDBEngine for AlloyDB Omni¶
要为 AlloyDB Omni 创建 AlloyDBEngine
,您需要一个连接 URL。AlloyDBEngine.from_connection_string
首先创建一个异步引擎,然后将其转换为 AlloyDBEngine
。这是一个使用 asyncpg
驱动程序的连接示例:
# Replace with your own AlloyDB Omni info
OMNI_USER = "my-omni-user"
OMNI_PASSWORD = ""
OMNI_HOST = "127.0.0.1"
OMNI_PORT = "5432"
OMNI_DATABASE = "my-omni-db"
connstring = f"postgresql+asyncpg://{OMNI_USER}:{OMNI_PASSWORD}@{OMNI_HOST}:{OMNI_PORT}/{OMNI_DATABASE}"
engine = AlloyDBEngine.from_connection_string(connstring)
OMNI_USER = "my-omni-user"
OMNI_PASSWORD = ""
OMNI_HOST = "127.0.0.1"
OMNI_PORT = "5432"
OMNI_DATABASE = "my-omni-db"
connstring = f"postgresql+asyncpg://{OMNI_USER}:{OMNI_PASSWORD}@{OMNI_HOST}:{OMNI_PORT}/{OMNI_DATABASE}"
engine = AlloyDBEngine.from_connection_string(connstring)
初始化表¶
AlloyDBDocumentStore
类需要一个数据库表。AlloyDBEngine
引擎有一个 helper 方法 init_doc_store_table()
,可用于为您创建具有适当模式的表。
await engine.ainit_doc_store_table(
table_name=TABLE_NAME,
)
table_name=TABLE_NAME,
)
可选提示:💡¶
您也可以通过在任何传递 table_name
的地方传递 schema_name
来指定模式名称。
SCHEMA_NAME = "my_schema"
await engine.ainit_doc_store_table(
table_name=TABLE_NAME,
schema_name=SCHEMA_NAME,
)
初始化默认 AlloyDBDocumentStore¶
from llama_index_alloydb_pg import AlloyDBDocumentStore
doc_store = await AlloyDBDocumentStore.create(
engine=engine,
table_name=TABLE_NAME,
# schema_name=SCHEMA_NAME
)
下载数据¶
!mkdir -p 'data/paul_graham/'
!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'
!wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'
加载文档¶
from llama_index.core import SimpleDirectoryReader
documents = SimpleDirectoryReader("./data/paul_graham").load_data()
print("Document ID:", documents[0].doc_id)
documents = SimpleDirectoryReader("./data/paul_graham").load_data()
print("文档 ID:", documents[0].doc_id)
解析为节点¶
from llama_index.core.node_parser import SentenceSplitter
nodes = SentenceSplitter().get_nodes_from_documents(documents)
设置 IndexStore¶
from llama_index_alloydb_pg import AlloyDBIndexStore
INDEX_TABLE_NAME = "index_store"
await engine.ainit_index_store_table(
table_name=INDEX_TABLE_NAME,
)
index_store = await AlloyDBIndexStore.create(
engine=engine,
table_name=INDEX_TABLE_NAME,
# schema_name=SCHEMA_NAME
)
添加到 Docstore¶
from llama_index.core import StorageContext
storage_context = StorageContext.from_defaults(
docstore=doc_store, index_store=index_store
)
storage_context.docstore.add_documents(nodes)
与索引一起使用¶
文档存储可以与多个索引一起使用。每个索引都使用相同的底层节点。
from llama_index.core import Settings, SimpleKeywordTableIndex, SummaryIndex
from llama_index.llms.vertex import Vertex
Settings.llm = Vertex(model="gemini-1.5-flash", project=PROJECT_ID)
summary_index = SummaryIndex(nodes, storage_context=storage_context)
keyword_table_index = SimpleKeywordTableIndex(
nodes, storage_context=storage_context
)
查询索引¶
query_engine = summary_index.as_query_engine()
response = query_engine.query("What did the author do?")
print(response)
加载现有索引¶
文档存储可以与多个索引一起使用。每个索引都使用相同的底层节点。
# note down index IDs
list_id = summary_index.index_id
keyword_id = keyword_table_index.index_id
list_id = summary_index.index_id
keyword_id = keyword_table_index.index_id
from llama_index.core import load_index_from_storage
# re-create storage context
storage_context = StorageContext.from_defaults(
docstore=doc_store, index_store=index_store
)
# load indices
summary_index = load_index_from_storage(
storage_context=storage_context, index_id=list_id
)
keyword_table_index = load_index_from_storage(
storage_context=storage_context, index_id=keyword_id
)
# 重新创建存储上下文
storage_context = StorageContext.from_defaults(
docstore=doc_store,
index_store=index_store
)
# 加载索引
summary_index = load_index_from_storage(
storage_context=storage_context,
index_id=list_id
)
keyword_table_index = load_index_from_storage(
storage_context=storage_context,
index_id=keyword_id
)