# 模型配置

你可以使用 `config()` 宏来实现更细粒度且更强大的模型控制。

## `config()` 的特点

### **1. 物化设置**

`config()` 宏使用户能够决定模型在分析数据库中的物化方式，常见的物化策略包括：

* **Table（表）**：模型以表的形式创建。
* **View（视图）**：模型以视图的形式创建。
* **Incremental（增量）**：模型以增量方式构建，仅更新自上次运行以来的新数据，提高大数据集的处理效率。

### **2. 主键和分区设置**

使用 `config()` 宏定义的配置可以继承或覆盖其他位置（如模型的元数据）中定义的设置。用户可以在 `config()` 宏中定义多种配置，包括：

* 为增量模型设置主键（unique key）。
* 指定增量策略（incremental strategy）。
* 指定分区（partition）。

不同数据库类型可以使用的 config 配置项有所差异，详见 [数据库特定配置](/cn-reorc-help-center/shu-ju-jian-mo/shu-ju-ku-te-ding-pei-zhi.md)

### **3. 配置示例**

config() 配置一般放置在模型代码的开头，例如：

```sql
-- models/model_name.sql
{{ config(
    materialized='incremental',
    unique_key='id'
) }}

SELECT *
FROM {{ ref('source_table') }}
```

***

## 配置增量模型

`config()` 宏的一个常见用途是定义数据模型的增量策略。

**增量（Incremental）** 是一种物化方式，每次运行时仅更新新增数据。相比于全量更新的表（Table），增量模型能够减少数据转换所需的时间和资源，适用于周期性更新的大数据集。

在模型的元数据面板中，你可以指定物化选项为 `incremental`。默认情况下，此选项采用 **追加（append）** 的方式，每次构建时仅向表中追加新数据，可能会导致重复数据的写入。

因此，你可以指定以下配置来实现按主键字段增量更新：

* **`unique_key`**：定义数据的唯一标识符，实际运行时会根据主键字段的取值是否已存在，来决定插入新记录还是更新现有记录。
* **`incremental_strategy`**：处理增量更新的方式，常见策略包括：
  * **merge**：基于唯一键更新现有记录并插入新记录。
  * **append**：仅追加新记录，不更新现有记录。
  * **insert\_overwrite**：根据指定条件覆盖现有记录。
* **`is_incremental()`**：用于筛选在运行过程中应增量更新的数据。你可以借助此语法指定增量更新的数据范围

**示例：**

在 `orders`（订单）表中，我们可以实现增量物化，使其仅处理自上次运行以来新增或更新的订单，以减少处理时间并确保表数据保持最新：

```sql
{{ config(
    materialized='incremental',
    unique_key='id',
    incremental_strategy='merge'
) }}

SELECT *  
FROM {{ source("public", "raw_orders") }}  
{% if is_incremental() %}  -- 仅处理新记录
    WHERE ordered_at >= (SELECT MAX(ordered_at) FROM {{ this }})
{% endif %}
```

***

### 数据库特定配置

由于不同数据库平台在优化数据处理方面采用不同的方法，因此某些配置是专门为特定平台设计和应用的。有关这些平台特定配置和行为的详细信息，请参考 **PLATFORM SPECIFIC** 文档。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.reorc.com/cn-reorc-help-center/shu-ju-jian-mo/mo-xing/mo-xing-pei-zhi.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
