Skip to main content
Open In ColabOpen on GitHub

Oracle AI 向量搜索:文档处理

Oracle AI向量搜索是为人工智能(AI)工作负载设计的,它允许您基于语义而非关键词查询数据。 Oracle AI向量搜索的一大优势在于可以将非结构化数据上的语义搜索与业务数据上的关系搜索结合在一个系统中使用。 这不仅非常强大而且更加有效,因为您不需要添加一个专门的向量数据库,从而避免了在多个系统之间进行数据碎片化的痛苦。

此外,您的向量可以利用Oracle数据库的所有最强大功能,例如以下内容:

The guide demonstrates how to use Document Processing Capabilities within Oracle AI Vector Search to load and chunk documents using OracleDocLoader and OracleTextSplitter respectively.

如果您是第一次使用 Oracle 数据库,可以考虑探索我们的 免费 Oracle 23 AI,它提供了一个很好的入门介绍来设置您的数据库环境。在操作数据库时,默认避免使用系统用户会更加安全和灵活;您可以创建自己的用户以增强安全性并进行个性化设置。有关用户创建的详细步骤,请参阅我们的 端到端指南,其中还介绍了如何在 Oracle 中设置用户。此外,了解用户权限对于有效管理数据库安全至关重要。您可以在官方 Oracle 指南 中了解更多关于管理用户帐户和安全性的内容。

前置条件

请安装Oracle Python客户端驱动以使用LangChain与Oracle AI向量搜索。

# pip install oracledb

连接到Oracle数据库

以下示例代码将展示如何连接到Oracle数据库。默认情况下,python-oracledb 以‘薄’模式运行,直接连接到 Oracle 数据库。这种模式不需要 Oracle 客户端库。但是,在使用这些库时会提供一些额外的功能性。当 python-oracledb 使用 Oracle 客户端库时,它被认为是以‘厚’模式运行的。两种模式都具有全面的功能以支持 Python 数据库 API v2.0 规范。请参阅以下 指南,其中介绍了每种模式所支持的特性。如果您无法使用薄模式,您可能需要切换到厚模式。

import sys

import oracledb

# please update with your username, password, hostname and service_name
username = "<username>"
password = "<password>"
dsn = "<hostname>/<service_name>"

try:
conn = oracledb.connect(user=username, password=password, dsn=dsn)
print("Connection successful!")
except Exception as e:
print("Connection failed!")
sys.exit(1)

现在让我们创建一个表格并插入一些样本文档以进行测试。

try:
cursor = conn.cursor()

drop_table_sql = """drop table if exists demo_tab"""
cursor.execute(drop_table_sql)

create_table_sql = """create table demo_tab (id number, data clob)"""
cursor.execute(create_table_sql)

insert_row_sql = """insert into demo_tab values (:1, :2)"""
rows_to_insert = [
(
1,
"If the answer to any preceding questions is yes, then the database stops the search and allocates space from the specified tablespace; otherwise, space is allocated from the database default shared temporary tablespace.",
),
(
2,
"A tablespace can be online (accessible) or offline (not accessible) whenever the database is open.\nA tablespace is usually online so that its data is available to users. The SYSTEM tablespace and temporary tablespaces cannot be taken offline.",
),
(
3,
"The database stores LOBs differently from other data types. Creating a LOB column implicitly creates a LOB segment and a LOB index. The tablespace containing the LOB segment and LOB index, which are always stored together, may be different from the tablespace containing the table.\nSometimes the database can store small amounts of LOB data in the table itself rather than in a separate LOB segment.",
),
]
cursor.executemany(insert_row_sql, rows_to_insert)

conn.commit()

print("Table created and populated.")
cursor.close()
except Exception as e:
print("Table creation failed.")
cursor.close()
conn.close()
sys.exit(1)

加载文档

用户可以根据需要通过适当配置加载器参数,从Oracle数据库、文件系统或两者中加载文档。有关这些参数的详细信息,请参阅Oracle AI向量搜索指南

使用 OracleDocLoader 的一个重要优势在于它可以处理超过150种不同的文件格式,从而避免为不同类型的文档类型使用多个加载器。要查看所有受支持的格式,请参阅 Oracle Text 支持的文档格式

以下是一个示例代码片段,展示了如何使用OracleDocLoader

from langchain_community.document_loaders.oracleai import OracleDocLoader
from langchain_core.documents import Document

"""
# loading a local file
loader_params = {}
loader_params["file"] = "<file>"

# loading from a local directory
loader_params = {}
loader_params["dir"] = "<directory>"
"""

# loading from Oracle Database table
loader_params = {
"owner": "<owner>",
"tablename": "demo_tab",
"colname": "data",
}

""" load the docs """
loader = OracleDocLoader(conn=conn, params=loader_params)
docs = loader.load()

""" verify """
print(f"Number of docs loaded: {len(docs)}")
# print(f"Document-0: {docs[0].page_content}") # content

Split Documents

The documents may vary in size, ranging from small to very large. Users often prefer to chunk their documents into smaller sections to facilitate the generation of embeddings. A wide array of customization options is available for this splitting process. For comprehensive details regarding these parameters, please consult the Oracle AI Vector Search Guide.

以下是样本代码,说明了如何实现此功能:

from langchain_community.document_loaders.oracleai import OracleTextSplitter
from langchain_core.documents import Document

"""
# Some examples
# split by chars, max 500 chars
splitter_params = {"split": "chars", "max": 500, "normalize": "all"}

# split by words, max 100 words
splitter_params = {"split": "words", "max": 100, "normalize": "all"}

# split by sentence, max 20 sentences
splitter_params = {"split": "sentence", "max": 20, "normalize": "all"}
"""

# split by default parameters
splitter_params = {"normalize": "all"}

# get the splitter instance
splitter = OracleTextSplitter(conn=conn, params=splitter_params)

list_chunks = []
for doc in docs:
chunks = splitter.split_text(doc.page_content)
list_chunks.extend(chunks)

""" verify """
print(f"Number of Chunks: {len(list_chunks)}")
# print(f"Chunk-0: {list_chunks[0]}") # content

End to End Demo

请参考我们的完整示例指南 Oracle AI向量搜索端到端示例指南,在Oracle AI向量搜索的帮助下构建完整的RAG流水线。