Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions docs/how-to-guides/dbt-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,8 @@ feast dbt import -m target/manifest.json -e driver_id --tag feast

All specified entity columns must exist in each dbt model being imported. Models missing any entity column will be skipped with a warning.

Entity columns should be string or integer columns. Feast prints a warning for entity columns whose type maps to another Feast type, such as `FLOAT64`, `BOOLEAN`, `BYTES` or `TIMESTAMP`, and still imports the model. Models with an array entity column are skipped with a warning.

### Generated Code

The `--output` flag generates code like:
Expand Down Expand Up @@ -431,3 +433,11 @@ Ensure your dbt model includes the entity column specified with `--entity-column
### "Missing timestamp column"

By default, Feast looks for `event_timestamp`. Use `--timestamp-field` to specify a different column name.

### "Entity column ... may not be suitable as an entity key"

The entity column's `data_type` in schema.yml maps to a Feast type other than a string or integer type. Floating point values are unreliable join keys, and boolean, binary and timestamp columns rarely identify an entity. The model is still imported. Use a `STRING` or `INT64` column as the entity, or declare the column's type in schema.yml if it is wrong. `NUMBER` types with a precision above 18, such as Snowflake's `NUMBER(38,0)`, map to `Float64`; declare integer IDs as `INTEGER` or `NUMBER(18,0)` instead.

### "Model ... has array entity column(s)"

Array columns cannot be used as entity keys, so the model is skipped. Choose a scalar column with `--entity-column`.
41 changes: 31 additions & 10 deletions sdk/python/feast/cli/dbt_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,9 @@ def import_command(
# Generate Python file instead of applying to registry
feast dbt import -m target/manifest.json -e driver_id --tag feast --output features.py
"""
from feast.dbt.mapper import DbtToFeastMapper
from feast.dbt.parser import DbtManifestParser
from feast.dbt.mapper import DbtToFeastMapper, map_dbt_type_to_feast_type
from feast.dbt.parser import DbtManifestParser, DbtModel
from feast.types import Array, Int32, Int64, String

# Parse manifest
click.echo(f"{Fore.CYAN}Parsing dbt manifest: {manifest_path}{Style.RESET_ALL}")
Expand Down Expand Up @@ -198,6 +199,7 @@ def import_command(

all_objects: List[Any] = []
entities_created: Dict[str, Any] = {}
valid_models: List[DbtModel] = []

for model in models:
# Validate timestamp field exists
Expand All @@ -218,6 +220,32 @@ def import_command(
)
continue

# Validate entity column types: arrays cannot be entity keys, and
# types other than strings and integers make poor join keys
columns_by_name = {c.name: c for c in model.columns}
entity_types = {
e: map_dbt_type_to_feast_type(columns_by_name[e].data_type)
for e in entity_cols
}
array_entities = [e for e, t in entity_types.items() if isinstance(t, Array)]
if array_entities:
click.echo(
f"{Fore.YELLOW}Warning: Model '{model.name}' has array entity "
f"column(s): {', '.join(array_entities)}. Skipping.{Style.RESET_ALL}"
)
continue

for entity_col, feast_type in entity_types.items():
if feast_type not in (String, Int32, Int64):
click.echo(
f"{Fore.YELLOW}Warning: Model '{model.name}' entity column "
f"'{entity_col}' has type "
f"'{columns_by_name[entity_col].data_type}' (Feast type "
f"{feast_type}), which may not be suitable as an entity key. "
f"Recommended types: STRING, INT64. Importing anyway."
f"{Style.RESET_ALL}"
)

# Create or reuse entities (one per entity column)
model_entities: List[Any] = []
for entity_col in entity_cols:
Expand Down Expand Up @@ -253,6 +281,7 @@ def import_command(
exclude_columns=excluded,
)
all_objects.append(feature_view)
valid_models.append(model)

click.echo(
f" {Fore.GREEN}✓{Style.RESET_ALL} {model.name}: "
Expand All @@ -265,14 +294,6 @@ def import_command(
)
raise SystemExit(0)

# Filter models that were actually processed (have valid columns)
valid_models = [
m
for m in models
if timestamp_field in [c.name for c in m.columns]
and all(e in [c.name for c in m.columns] for e in entity_cols)
]

# Summary
click.echo(f"\n{Fore.CYAN}Summary:{Style.RESET_ALL}")
click.echo(f" Entities: {len(entities_created)}")
Expand Down
187 changes: 187 additions & 0 deletions sdk/python/tests/unit/dbt/test_entity_column_type.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
"""
Unit tests for the entity column type checks of `feast dbt import`.
"""

import json

import pytest
from click.testing import CliRunner

# Skip all tests in this module if dbt-artifacts-parser is not installed
pytest.importorskip("dbt_artifacts_parser", reason="dbt-artifacts-parser not installed")

from feast.cli.cli import cli # noqa: E402

MISSING = object()


def _create_column(name: str, data_type=MISSING):
"""Helper to create a column definition, optionally without a data_type."""
column = {"name": name, "description": "", "tags": [], "meta": {}}
if data_type is not MISSING:
column["data_type"] = data_type
return column


def _create_model_node(name: str, entity_columns: dict):
"""Helper to create a model node with a timestamp, a feature and the given
entity columns."""
return {
"name": name,
"unique_id": f"model.test_project.{name}",
"resource_type": "model",
"package_name": "test_project",
"path": f"models/{name}.sql",
"original_file_path": f"models/{name}.sql",
"fqn": ["test_project", name],
"alias": name,
"checksum": {"name": "sha256", "checksum": "abc123"},
"database": "my_database",
"schema": "analytics",
"description": "",
"columns": {
"event_timestamp": _create_column("event_timestamp", "TIMESTAMP"),
"trip_count": _create_column("trip_count", "INT64"),
**entity_columns,
},
"tags": ["feast"],
"meta": {},
"config": {"enabled": True, "materialized": "table", "tags": []},
"depends_on": {"nodes": [], "macros": []},
}


def _write_manifest(tmp_path, models: dict) -> str:
"""Write a manifest with one model per entry of `models`, which maps model
names to their entity columns, and return its path."""
manifest = {
"metadata": {
"dbt_schema_version": "https://schemas.getdbt.com/dbt/manifest/v9.json",
"dbt_version": "1.5.0",
"generated_at": "2024-01-10T00:00:00Z",
"invocation_id": "test-invocation-id",
"env": {},
"adapter_type": "bigquery",
},
"nodes": {
f"model.test_project.{name}": _create_model_node(name, entity_columns)
for name, entity_columns in models.items()
},
"sources": {},
"macros": {},
"docs": {},
"exposures": {},
"metrics": {},
"groups": {},
"selectors": {},
"disabled": {},
"parent_map": {},
"child_map": {},
}
manifest_path = tmp_path / "manifest.json"
manifest_path.write_text(json.dumps(manifest))
return str(manifest_path)


def _import(manifest_path: str, entity_columns: list, *extra_args: str):
args = ["dbt", "import", "-m", manifest_path, "-d", "file", *extra_args]
for entity_column in entity_columns:
args += ["-e", entity_column]
return CliRunner().invoke(cli, args, catch_exceptions=False)


@pytest.mark.parametrize(
"data_type, feast_type",
[
("FLOAT64", "Float64"),
("NUMBER(38,0)", "Float64"),
("BOOLEAN", "Bool"),
("BYTES", "Bytes"),
("TIMESTAMP", "UnixTimestamp"),
],
)
def test_import_warns_on_unsuitable_entity_column_type(tmp_path, data_type, feast_type):
manifest_path = _write_manifest(
tmp_path,
{"driver_stats": {"driver_id": _create_column("driver_id", data_type)}},
)

result = _import(manifest_path, ["driver_id"], "--dry-run")

assert result.exit_code == 0, result.output
assert (
f"Warning: Model 'driver_stats' entity column 'driver_id' has type "
f"'{data_type}' (Feast type {feast_type}), which may not be suitable "
f"as an entity key." in result.output
)
# The model is still imported
assert "driver_stats: DataSource + FeatureView" in result.output


@pytest.mark.parametrize(
"data_type",
[
"STRING",
"VARCHAR(36)",
"INT64",
"INTEGER",
"NUMBER(10,0)",
pytest.param(MISSING, id="undeclared"),
],
)
def test_import_accepts_string_and_integer_entity_columns(tmp_path, data_type):
manifest_path = _write_manifest(
tmp_path,
{"driver_stats": {"driver_id": _create_column("driver_id", data_type)}},
)

result = _import(manifest_path, ["driver_id"], "--dry-run")

assert result.exit_code == 0, result.output
assert "Warning" not in result.output
assert "driver_stats: DataSource + FeatureView" in result.output


def test_import_warns_only_for_unsuitable_entity_columns(tmp_path):
manifest_path = _write_manifest(
tmp_path,
{
"driver_stats": {
"driver_id": _create_column("driver_id", "INT64"),
"vehicle_id": _create_column("vehicle_id", "FLOAT64"),
}
},
)

result = _import(manifest_path, ["driver_id", "vehicle_id"], "--dry-run")

assert result.exit_code == 0, result.output
assert "entity column 'vehicle_id' has type 'FLOAT64'" in result.output
assert "entity column 'driver_id'" not in result.output
assert "driver_stats: DataSource + FeatureView" in result.output


def test_import_skips_models_with_array_entity_columns(tmp_path):
manifest_path = _write_manifest(
tmp_path,
{
"driver_stats": {"driver_id": _create_column("driver_id", "INT64")},
"driver_lists": {"driver_id": _create_column("driver_id", "ARRAY<INT64>")},
},
)
output_path = tmp_path / "features.py"

result = _import(manifest_path, ["driver_id"], "--output", str(output_path))

assert result.exit_code == 0, result.output
assert (
"Warning: Model 'driver_lists' has array entity column(s): driver_id. "
"Skipping." in result.output
)
assert "driver_stats: DataSource + FeatureView" in result.output
assert "driver_lists: DataSource + FeatureView" not in result.output
assert "FeatureViews: 1" in result.output

generated_code = output_path.read_text()
assert "driver_stats" in generated_code
assert "driver_lists" not in generated_code
Loading