使用 Declarative Automation Bundles 提供 Feature Views

Important

這項功能處於個人預覽版狀態。 若要試用,請洽詢您的 Azure Databricks 連絡人。

宣告式自動化套件(前稱 Databricks 資產套件)讓您能以程式化方式驗證、部署並執行 Azure Databricks 資源,例如功能檢視及其服務端點。 請參閱「什麼是宣告式自動化套件?」。

本教學建立一個套件,宣告兩個串流 功能檢視,將它們實體化到線上商店,並透過 FeatureSpec 和功能服務端點提供它們。 接著你查詢端點,改變它提供哪些特徵,然後把所有東西拆掉。

功能檢視及其具體化內容遵循使用宣告式自動化套件管理功能檢視,其中有詳細說明。 若要改用 Python API 建立 FeatureSpec 和端點,請參閱「部署 Feature Views」。

每個步驟都會以 YAML 和 Python 兩種方式顯示該設定。 選擇一種語言,頁面就會依照你的選擇變更。

Requirements

若要完成本教學課程,您需要下列項目:

  • Databricks CLI 版本 1.26.0 或以上。 執行 databricks --version 來檢查。 請參閱安裝或更新 Databricks CLI。
  • 一個支援 Unity Catalog 的工作區。 請參閱 需求。
  • 建立功能並將其具體化的權限 請參閱 權限。
  • 建立模型服務端點的權限。 請參見 身份與存取。
  • 現有的線上商店。 請參閱 「建立線上商店」。
  • 一個現有的 Stream。 串流不是套件資源,因此請先建立它,並在套件中以名稱引用它。 請參閱 「建立串流」。
  • Python 3.10 或以上版本,以 Python 宣告資源。

以組合形式提供資源

一個套件透過兩種資源類型提供功能檢視:

  • FeatureSpec:一個列出要提供服務的特徵的 Unity Catalog 函數。 它沒有任何特徵值。 提供這些資料的端點會從功能檢視所實體化的線上資料表讀取這些資料。 請參閱「使用 FeatureSpec 提供特徵服務」,另請參閱設定參考 feature_spec。
  • 功能服務端點:一種模型服務端點,提供 FeatureSpec,而不是模型。 一個套件會將其宣告為 model_serving_endpoints 資源。 有關組態參考文件,請參閱 model_serving_endpoint。

從套件提供 Feature Views

以下步驟包括建置與部署套件、查詢端點、變更其服務內容,以及清理資源。

設定認證

首先,在你的開發機器上設定 Databricks CLI 與 Azure Databricks 工作區之間的驗證。 此頁面假設您希望使用 OAuth 使用者到機器 (U2M) 驗證,以及名為 DEFAULT 的對應 Azure Databricks 組態設定檔進行驗證。

Note

U2M 驗證適用於即時試用這些步驟。 針對完全自動化的工作流程,Databricks 建議您改用 OAuth 機器對機器 (M2M) 驗證。 請參閱 使用 OAuth 授權服務主體存取 Azure Databricks 中的 M2M 驗證設定指示。

  1. 使用 Databricks CLI 在本地端啟動 OAuth 權杖管理,針對每個目標工作區執行以下命令。

    在下列命令中,將 <workspace-url> 替換成 您的 Azure Databricks 個別工作區的 URL,例如 https://adb-1234567890123456.7.azuredatabricks.net。

    databricks auth login --host <workspace-url>
    
  2. Databricks CLI 會提示你將輸入的資訊儲存為 Azure Databricks configuration profile。 按 Enter 以接受建議的設定檔名稱,或輸入新或現有設定檔的名稱。 任何具有相同名稱的現有設定檔,會被您輸入的資訊覆蓋。 您可以使用個人檔案,在多個工作區之間快速切換您的驗證環境。

    若要取得任何現有設定檔的清單,請在個別的終端機或命令提示字元中,使用 Databricks CLI 來執行 databricks auth profiles 命令。 若要檢視特定設定檔的現有設定,請執行 命令 databricks auth env --profile <profile-name>。

  3. 在網頁瀏覽器中,完成畫面上的指示,登入 Azure Databricks 工作區。

  4. 若要檢視配置檔目前的 OAuth 令牌值和令牌即將到期的時間戳,請執行下列其中一個命令:

    • databricks auth token --host <workspace-url>
    • databricks auth token -p <profile-name>
    • databricks auth token --host <workspace-url> -p <profile-name>

    如果您有多個具有相同 --host 值的設定檔,您可能需要一起指定 --host 和 -p 選項,以協助 Databricks CLI 尋找正確的相符 OAuth 權杖資訊。

建立組合

為該套件建立一個空白目錄, databricks.yml 根目錄有一個檔案,旁邊則有一個 resources 目錄。

YAML

以下每個步驟都會在 resources/ 下新增一個檔案:

databricks.yml
resources/
  streaming_features.yml
  feature_spec.yml
  serving_endpoint.yml

databricks.yml 包含 bundle 名稱、載入 resources/ 下所有檔案的 include 條目,以及資源參考的變數:

bundle:
  name: feature-serving-quickstart

include:
  - resources/*.yml

variables:
  catalog:
    description: The catalog that the Feature Views and the FeatureSpec are written to.
    default: main
  schema:
    description: The schema that the Feature Views and the FeatureSpec are written to.
    default: features_demo
  stream:
    description: The three-level name of a Stream registered in Unity Catalog.
    default: main.features_demo.events
  online_store:
    description: The online store that serves the features.
    default: my_online_store
  endpoint_name:
    description: The name of the Feature Serving endpoint.
    default: event-features

Python

以 Python 宣告的資源僅能透過在 databricks.yml 中的 python 映射找到。 沒有它,套件會成功驗證並部署,但不含任何資源,因此請立即新增:

bundle:
  name: feature-serving-quickstart

python:
  venv_path: .venv
  resources:
    - 'resources:load_resources'

variables:
  catalog:
    description: The catalog that the Feature Views and the FeatureSpec are written to.
    default: main
  schema:
    description: The schema that the Feature Views and the FeatureSpec are written to.
    default: features_demo
  stream:
    description: The three-level name of a Stream registered in Unity Catalog.
    default: main.features_demo.events
  online_store:
    description: The online store that serves the features.
    default: my_online_store
  endpoint_name:
    description: The name of the Feature Serving endpoint.
    default: event-features

建立專案及其虛擬環境,並新增套件:

uv init --bare
uv venv .venv
uv add databricks-bundles

建立resources/__init__.py,並使用名為databricks.yml的函式:

from databricks.bundles.core import Bundle, Resources


def load_resources(bundle: Bundle) -> Resources:
    resources = Resources()
    # The following steps add resources here.
    return resources

宣告特徵檢視及其實現

兩個功能檢視會讀取相同的串流,並在過去 90 分鐘內依每個鍵彙總。 events_90m 計算事件,並 amount_sum_90m 將 value.amount 加總。 其中一組實體化集合以串流模式將兩者寫入線上商店。 關於每個設定鍵的意義,請參閱 功能檢視教學的步驟 4。

串流特徵檢視將輸入欄位視為串流記錄中的路徑,因此請將範例顯示 value.* 的地方替換為您的串流結構所使用的名稱。

YAML

創建 resources/streaming_features.yml:

resources:
  features:
    events_90m:
      full_name: ${var.catalog}.${var.schema}.events_90m
      description: Events per key over a trailing 90 minutes
      source:
        stream_source:
          full_name: ${var.stream}
      function:
        aggregation_function:
          count_function:
            input: value.amount
          time_window:
            rolling:
              window_duration: 5400s
      entities:
        - name: value.key
      timeseries_column:
        name: value.event_timestamp

    amount_sum_90m:
      full_name: ${var.catalog}.${var.schema}.amount_sum_90m
      description: Sum of amount per key over a trailing 90 minutes
      source:
        stream_source:
          full_name: ${var.stream}
      function:
        aggregation_function:
          sum:
            input: value.amount
          time_window:
            rolling:
              window_duration: 5400s
      entities:
        - name: value.key
      timeseries_column:
        name: value.event_timestamp

  materialization_sets:
    serving_online:
      materialized_features:
        - feature_name: ${resources.features.events_90m.full_name}
          online_store_config:
            online_store_name: ${var.online_store}
            catalog_name: ${var.catalog}
            schema_name: ${var.schema}
            table_name_prefix: serving_online
          streaming_mode:
            mode: STREAMING_MODE_TYPE_RTM
        - feature_name: ${resources.features.amount_sum_90m.full_name}
          online_store_config:
            online_store_name: ${var.online_store}
            catalog_name: ${var.catalog}
            schema_name: ${var.schema}
            table_name_prefix: serving_online
          streaming_mode:
            mode: STREAMING_MODE_TYPE_RTM

Python

將匯入新增到 resources/__init__.py:

from databricks.bundles.features import (
    AggregationFunction,
    CountFunction,
    DataSource,
    EntityColumn,
    Feature,
    Function,
    RollingWindow,
    StreamSource,
    SumFunction,
    TimeseriesColumn,
    TimeWindow,
)
from databricks.bundles.materialization_sets import (
    MaterializationSet,
    MaterializedFeature,
    OnlineStoreConfig,
    StreamingMode,
    StreamingModeStreamingModeType,
)

然後將此加入主 load_resources體:

resources.add_feature(
    'events_90m',
    Feature(
        full_name='${var.catalog}.${var.schema}.events_90m',
        description='Events per key over a trailing 90 minutes',
        source=DataSource(stream_source=StreamSource(full_name='${var.stream}')),
        function=Function(
            aggregation_function=AggregationFunction(
                count_function=CountFunction(input='value.amount'),
                time_window=TimeWindow(rolling=RollingWindow(window_duration='5400s')),
            )
        ),
        entities=[EntityColumn(name='value.key')],
        timeseries_column=TimeseriesColumn(name='value.event_timestamp'),
    ),
)

resources.add_feature(
    'amount_sum_90m',
    Feature(
        full_name='${var.catalog}.${var.schema}.amount_sum_90m',
        description='Sum of amount per key over a trailing 90 minutes',
        source=DataSource(stream_source=StreamSource(full_name='${var.stream}')),
        function=Function(
            aggregation_function=AggregationFunction(
                sum=SumFunction(input='value.amount'),
                time_window=TimeWindow(rolling=RollingWindow(window_duration='5400s')),
            )
        ),
        entities=[EntityColumn(name='value.key')],
        timeseries_column=TimeseriesColumn(name='value.event_timestamp'),
    ),
)

resources.add_materialization_set(
    'serving_online',
    MaterializationSet(
        materialized_features=[
            MaterializedFeature(
                feature_name='${resources.features.events_90m.full_name}',
                online_store_config=OnlineStoreConfig(
                    online_store_name='${var.online_store}',
                    catalog_name='${var.catalog}',
                    schema_name='${var.schema}',
                    table_name_prefix='serving_online',
                ),
                streaming_mode=StreamingMode(
                    mode=StreamingModeStreamingModeType.STREAMING_MODE_TYPE_RTM
                ),
            ),
            MaterializedFeature(
                feature_name='${resources.features.amount_sum_90m.full_name}',
                online_store_config=OnlineStoreConfig(
                    online_store_name='${var.online_store}',
                    catalog_name='${var.catalog}',
                    schema_name='${var.schema}',
                    table_name_prefix='serving_online',
                ),
                streaming_mode=StreamingMode(
                    mode=StreamingModeStreamingModeType.STREAMING_MODE_TYPE_RTM
                ),
            ),
        ]
    ),
)

新增功能規範

此清單 FeatureSpec 列出此端點提供的功能。 在 features 中的每個項目都會以 declarative_feature 標示一個特徵檢視。

FeatureSpec 只能在其所命名的每個功能檢視都實體化到線上商店後才會被建立。 amount_sum_90m 中的 events_90m 參照使規格依賴於 Feature View lifecycle.depends_on 和 serving_online,而 declarative_feature 則加入了參照中未表達的、對實體化集合 ${resources.features...} 的依賴。 組合包會在這三者之後建立該規格,並在三者之前刪除。 請參閱 「功能規範必須符合的規則」。

YAML

創建 resources/feature_spec.yml:

resources:
  feature_specs:
    event_features:
      name: ${var.catalog}.${var.schema}.event_features
      features:
        - declarative_feature:
            feature: ${resources.features.events_90m.full_name}
        - declarative_feature:
            feature: ${resources.features.amount_sum_90m.full_name}
      lifecycle:
        depends_on:
          - resource: materialization_sets.serving_online

Python

將匯入陳述式新增至 resources/__init__.py:

from databricks.bundles.feature_specs import (
    DeclarativeFeature,
    DependsOn,
    FeatureSpec,
    Features,
    Lifecycle,
)

然後將此加入主 load_resources體:

resources.add_feature_spec(
    'event_features',
    FeatureSpec(
        name='${var.catalog}.${var.schema}.event_features',
        features=[
            Features(
                declarative_feature=DeclarativeFeature(
                    feature='${resources.features.events_90m.full_name}'
                )
            ),
            Features(
                declarative_feature=DeclarativeFeature(
                    feature='${resources.features.amount_sum_90m.full_name}'
                )
            ),
        ],
        lifecycle=Lifecycle(depends_on=[DependsOn(resource='materialization_sets.serving_online')]),
    ),
)

新增功能服務端點

端點提供由 entity_name 命名的 FeatureSpec。 由於 entity_name 會參考規格 name的 ,套件會在規格之後建立端點,如 Deploy 的輸出所示,並在規格之前刪除該端點。當 scale_to_zero_enabled端點沒有收到任何請求時,會將其運算量縮減至零。

YAML

創建 resources/serving_endpoint.yml:

resources:
  model_serving_endpoints:
    event_endpoint:
      name: ${var.endpoint_name}
      config:
        served_entities:
          - entity_name: ${resources.feature_specs.event_features.name}
            workload_size: Small
            scale_to_zero_enabled: true

Python

將匯入新增至 resources/__init__.py:

from databricks.bundles.model_serving_endpoints import (
    EndpointCoreConfigInput,
    ModelServingEndpoint,
    ServedEntityInput,
)

然後將此加入 load_resources 的 body:

resources.add_model_serving_endpoint(
    'event_endpoint',
    ModelServingEndpoint(
        name='${var.endpoint_name}',
        config=EndpointCoreConfigInput(
            served_entities=[
                ServedEntityInput(
                    entity_name='${resources.feature_specs.event_features.name}',
                    workload_size='Small',
                    scale_to_zero_enabled=True,
                )
            ]
        ),
    ),
)

Deploy

檢查設定,然後檢視部署所做的事:

databricks bundle validate
databricks bundle plan

首次部署時,五個資源均回報 create:

create feature_specs.event_features
create features.amount_sum_90m
create features.events_90m
create materialization_sets.serving_online
create model_serving_endpoints.event_endpoint

Plan: 5 to add, 0 to change, 0 to delete, 0 unchanged

將套件部署到你的工作空間:

databricks bundle deploy

部署會依相依順序建立資源,並在端點準備好時回傳,這需要數分鐘:

Uploading bundle files to /Workspace/Users/someone@example.com/.bundle/feature-serving-quickstart/default/files...
Created features.events_90m
Created features.amount_sum_90m
Created materialization_sets.serving_online
Created feature_specs.event_features
Created model_serving_endpoints.event_endpoint
Files: 4 uploaded, 0 deleted
Resources: 5 created, 0 changed, 0 deleted, 0 unchanged

查詢端點

將要查找的鍵作為 dataframe_records 傳送。 記錄會以特徵檢視實體路徑的最後一段來命名每個鍵,因此 value.key 變成 key:

databricks serving-endpoints query event-features --json '{"dataframe_records": [{"key": 1280}, {"key": 1188}, {"key": 42}, {"key": 10001}]}'

回應包含每筆記錄各一個物件,依請求順序排列。 每個物件對每個功能檢視都持有一個值,以功能檢視的名稱作為鍵值,但不含其目錄與結構:

{
  "outputs": [
    {
      "events_90m": 10,
      "amount_sum_90m": 10
    },
    {
      "events_90m": 11,
      "amount_sum_90m": 11
    },
    {
      "events_90m": 9,
      "amount_sum_90m": 10
    },
    {
      "events_90m": 0,
      "amount_sum_90m": null
    }
  ]
}

視窗中沒有事件的鍵會回傳 0 計數與 null 總和,就像鍵 10001 一樣。 每個鍵都會回傳這些值,直到實體化管線寫入第一筆資料列,而這可能是在 databricks bundle deploy 回傳後幾分鐘才發生。 如需查詢端點的其他方式,請參閱 「查詢端點」。

從 FeatureSpec 中移除功能檢視

任何對 A FeatureSpec 的變更都會刪除並重新建立。 一個正在運行的端點會持續提供其建置時所使用的 FeatureSpec 中的功能,所以在保留規格名稱不變的情況下所做的變更,不會影響端點本身。 請參閱「更新上線功能服務端點的相依關係」。

要看這點,請從規格中移除 amount_sum_90m 並保留其名稱:

YAML

   feature_specs:
     event_features:
       name: ${var.catalog}.${var.schema}.event_features
       features:
         - declarative_feature:
             feature: ${resources.features.events_90m.full_name}
-        - declarative_feature:
-            feature: ${resources.features.amount_sum_90m.full_name}
       lifecycle:

Python

         features=[
             Features(
                 declarative_feature=DeclarativeFeature(
                     feature='${resources.features.events_90m.full_name}'
                 )
             ),
-            Features(
-                declarative_feature=DeclarativeFeature(
-                    feature='${resources.features.amount_sum_90m.full_name}'
-                )
-            ),
         ],

databricks bundle plan 僅回報需要重新建立規格:

recreate feature_specs.event_features

Plan: 1 to add, 0 to change, 1 to delete, 4 unchanged

databricks bundle deploy 在重新建立規格前要求確認:

Uploading bundle files to /Workspace/Users/someone@example.com/.bundle/feature-serving-quickstart/default/files...

This action will result in the deletion or recreation of the following feature specs.
Grants on them that are not declared in the bundle are lost:
  recreate resources.feature_specs.event_features

Would you like to proceed? [y/N]: y
Recreated feature_specs.event_features
Files: 1 uploaded, 0 deleted
Resources: 1 created, 0 changed, 1 deleted, 4 unchanged

端點仍會回傳兩個功能:

databricks serving-endpoints query event-features --json '{"dataframe_records": [{"key": 1188}, {"key": 42}]}'
{
  "outputs": [
    {
      "events_90m": 16,
      "amount_sum_90m": 20
    },
    {
      "events_90m": 12,
      "amount_sum_90m": 11
    }
  ]
}

重新命名 FeatureSpec

若要變更端點提供的內容,請為 FeatureSpec 取一個新名稱。 端點的 entity_name 會引用該名稱,所以部署也會更新端點,端點會持續用原始 FeatureSpec 功能回應請求,直到更新完成。

YAML

   feature_specs:
     event_features:
-      name: ${var.catalog}.${var.schema}.event_features
+      name: ${var.catalog}.${var.schema}.event_features_v2

Python

     FeatureSpec(
-        name='${var.catalog}.${var.schema}.event_features',
+        name='${var.catalog}.${var.schema}.event_features_v2',

databricks bundle plan 回報正在重新建立規格及更新端點:

recreate feature_specs.event_features
update model_serving_endpoints.event_endpoint

Plan: 1 to add, 1 to change, 1 to delete, 3 unchanged

databricks bundle deploy 請求確認,重新建立規格,並在端點更新後返回:

Uploading bundle files to /Workspace/Users/someone@example.com/.bundle/feature-serving-quickstart/default/files...

This action will result in the deletion or recreation of the following feature specs.
Grants on them that are not declared in the bundle are lost:
  recreate resources.feature_specs.event_features

Would you like to proceed? [y/N]: y
Recreated feature_specs.event_features
Updated model_serving_endpoints.event_endpoint
Files: 1 uploaded, 0 deleted
Resources: 1 created, 1 changed, 1 deleted, 3 unchanged

端點現在只會回傳 events_90m:

databricks serving-endpoints query event-features --json '{"dataframe_records": [{"key": 1188}]}'
{
  "outputs": [
    {
      "events_90m": 68
    }
  ]
}

清理

實體化管線會繼續執行,端點也會持續提供服務,直到你刪除它們為止。 完成後拆除這個套件組:

databricks bundle destroy

databricks bundle destroy 列出它刪除的內容並要求確認:

The following resources will be deleted:
  delete resources.feature_specs.event_features
  delete resources.features.amount_sum_90m
  delete resources.features.events_90m
  delete resources.materialization_sets.serving_online
  delete resources.model_serving_endpoints.event_endpoint

This action will result in the deletion of the following Feature Views.
Deleting a Feature View that a FeatureSpec serves is not blocked, and leaves the FeatureSpec stale:
  delete resources.features.amount_sum_90m
  delete resources.features.events_90m

This action will result in the deletion of the following feature specs.
Feature Serving endpoints and training code that use them can no longer load them:
  delete resources.feature_specs.event_features

All files and directories at the following location will be deleted: /Workspace/Users/someone@example.com/.bundle/feature-serving-quickstart/default

Would you like to proceed? [y/N]: y
Destroy: 5 deleted

只有建立實體化功能的使用者才能刪除該功能,因此請使用部署該套件的相同身份執行 databricks bundle destroy 。 參見 delete_materialized_feature()。

Limitations

  • 當特徵檢視以批次模式實體化時,其線上資料表僅在實體化集首次執行後才存在,因此部署在相同的 databricks bundle deploy 中的端點會失效。 第一次跑完再跑 databricks bundle deploy 一次。
  • 刪除由 FeatureSpec 提供服務的功能檢視不會被阻止,並會使 FeatureSpec 保持過時狀態。

下一步