> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Oracle AI vector search document processing 集成

> 使用 LangChain Python 集成 Oracle AI 向量搜索文档处理加载器。

Oracle AI 数据库通过将非结构化内容中的语义搜索与业务数据中的关系查询结合，在一个系统中支持文档中心式 AI 工作流。这使得构建检索工作流（如 RAG）时无需将数据与向量拆分到多个数据库。

在本指南中，您将学习如何：

* 从 Python 连接 Oracle 数据库
* 使用 `OracleDocLoader` 加载文档（从数据库表、文件或目录）
* 使用 `OracleTextSplitter` 分割内容以准备嵌入和检索

> **为什么在数据库内处理文档？**
> 您可以将 Oracle 数据库的能力（安全、事务、可扩展性、高可用性）应用于加载、分割和存储内容以支持 AI 搜索与检索的同一管道。

如果您刚开始使用 Oracle 数据库，建议探索 [免费 Oracle 26 AI](https://www.oracle.com/database/free/#resources)，该版本提供了一种快速入门的方式。在使用数据库时，通常建议避免使用 `SYSTEM` 用户处理应用负载；建议创建具有最小权限的专用用户。完整的端到端配置步骤请参考 [Oracle AI 向量搜索演示笔记本](https://github.com/langchain-ai/langchain/blob/v0.3/cookbook/oracleai_demo.ipynb)。关于用户管理的背景知识，请查阅官方 [Oracle 指南](https://docs.oracle.com/en/database/oracle/oracle-database/19/admqs/administering-user-accounts-and-security.html#GUID-36B21D72-1BBB-46C9-A0C9-F0D2A8591B8D)。

### 预先条件

安装 `langchain-oracledb`。`python-oracledb` 驱动会自动安装为依赖项。

```bash pip theme={null}
pip install -qU langchain-oracledb
```

```bash uv theme={null}
uv add langchain-oracledb
```

### 连接到 Oracle 数据库

以下示例代码将展示如何连接到 Oracle 数据库。默认情况下，python-oracledb 运行在“Thin”模式，直接连接到 Oracle 数据库。该模式无需 Oracle 客户端库。但使用客户端库时（即“Thick”模式），可提供更多功能。两种模式均完整支持 Python 数据库 API v2.0 规范。请参考 [此指南](https://python-oracledb.readthedocs.io/en/latest/user_guide/appendix_a.html#featuresummary)了解各模式支持的功能。如果您无法使用 Thin 模式，可能需要切换到 Thick 模式。

```python theme={null}
import sys

import oracledb

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

connection = oracledb.connect(user=username, password=password, dsn=dsn)
print("Connection successful!")
```

现在让我们创建一个表并插入一些测试文档。

```python theme={null}
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 向量搜索指南](https://docs.oracle.com/en/database/oracle/oracle-database/23/arpls/dbms_vector_chain1.html#GUID-73397E89-92FB-48ED-94BB-1AD960C4EA1F)。

使用 `OracleDocLoader` 的显著优势在于可处理超过 150 种不同格式的文档，无需为不同文档类型配置多个加载器。完整支持的格式列表请参考 [Oracle Text 支持的文档格式](https://docs.oracle.com/en/database/oracle/oracle-database/23/ccref/oracle-text-supported-document-formats.html)。

以下代码片段演示了 `OracleDocLoader` 的使用方法：

```python theme={null}
from langchain_oracledb.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
```

### 分割文档

文档大小可能从很小到非常大。用户通常倾向于将文档分割为较小部分以生成嵌入。分割过程提供丰富的定制选项。详细参数说明请查阅 [Oracle AI 向量搜索指南](https://docs.oracle.com/en/database/oracle/oracle-database/23/arpls/dbms_vector_chain1.html#GUID-4E145629-7098-4C7C-804F-FC85D1F24240)。

以下代码示例展示了如何实现该功能：

```python theme={null}
from langchain_oracledb.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
```

### 端到端演示

请参考完整演示指南 [Oracle AI 向量搜索端到端演示指南](https://github.com/langchain-ai/langchain/blob/v0.3/cookbook/oracleai_demo.ipynb)，使用 Oracle AI 向量搜索构建完整的 RAG 管道。

***

> 官方原文：[src/oss/python/integrations/document\_loaders/oracleai.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/python/integrations/document_loaders/oracleai.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.