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
37 changes: 35 additions & 2 deletions docs/how-to-guides/dbt-integration.md
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,7 @@ feast dbt import <manifest_path> [OPTIONS]
|--------|-------------|---------|
| `--entity-column`, `-e` | Entity column name (can be specified multiple times) | (required) |
| `--data-source-type`, `-d` | Data source type: `bigquery`, `snowflake`, `file` | `bigquery` |
| `--file-path-template` | File source path; `{model}` expands to the dbt model name | `/data/{model}.parquet` |
| `--tag-filter`, `-t` | Filter models by dbt tag | None |
| `--model`, `-m` | Import specific model(s) only | None |
| `--timestamp-field` | Timestamp column name | `event_timestamp` |
Expand Down Expand Up @@ -339,7 +340,7 @@ SnowflakeSource(
### File

```bash
feast dbt import manifest.json -e user_id -d file -o features.py
feast dbt import -m manifest.json -e user_id -d file -o features.py
```

Generates `FileSource` with a placeholder path:
Expand All @@ -351,9 +352,41 @@ FileSource(
```

{% hint style="info" %}
For file sources, update the generated path to point to your actual data files.
When `--file-path-template` is omitted, the placeholder path is preserved. Update it
manually or supply a template pointing to your actual files.
{% endhint %}

Use `--file-path-template` to configure the paths for both direct registry imports
and generated Python definitions:

```bash
# Import directly into the Feast registry
feast dbt import -m manifest.json -e user_id -d file \
--file-path-template "/warehouse/{model}.parquet"

# Generate definitions with the same paths
feast dbt import -m manifest.json -e user_id -d file \
--file-path-template "/warehouse/{model}.parquet" -o features.py
```

`{model}` is replaced with the dbt model's name, not its warehouse alias. For a
model named `user_stats`, the example produces `/warehouse/user_stats.parquet`.
A literal path without `{model}` is also accepted; it is used for every selected
model. Repeat `{model}` if needed, and use `{{` and `}}` for literal braces.

Paths are preserved as supplied after substitution, including relative paths and
URIs such as `s3://bucket/{model}.parquet`. The importer does not check whether the
files exist or change how the configured offline store resolves them. For the
File/Dask offline store, relative paths are resolved against the feature repository,
not the manifest's directory or the generated Python file's directory.

The option is only valid with `--data-source-type file`. Empty templates, unknown
placeholders, attribute/index access, conversions, format specifications, and
unmatched braces produce an error before importing or writing definitions.

The Python APIs accept the same optional `file_path_template` argument on
`DbtToFeastMapper`, `DbtCodeGenerator`, and `generate_feast_code`.

## Best Practices

### 1. Use consistent tagging
Expand Down
20 changes: 19 additions & 1 deletion sdk/python/feast/cli/dbt_import.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ def dbt_cmd():
show_default=True,
help="Type of data source to create",
)
@click.option(
"--file-path-template",
default=None,
help="Path template for file sources; {model} is the model name. "
"Defaults to /data/{model}.parquet.",
)
@click.option(
"--timestamp-field",
"-t",
Expand Down Expand Up @@ -100,6 +106,7 @@ def import_command(
dry_run: bool,
exclude_columns: Optional[str],
output: Optional[str],
file_path_template: Optional[str] = None,
):
"""
Import dbt models as Feast FeatureViews.
Expand All @@ -121,10 +128,19 @@ 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, map_dbt_type_to_feast_type
from feast.dbt.mapper import (
DbtToFeastMapper,
_validate_file_path_template,
map_dbt_type_to_feast_type,
)
from feast.dbt.parser import DbtManifestParser, DbtModel
from feast.types import Array, Int32, Int64, String

try:
_validate_file_path_template(file_path_template, data_source_type)
except ValueError as e:
raise click.BadParameter(str(e), param_hint="--file-path-template") from e

# Parse manifest
click.echo(f"{Fore.CYAN}Parsing dbt manifest: {manifest_path}{Style.RESET_ALL}")

Expand Down Expand Up @@ -192,6 +208,7 @@ def import_command(
data_source_type=data_source_type,
timestamp_field=timestamp_field,
ttl_days=ttl_days,
file_path_template=file_path_template,
)

# Generate Feast objects
Expand Down Expand Up @@ -314,6 +331,7 @@ def import_command(
project_name=parser.project_name or "",
exclude_columns=excluded,
online=True,
file_path_template=file_path_template,
)

with open(output, "w") as f:
Expand Down
21 changes: 18 additions & 3 deletions sdk/python/feast/dbt/codegen.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,11 @@

from jinja2 import BaseLoader, Environment

from feast.dbt.mapper import map_dbt_type_to_feast_type
from feast.dbt.mapper import (
_resolve_file_path,
_validate_file_path_template,
map_dbt_type_to_feast_type,
)
from feast.dbt.parser import DbtModel
from feast.types import (
Array,
Expand Down Expand Up @@ -90,7 +94,7 @@
{% elif data_source_type == 'file' %}
{{ source.var_name }} = FileSource(
name="{{ source.name }}",
path="{{ source.path }}",
path={{ source.path_literal }},
timestamp_field="{{ source.timestamp_field }}",
description="{{ source.description }}",
tags={{ source.tags }},
Expand Down Expand Up @@ -182,6 +186,9 @@ class DbtCodeGenerator:
This class creates complete, importable Python files containing
Entity, DataSource, and FeatureView definitions.

For file sources, ``file_path_template`` optionally replaces the default
``/data/{model}.parquet`` path, using the dbt model name for ``{model}``.

Example::

generator = DbtCodeGenerator(
Expand All @@ -204,10 +211,13 @@ def __init__(
data_source_type: str = "bigquery",
timestamp_field: str = "event_timestamp",
ttl_days: int = 1,
file_path_template: Optional[str] = None,
):
self.data_source_type = data_source_type.lower()
self.timestamp_field = timestamp_field
self.ttl_days = ttl_days
_validate_file_path_template(file_path_template, self.data_source_type)
self.file_path_template = file_path_template

# Set up Jinja2 environment
self.env = Environment(
Expand Down Expand Up @@ -309,7 +319,9 @@ def generate(
source_data["schema"] = model.schema
source_data["table"] = model.alias
elif self.data_source_type == "file":
source_data["path"] = f"/data/{model.name}.parquet"
source_data["path_literal"] = repr(
_resolve_file_path(self.file_path_template, model.name)
)

data_sources.append(source_data)

Expand Down Expand Up @@ -389,6 +401,7 @@ def generate_feast_code(
project_name: str = "",
exclude_columns: Optional[List[str]] = None,
online: bool = True,
file_path_template: Optional[str] = None,
) -> str:
"""
Convenience function to generate Feast code from dbt models.
Expand All @@ -403,6 +416,7 @@ def generate_feast_code(
project_name: Project name for documentation
exclude_columns: Columns to exclude from features
online: Whether to enable online serving
file_path_template: Optional file source path, with {model} replaced by the model name

Returns:
Generated Python code as a string
Expand All @@ -411,6 +425,7 @@ def generate_feast_code(
data_source_type=data_source_type,
timestamp_field=timestamp_field,
ttl_days=ttl_days,
file_path_template=file_path_template,
)

return generator.generate(
Expand Down
35 changes: 33 additions & 2 deletions sdk/python/feast/dbt/mapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
including DataSource, Entity, and FeatureView.
"""

import re
from datetime import timedelta
from typing import Any, Dict, List, Optional, Union

Expand Down Expand Up @@ -167,6 +168,33 @@ def map_dbt_type_to_feast_type(dbt_type: str) -> FeastType:
return String


def _validate_file_path_template(
file_path_template: Optional[str], data_source_type: str
) -> None:
if file_path_template is None:
return
if data_source_type.lower() != "file":
raise ValueError("file_path_template is only supported for file data sources")
if not file_path_template:
raise ValueError("file_path_template must not be empty")

# Remove the supported tokens; any remaining brace is invalid template syntax.
literal = re.sub(r"\{\{|\}\}|\{model\}", "", file_path_template)
if "{" in literal or "}" in literal:
raise ValueError(
f"Invalid file_path_template {file_path_template!r}. "
"Use only {model}, with {{ and }} for literal braces; "
"other fields and formatting are not supported."
)


def _resolve_file_path(file_path_template: Optional[str], model_name: str) -> str:
template = (
"/data/{model}.parquet" if file_path_template is None else file_path_template
)
return template.format(model=model_name)


class DbtToFeastMapper:
"""
Maps dbt models to Feast objects.
Expand All @@ -186,17 +214,21 @@ class DbtToFeastMapper:
data_source_type: Type of data source ('bigquery', 'snowflake', 'file')
timestamp_field: Default timestamp field name
ttl_days: Default TTL in days for feature views
file_path_template: Optional file source path, with {model} replaced by the model name
"""

def __init__(
self,
data_source_type: str = "bigquery",
timestamp_field: str = "event_timestamp",
ttl_days: int = 1,
file_path_template: Optional[str] = None,
):
self.data_source_type = data_source_type.lower()
self.timestamp_field = timestamp_field
self.ttl_days = ttl_days
_validate_file_path_template(file_path_template, self.data_source_type)
self.file_path_template = file_path_template

def _infer_entity_value_type(self, model: DbtModel, entity_col: str) -> ValueType:
"""Infer entity ValueType from dbt model column type."""
Expand Down Expand Up @@ -262,10 +294,9 @@ def create_data_source(
elif self.data_source_type == "file":
from feast.infra.offline_stores.file_source import FileSource

# For file sources, use the model name as a placeholder path
return FileSource(
name=f"{model.name}_source",
path=f"/data/{model.name}.parquet",
path=_resolve_file_path(self.file_path_template, model.name),
timestamp_field=ts_field,
created_timestamp_column=created_timestamp_column or "",
description=model.description,
Expand Down
Loading