> ## 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.

# Google firestore (native mode) 集成

> 使用 LangChain Python 集成 Google Firestore（原生模式）文档加载器。

> [Firestore](https://cloud.google.com/firestore) 是一种无服务器的文档型数据库，能够根据需求进行扩展。利用 Firestore 的 LangChain 集成扩展您的数据库应用程序，以构建 AI 驱动的体验。

本笔记本介绍了如何使用 [Firestore](https://cloud.google.com/firestore) 通过 `FirestoreLoader` 和 `FirestoreSaver` 来 [保存、加载和删除 langchain 文档](https://langchain-docs-zh.mintlify.site/langchain/oss/python/integrations/document_loaders.md)。

了解更多关于该包的信息，请访问 [GitHub](https://github.com/googleapis/langchain-google-firestore-python/)。

[![在 Colab 中打开](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/googleapis/langchain-google-firestore-python/blob/main/docs/document_loader.ipynb)

## 开始前

要运行此笔记本，您需要执行以下操作：

* [创建 Google Cloud 项目](https://developers.google.com/workspace/guides/create-project)
* [启用 Firestore API](https://console.cloud.google.com/flows/enableapi?apiid=firestore.googleapis.com)
* [创建 Firestore 数据库](https://cloud.google.com/firestore/docs/manage-databases)

在确认此笔记本的运行环境中可以访问数据库后，请填写以下值并运行单元格，然后再运行示例脚本。

```python theme={null}
# @markdown Please specify a source for demo purpose.
SOURCE = "test"  # @param {type:"Query"|"CollectionGroup"|"DocumentReference"|"string"}
```

### 🦜🔗 库安装

集成位于其自己的 `langchain-google-firestore` 包中，因此我们需要安装它。

```python theme={null}
pip install -qU langchain-google-firestore
```

**Colab 仅限**：取消注释以下单元格以重启内核，或使用按钮重启内核。对于 Gemini Enterprise Agent Platform Workbench，您可以使用顶部的按钮重启终端。

```python theme={null}
# # 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)
```

### ☁ 设置您的 Google 云项目

设置您的 Google 云项目，以便您可以在本笔记本中利用 Google 云资源。

如果您不知道您的项目 ID，请尝试以下操作：

* 运行 `gcloud config list`。
* 运行 `gcloud projects list`。
* 查看支持页面：[定位项目 ID](https://support.google.com/googleapi/answer/7014113)。

```python theme={null}
# @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}
```

### 🔐 身份验证

以登录到本笔记本的 IAM 用户身份验证 Google Cloud，以便访问您的 Google Cloud 项目。

* 如果您使用 Colab 运行此笔记本，请使用以下单元格并继续。
* 如果您使用 Gemini Enterprise Agent Platform Workbench，请查看 [Gemini Enterprise Agent Platform Workbench 设置说明](https://github.com/GoogleCloudPlatform/generative-ai/tree/main/setup-env)。

```python theme={null}
from google.colab import auth

auth.authenticate_user()
```

## 基本用法

### 保存文档

`FirestoreSaver` 可以将文档存储到 Firestore。默认情况下，它将尝试从元数据中提取文档引用

使用 `FirestoreSaver.upsert_documents(<documents>)` 保存 langchain 文档。

```python theme={null}
from langchain_core.documents import Document
from langchain_google_firestore import FirestoreSaver

saver = FirestoreSaver()

data = [Document(page_content="Hello, World!")]

saver.upsert_documents(data)
```

#### 无引用保存文档

如果指定了集合，文档将使用自动生成的 ID 进行存储。

```python theme={null}
saver = FirestoreSaver("Collection")

saver.upsert_documents(data)
```

#### 使用其他引用保存文档

```python theme={null}
doc_ids = ["AnotherCollection/doc_id", "foo/bar"]
saver = FirestoreSaver()

saver.upsert_documents(documents=data, document_ids=doc_ids)
```

### 从集合或子集合加载

使用 `FirestoreLoader.load()` 或 `Firestore.lazy_load()` 加载 langchain 文档。`lazy_load` 返回一个生成器，该生成器仅在迭代期间查询数据库。要初始化 `FirestoreLoader` 类，您需要提供：

1. `source` - 一个查询、集合组、文档引用的实例，或 Firestore 集合的单个 `\`-分隔的路径。

```python theme={null}
from langchain_google_firestore import FirestoreLoader

loader_collection = FirestoreLoader("Collection")
loader_subcollection = FirestoreLoader("Collection/doc/SubCollection")


data_collection = loader_collection.load()
data_subcollection = loader_subcollection.load()
```

### 加载单个文档

```python theme={null}
from google.cloud import firestore

client = firestore.Client()
doc_ref = client.collection("foo").document("bar")

loader_document = FirestoreLoader(doc_ref)

data = loader_document.load()
```

### 从集合组或查询加载

```python theme={null}
from google.cloud.firestore import CollectionGroup, FieldFilter, Query

col_ref = client.collection("col_group")
collection_group = CollectionGroup(col_ref)

loader_group = FirestoreLoader(collection_group)

col_ref = client.collection("collection")
query = col_ref.where(filter=FieldFilter("region", "==", "west_coast"))

loader_query = FirestoreLoader(query)
```

### 删除文档

使用 `FirestoreSaver.delete_documents(<documents>)` 从 Firestore 集合中删除一系列 langchain 文档。

如果提供了文档 ID，则文档将被忽略。

```python theme={null}
saver = FirestoreSaver()

saver.delete_documents(data)

# The Documents will be ignored and only the document ids will be used.
saver.delete_documents(data, doc_ids)
```

## 高级用法

### 使用自定义文档页面内容和元数据加载文档

`page_content_fields` 和 `metadata_fields` 的参数将指定要写入 LangChain 文档 `page_content` 和 `metadata` 的 Firestore 文档字段。

```python theme={null}
loader = FirestoreLoader(
    source="foo/bar/subcol",
    page_content_fields=["data_field"],
    metadata_fields=["metadata_field"],
)

data = loader.load()
```

#### 自定义页面内容格式

当 `page_content` 只包含一个字段时，信息将是该字段的值。否则，`page_content` 将以 JSON 格式显示。

### 自定义连接和身份验证

```python theme={null}
from google.auth import compute_engine
from google.cloud.firestore import Client

client = Client(database="non-default-db", creds=compute_engine.Credentials())
loader = FirestoreLoader(
    source="foo",
    client=client,
)
```

***

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


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