宣言的オートメーション バンドルを使用してフィーチャー ビューを提供する

Important

この機能は、プライベート プレビュー段階にあります。 試すには、Azure Databricks の連絡先にお問い合わせください。

宣言的自動化バンドル(旧称 Databricks Asset Bundles)は、Feature View やそれに対応するエンドポイントなどの Azure Databricks リソースをプログラム的に検証、展開、実行することを可能にします。 「宣言型オートメーション バンドルとは」を参照してください。

このチュートリアルでは、2つのストリーミング フィーチャービューを宣言し、それらをオンラインストアにマテリアライズし、FeatureSpec および機能サービングエンドポイントを通じて提供するバンドルを作成します。 その後、エンドポイントにクエリを実行し、どの機能を提供するかを変更し、すべてを削除します。

フィーチャービューとそのマテリアライゼーションは 宣言的自動化バンドルを使用したフィーチャービューの管理 に従っており、このトピックでそれらについて詳しく説明しています。 代わりに Python API で FeatureSpec とエンドポイントを作成するには、「フィーチャービューの提供」を参照してください。

各ステップはYAMLとPythonの両方の構成を示します。 言語を選べば、ページはその選択に従って表示されます。

Requirements

このチュートリアルを完了するには、以下のものが必要です:

  • Databricks CLI バージョン 1.26.0 以上。 databricks --version を実行して確認します。 「Databricks CLI のインストールまたは更新」を参照してください。
  • Unity カタログ対応ワークスペース。 要件を参照してください。
  • フィーチャーを作成し、それらをマテリアライズする権限 「 アクセス許可」を参照してください。
  • モデルサーバングエンドポイントを作成する権限。 ID とアクセスを参照してください。
  • 既存のオンラインストア。 「 オンラインストアを作成する」をご覧ください。
  • 既存のストリーム。 ストリームはバンドルリソースではないため、まず作成し、バンドル内で名前で参照してください。 「 ストリームを作成する」をご覧ください。
  • Python 3.10以上で、Pythonでリソースを宣言するには。

リソースをバンドルで提供する

バンドルは2種類のリソースタイプを通じてフィーチャービューを提供します:

  • FeatureSpec: 提供する機能を一覧表示する Unity カタログ関数。 特徴値を持ちません。 それを提供するエンドポイントは、フィーチャービューがマテリアライズされているオンラインテーブルからそれらを読み取ります。 「FeatureSpecで特徴量を提供する」を参照してください。設定参照については「feature_spec」を参照してください。
  • フィーチャーサービングエンドポイント:モデルではなく FeatureSpec を提供するモデルサービスエンドポイント。 バンドルはそれを model_serving_endpoints リソースとして宣言します。 構成リファレンスについては、 model_serving_endpointを参照してください。

バンドルからフィーチャービューを提供

以下の手順では、バンドルをビルド・展開し、エンドポイントをクエリし、提供内容を変更し、整理を行います。

認証の設定

まず、開発マシンの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 構成プロファイルとして保存するように求められます。 Enter キーを押して提案されたプロファイル名を受け入れるか、新規または既存のプロファイル名を入力します。 同じ名前の既存のプロファイルは、入力した情報で上書きされます。 プロファイルを使用すると、複数のワークスペース間で認証コンテキストをすばやく切り替えることができます。

    既存のプロファイルの一覧を取得するには、別のターミナルまたはコマンド プロンプト内で、Databricks CLI を使用してコマンド databricks auth profiles を実行します。 特定のプロファイルの既存の設定を表示するには、コマンド databricks auth env --profile <profile-name>を実行します。

  3. Web ブラウザーで、画面の指示に従って、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 値を持つ複数のプロファイルがある場合は、Databricks CLI が正しく一致する OAuth トークン情報を見つけるのに役立つ --host と -p のオプションを一緒に指定することが必要になる場合があります。

バンドルを作成する

バンドル用の空のディレクトリを作成し、ルートに databricks.yml ファイル、隣に resources ディレクトリを置きます。

YAML

以下の各ステップは、 resources/の下に1つのファイルを追加します:

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

databricks.yml にはバンドル名、include 下のすべてのファイルを読み込む resources/ エントリ、およびリソースが参照する変数が含まれます:

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で宣言された資源は、python内のdatabricks.ymlマッピングを通じてのみ見つかります。 これがなければバンドルは検証とデプロイに成功しますが、リソースは含まれていないので、今すぐ追加してください:

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

databricks.yml に名前を付ける関数で resources/__init__.py を作成します:

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_90mvalue.amountを合計します。 1つのマテリアライゼーションセットが、ストリーミングモードで両方のデータをオンラインストアに書き込みます。 各設定キーの意味については、 Feature Viewチュートリアルのステップ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を追加する

FeatureSpecにはエンドポイントが提供する機能が一覧表示されます。 features内の各エントリには、declarative_featureを持つ1つのフィーチャービューの名前が記載されています。

FeatureSpecは、それが名前を挙げる各 Feature View がオンラインストアに具現化された後にのみ作成できます。 declarative_feature の${resources.features...}参照により、仕様はフィーチャービューevents_90mおよびamount_sum_90mに依存し、lifecycle.depends_on は、どの参照でも表されない、マテリアライゼーションセットserving_onlineへの依存関係を追加します。 バンドルは3つすべての後にスペックを作成し、それらより前に削除します。 FeatureSpecが満たすべきルールを参照してください。

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')]),
    ),
)

機能サービングエンドポイントの追加

エンドポイントは、FeatureSpecが名前を付けたentity_nameを提供します。 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 の本文に以下を加えます。

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,
                )
            ]
        ),
    ),
)

デプロイ

構成を確認し、展開が何をしているかを確認します:

databricks bundle validate
databricks bundle plan

初回の展開では、5つのリソースはいずれも 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}]}'

レスポンスは、リクエストの順序に沿って、各レコードごとに1つのオブジェクトを保持します。 各オブジェクトは各フィーチャービューごとに1つの値を保持し、カタログとスキーマを除いたフィーチャービュー名をキーとします。

{
  "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
    }
  ]
}

ウィンドウにイベントがない場合、キー10001と同様に、カウントに対して0、合計に対してnullを返します。 各キーは、マテリアライゼーションパイプラインが最初の行を書き込むまでこれらの値を返します。これは databricks bundle deploy が返ってから数分後のこともあります。 エンドポイントをクエリするその他の方法については、「 エンドポイントをクエリする」を参照してください。

FeatureSpecからフィーチャービューを削除する

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

マテリアライズされた機能を削除できるのはユーザーだけなので、バンドルをデプロイした同じIDで databricks bundle destroy 実行してください。 delete_materialized_feature()を参照してください。

Limitations

  • フィーチャービューがバッチモードでマテリアライズされる場合、そのオンラインテーブルはマテリアライゼーションセットの最初の実行後にのみ存在するため、同じ databricks bundle deploy に展開されたエンドポイントは失敗します。 最初の実行後、もう一度 databricks bundle deploy を実行してください。
  • FeatureSpecが提供するフィーチャービューを削除してもブロックされず、FeatureSpecは古くなったままになります。

次のステップ