|
| 1 | +from typing import Any, Dict, List, Optional |
| 2 | + |
| 3 | +from pyspark.sql.dataframe import DataFrame |
| 4 | + |
| 5 | +from butterfree.clients import SparkClient |
| 6 | +from butterfree.configs.db import DeltaConfig |
| 7 | +from butterfree.load.writers.delta_writer import DeltaWriter |
| 8 | +from butterfree.load.writers.writer import Writer |
| 9 | +from butterfree.transform import FeatureSet |
| 10 | + |
| 11 | + |
| 12 | +class DeltaFeatureStoreWriter(Writer): |
| 13 | + """Enable writing feature sets into Delta tables with merge capabilities. |
| 14 | +
|
| 15 | + Attributes: |
| 16 | + database: database name to use for the Delta table. |
| 17 | + table: table name to write the feature set to. |
| 18 | + merge_on: list of columns to use as merge keys. |
| 19 | + deduplicate: whether to deduplicate data before merging based on featr set keys. |
| 20 | + Default is False. |
| 21 | + when_not_matched_insert: optional condition for insert operations. |
| 22 | + When provided, rows will only be inserted if this condition is true. |
| 23 | + when_matched_update: optional condition for update operations. |
| 24 | + When provided, rows will only be updated if this condition is true. |
| 25 | + Source columns can be referenced as source.<column_name> and target |
| 26 | + columns as target.<column_name>. |
| 27 | + when_matched_delete: optional condition for delete operations. |
| 28 | + When provided, rows will be deleted if this condition is true. |
| 29 | + Source and target columns can be referenced as in update conditions. |
| 30 | +
|
| 31 | + Example: |
| 32 | + Simple example regarding DeltaFeatureStoreWriter class instantiation. |
| 33 | + We can instantiate this class with basic merge configuration: |
| 34 | +
|
| 35 | + >>> from butterfree.load.writers import DeltaFeatureStoreWriter |
| 36 | + >>> spark_client = SparkClient() |
| 37 | + >>> writer = DeltaFeatureStoreWriter( |
| 38 | + ... database="feature_store", |
| 39 | + ... table="user_features", |
| 40 | + ... merge_on=["id", "timestamp"] |
| 41 | + ... ) |
| 42 | + >>> writer.write(feature_set=feature_set, |
| 43 | + ... dataframe=dataframe, |
| 44 | + ... spark_client=spark_client) |
| 45 | +
|
| 46 | + We can also enable deduplication based on the feature set keys: |
| 47 | +
|
| 48 | + >>> writer = DeltaFeatureStoreWriter( |
| 49 | + ... database="feature_store", |
| 50 | + ... table="user_features", |
| 51 | + ... merge_on=["id", "timestamp"], |
| 52 | + ... deduplicate=True |
| 53 | + ... ) |
| 54 | +
|
| 55 | + For more control over the merge operation, we can add conditions: |
| 56 | +
|
| 57 | + >>> writer = DeltaFeatureStoreWriter( |
| 58 | + ... database="feature_store", |
| 59 | + ... table="user_features", |
| 60 | + ... merge_on=["id", "timestamp"], |
| 61 | + ... when_matched_update="source.value > target.value", |
| 62 | + ... when_not_matched_insert="source.value > 0" |
| 63 | + ... ) |
| 64 | +
|
| 65 | + The writer supports schema evolution by default and will automatically |
| 66 | + handle updates to the feature set schema. |
| 67 | +
|
| 68 | + When writing with deduplication enabled, the writer will use the feature |
| 69 | + set's key columns and timestamp to ensure data quality by removing |
| 70 | + duplicates before merging. |
| 71 | +
|
| 72 | + For optimal performance, it's recommended to: |
| 73 | + 1. Choose appropriate merge keys |
| 74 | + 2. Use conditions to filter unnecessary updates/inserts |
| 75 | + 3. Enable deduplication only when needed |
| 76 | + """ |
| 77 | + |
| 78 | + def __init__( |
| 79 | + self, |
| 80 | + database: str, |
| 81 | + table: str, |
| 82 | + merge_on: List[str], |
| 83 | + when_not_matched_insert: Optional[str] = None, |
| 84 | + when_matched_update: Optional[str] = None, |
| 85 | + when_matched_delete: Optional[str] = None, |
| 86 | + ): |
| 87 | + self.config = DeltaConfig( |
| 88 | + database=database, |
| 89 | + table=table, |
| 90 | + merge_on=merge_on, |
| 91 | + when_not_matched_insert=when_not_matched_insert, |
| 92 | + when_matched_update=when_matched_update, |
| 93 | + when_matched_delete=when_matched_delete, |
| 94 | + ) |
| 95 | + self.row_count_validation = False |
| 96 | + |
| 97 | + def write( |
| 98 | + self, |
| 99 | + dataframe: DataFrame, |
| 100 | + spark_client: SparkClient, |
| 101 | + feature_set: FeatureSet, |
| 102 | + ) -> None: |
| 103 | + """Merges the input dataframe into a Delta table. |
| 104 | +
|
| 105 | + Performs a Delta merge operation with the provided dataframe using the config |
| 106 | + merge settings. When deduplication is enabled, uses the feature set's key cols |
| 107 | + to remove duplicates before merging. |
| 108 | +
|
| 109 | + Args: |
| 110 | + dataframe: Spark dataframe with data to be merged. |
| 111 | + spark_client: Client with an active Spark connection. |
| 112 | + feature_set: Feature set instance containing schema and configuration. |
| 113 | + Used for deduplication when enabled. |
| 114 | +
|
| 115 | + Example: |
| 116 | + >>> from butterfree.load.writers import DeltaFeatureStoreWriter |
| 117 | + >>> writer = DeltaFeatureStoreWriter( |
| 118 | + ... database="feature_store", |
| 119 | + ... table="user_features", |
| 120 | + ... merge_on=["id", "timestamp"], |
| 121 | + ... deduplicate=True |
| 122 | + ... ) |
| 123 | + >>> writer.write( |
| 124 | + ... dataframe=dataframe, |
| 125 | + ... spark_client=spark_client, |
| 126 | + ... feature_set=feature_set |
| 127 | + ... ) |
| 128 | + """ |
| 129 | + options = self.config.get_options(self.config.table) |
| 130 | + |
| 131 | + DeltaWriter().merge( |
| 132 | + client=spark_client, |
| 133 | + database=options["database"], |
| 134 | + table=options["table"], |
| 135 | + merge_on=self.config.merge_on, |
| 136 | + source_df=dataframe, |
| 137 | + when_not_matched_insert=self.config.when_not_matched_insert, |
| 138 | + when_matched_update=self.config.when_matched_update, |
| 139 | + when_matched_delete=self.config.when_matched_delete, |
| 140 | + ) |
| 141 | + |
| 142 | + def validate( |
| 143 | + self, |
| 144 | + dataframe: DataFrame, |
| 145 | + spark_client: SparkClient, |
| 146 | + feature_set: FeatureSet, |
| 147 | + ) -> None: |
| 148 | + """Validates the dataframe written to Delta table. |
| 149 | +
|
| 150 | + In Delta tables, schema validation is handled by Delta's schema enforcement |
| 151 | + and evolution. No additional validation is needed. |
| 152 | +
|
| 153 | + Args: |
| 154 | + dataframe: Spark dataframe to be validated |
| 155 | + spark_client: Client for Spark connection |
| 156 | + feature_set: Feature set with the schema definition |
| 157 | + """ |
| 158 | + pass |
| 159 | + |
| 160 | + def check_schema(self, dataframe: DataFrame, schema: List[Dict[str, Any]]) -> None: |
| 161 | + """Checks if the dataframe schema matches the feature set schema. |
| 162 | +
|
| 163 | + Schema validation in Delta tables is handled by Delta Lake's schema enforcement |
| 164 | + and evolution capabilities. |
| 165 | +
|
| 166 | + Args: |
| 167 | + dataframe: Spark dataframe to be validated |
| 168 | + schema: Schema definition from the feature set |
| 169 | + """ |
| 170 | + pass |
0 commit comments