数据库与集合 #
一、数据库层级结构 #
1.1 层级概述 #
text
FaunaDB层级结构:
├── 账户(Account)
│ └── 数据库(Database)
│ └── 集合(Collection)
│ └── 文档(Document)
│ └── 字段(Field)
1.2 数据库概念 #
text
数据库特点:
├── 逻辑隔离的数据容器
├── 支持嵌套数据库
├── 独立的密钥和权限
├── 独立的索引和函数
└── 可配置区域
二、数据库管理 #
2.1 创建数据库 #
javascript
// 创建顶级数据库
CreateDatabase({
name: "my_database"
})
// 创建带配置的数据库
CreateDatabase({
name: "production",
global": true, // 全球分布
num_bytes: 0, // 初始字节数
num_collections: 0 // 初始集合数
})
// 创建子数据库
CreateDatabase({
name: "child_database"
}, {
parent: Database("parent_database")
})
2.2 查询数据库 #
javascript
// 获取数据库引用
Database("my_database")
// 检查数据库是否存在
Exists(Database("my_database"))
// 获取数据库信息
Get(Database("my_database"))
// 列出所有数据库
Paginate(Databases())
2.3 删除数据库 #
javascript
// 删除数据库(会删除所有子资源)
Delete(Database("my_database"))
2.4 数据库信息 #
javascript
// 获取数据库详情
Get(Database("my_database"))
// 返回:
// {
// ref: Database("my_database"),
// name: "my_database",
// global: false,
// num_bytes: 1024,
// num_collections: 5,
// ...
// }
三、集合概述 #
3.1 什么是集合 #
text
集合特点:
├── 类似关系数据库的"表"
├── 存储相同类型的文档
├── 无需预定义Schema
├── 自动生成文档ID
└── 支持历史版本
3.2 集合与表对比 #
| 关系数据库表 | FaunaDB集合 |
|---|---|
| 固定Schema | 灵活Schema |
| 预定义列 | 动态字段 |
| 外键约束 | 引用关系 |
| 索引预定义 | 索引可动态创建 |
四、集合管理 #
4.1 创建集合 #
javascript
// 基本创建
CreateCollection({
name: "users"
})
// 带配置创建
CreateCollection({
name: "products",
history_days: 30, // 保留历史天数
ttl_days: null, // 文档TTL
permissions: {
create: Role("user"),
delete: Role("admin")
}
})
4.2 集合配置选项 #
javascript
// 完整配置示例
CreateCollection({
name: "orders",
// 历史版本保留天数(默认30天)
history_days: 30,
// 文档自动过期天数(null表示不过期)
ttl_days: null,
// 权限配置
permissions: {
create: Role("user"), // 谁可以创建
delete: Role("admin"), // 谁可以删除
history_read: Role("admin"), // 谁可以读取历史
history_write: Role("admin"), // 谁可以写入历史
read: Role("user"), // 谁可以读取
write: Role("user"), // 谁可以更新
unrestricted_read: false // 是否允许无限制读取
},
// 数据验证函数
document_schema: {
validate: Query(
Lambda("doc",
And(
IsString(Select(["data", "name"], Var("doc"))),
IsNumber(Select(["data", "price"], Var("doc")))
)
)
)
}
})
4.3 查询集合 #
javascript
// 获取集合引用
Collection("users")
// 检查集合是否存在
Exists(Collection("users"))
// 获取集合信息
Get(Collection("users"))
// 列出所有集合
Paginate(Collections())
// 获取集合中的所有文档
Paginate(Documents(Collection("users")))
4.4 更新集合 #
javascript
// 更新集合配置
Update(Collection("users"), {
history_days: 60,
permissions: {
read: Role("user"),
write: Role("user")
}
})
4.5 删除集合 #
javascript
// 删除集合(会删除所有文档)
Delete(Collection("users"))
五、集合设计最佳实践 #
5.1 命名规范 #
text
命名建议:
├── 使用小写字母
├── 使用下划线分隔
├── 使用复数形式
├── 描述性名称
└── 示例:users, products, order_items
5.2 集合设计原则 #
text
设计原则:
├── 按实体类型分组
├── 考虑访问模式
├── 避免过度嵌套
├── 合理设置历史天数
└── 配置适当的权限
5.3 常见集合设计 #
javascript
// 用户集合
CreateCollection({
name: "users",
history_days: 30
})
// 产品集合
CreateCollection({
name: "products",
history_days: 7
})
// 订单集合
CreateCollection({
name: "orders",
history_days: 90
})
// 日志集合(短期保留)
CreateCollection({
name: "logs",
history_days: 7,
ttl_days: 30
})
// 会话集合(自动过期)
CreateCollection({
name: "sessions",
history_days: 0,
ttl_days: 7
})
六、嵌套数据库 #
6.1 嵌套结构 #
text
嵌套数据库示例:
├── production(生产环境)
│ ├── api(API服务)
│ │ ├── users
│ │ └── products
│ └── analytics(分析服务)
│ ├── events
│ └── reports
└── development(开发环境)
└── ...
6.2 创建嵌套数据库 #
javascript
// 创建父数据库
CreateDatabase({ name: "production" })
// 创建子数据库
CreateDatabase(
{ name: "api" },
{ parent: Database("production") }
)
// 在子数据库中创建集合
CreateCollection(
{ name: "users" },
{ scope: Database("api", Database("production")) }
)
6.3 访问嵌套数据库 #
javascript
// 访问子数据库
Database("api", Database("production"))
// 访问子数据库中的集合
Collection("users", Database("api", Database("production")))
七、区域配置 #
7.1 区域组 #
text
FaunaDB区域:
├── Classic(默认)
│ └── 美国和欧洲
├── United States (US)
│ └── 美国区域
└── Europe (EU)
└── 欧洲区域
7.2 创建区域数据库 #
javascript
// 创建全球分布式数据库
CreateDatabase({
name: "global_app",
global: true
})
// 创建区域特定数据库
CreateDatabase({
name: "us_app",
region_group: "us"
})
八、权限配置 #
8.1 集合级权限 #
javascript
// 配置集合权限
CreateCollection({
name: "posts",
permissions: {
// 创建权限
create: Or(
Role("user"),
Role("admin")
),
// 读取权限
read: Or(
Role("user"),
Role("admin")
),
// 更新权限
write: Or(
Role("user"),
Role("admin")
),
// 删除权限
delete: Role("admin"),
// 历史读取权限
history_read: Role("admin"),
// 历史写入权限
history_write: Role("admin")
}
})
8.2 基于谓词的权限 #
javascript
// 使用谓词函数控制权限
CreateCollection({
name: "documents",
permissions: {
read: Query(
Lambda("ref",
Let(
{
doc: Get(Var("ref")),
owner: Select(["data", "ownerId"], Var("doc")),
currentUser: CurrentIdentity()
},
Or(
Equals(Var("owner"), Var("currentUser")),
HasRole(Role("admin"))
)
)
)
),
write: Query(
Lambda("ref",
Let(
{
doc: Get(Var("ref")),
owner: Select(["data", "ownerId"], Var("doc")),
currentUser: CurrentIdentity()
},
Equals(Var("owner"), Var("currentUser"))
)
)
)
}
})
九、集合统计 #
9.1 获取集合统计 #
javascript
// 获取集合信息
Get(Collection("users"))
// 返回:
// {
// ref: Collection("users"),
// name: "users",
// ts: 1704067200000000,
// history_days: 30,
// num_documents: 1000,
// num_bytes: 102400
// }
9.2 文档计数 #
javascript
// 统计文档数量
Count(Documents(Collection("users")))
// 带条件的计数
Count(
Filter(
Documents(Collection("users")),
Lambda("ref",
Let(
{ doc: Get(Var("ref")) },
Equals(Select(["data", "status"], Var("doc")), "active")
)
)
)
)
十、实际应用示例 #
10.1 电商数据库设计 #
javascript
// 创建数据库
CreateDatabase({ name: "ecommerce" })
// 创建用户集合
CreateCollection({
name: "users",
history_days: 30
})
// 创建产品集合
CreateCollection({
name: "products",
history_days: 7
})
// 创建订单集合
CreateCollection({
name: "orders",
history_days: 90
})
// 创建评论集合
CreateCollection({
name: "reviews",
history_days: 30
})
// 创建购物车集合
CreateCollection({
name: "carts",
history_days: 7,
ttl_days: 14
})
10.2 多租户数据库设计 #
javascript
// 创建租户数据库
CreateDatabase({ name: "tenant_001" })
// 在租户数据库中创建集合
CreateCollection(
{ name: "users" },
{ scope: Database("tenant_001") }
)
CreateCollection(
{ name: "data" },
{ scope: Database("tenant_001") }
)
十一、常见问题 #
11.1 集合不存在错误 #
javascript
// 安全检查集合存在
If(
Exists(Collection("users")),
Get(Collection("users")),
CreateCollection({ name: "users" })
)
11.2 数据库不存在错误 #
javascript
// 安全检查数据库存在
If(
Exists(Database("my_database")),
Get(Database("my_database")),
Abort("Database not found")
)
十二、总结 #
数据库与集合要点:
| 概念 | 说明 |
|---|---|
| Database | 逻辑隔离的数据容器 |
| Collection | 文档的集合 |
| 嵌套数据库 | 支持层级结构 |
| history_days | 历史版本保留天数 |
| ttl_days | 文档自动过期天数 |
| permissions | 访问权限控制 |
下一步,让我们学习文档结构!
最后更新:2026-03-27