Disponibilidad de los paquetes: JaviMapper es una beta no publicada y JaviPerf es experimental. Ninguno tiene una versión pública en PyPI ni un wheel público, y el repositorio del código fuente es privado. Los visitantes no pueden obtener ni compilar estos paquetes desde este sitio. Los pasos de instalación en Fabric requieren un wheel ya autorizado y suministrado de forma privada; sin ese acceso, no se pueden ejecutar los ejercicios.
Práctica: concilia tres esquemas de comercios
Microsoft Fabric es la ruta principal. Instala el wheel privado JaviMapper 0.6.0b1 en un Environment dedicado, conecta un Lakehouse con tres CSV ficticios y ejecuta los seis ejercicios del notebook existente. La ruta local sigue disponible como opción.
- Crear wheel privado
- Publicar Environment
- Conectar notebook y Lakehouse
- Revisar y aplicar mapeos
- Examinar informe y esfuerzo
Requisitos previos
- Un workspace de laboratorio dedicado con capacidad activa de Fabric o una prueba de Fabric, y permisos para crear Environment, Lakehouse y notebook y publicar cambios. Power BI Pro por sí solo no proporciona capacidad Spark de Fabric. Si Environment no aparece en New item, abre All items y busca Environment.
- Python 3.10 o posterior en el equipo local de compilación y este repositorio. Estas instrucciones no crean recursos de Fabric.
- Un runtime Spark compatible. Verifica las versiones activas con
sys.version,pyspark.__version__yspark.versionen el notebook. JaviMapper declara Python>=3.10; la matriz local de 0.6.0b1 verificó Python 3.10–3.14 con combinaciones seleccionadas de pandas/PySpark: PySpark 3.5 con Python 3.10/3.11 y PySpark 4 con Python 3.12–3.14. Esto no demuestra compatibilidad con todos los runtimes de Fabric ni con la compilación exacta de sus paquetes. Fabric Runtime 2.0 usa actualmente Python 3.13 y Spark 4.1; considera esa combinación no verificada hasta superar las comprobaciones del notebook. Runtime 1.3 usa Python 3.11 y Spark 3.5.5, pero su fin de soporte ya fue anunciado. Comprueba las versiones vigentes antes de elegir. - Usa solo los tres CSV ficticios de esta práctica. No cargues datos de empleadores, producción o clientes.
Consulta las versiones y el ciclo de vida actuales en runtimes Spark de Fabric y Runtime 2.0.
Descargar el wheel
Abre Microsoft Fabric y crea un workspace y un Environment dedicados al laboratorio. En el Environment, carga el wheel descargado bajo Custom libraries, guarda y publica. Conecta el Environment publicado a este notebook, inicia una sesión nueva y verifica que import javimapper; print(javimapper.__version__) devuelve 0.6.0b1. Continúa con la configuración siguiente. El enlace solo funciona en el servidor local de desarrollo de JaviBuilds. El wheel privado no se publica en PyPI ni debe copiarse a los recursos del sitio web.
Crear un Environment de Fabric
En el workspace de laboratorio, selecciona + New → Environment, crea un elemento dedicado y abre sus opciones de Spark. Elige el runtime solo después de comparar sus versiones de Python, Spark, pandas y PySpark con los requisitos. El wheel Python puro evita restricciones ABI de paquetes compilados, pero el adaptador PySpark aún depende de que el runtime incluya una versión compatible de Spark/PySpark.
No deduzcas compatibilidad por el nombre del runtime. Si fallan la importación o las comprobaciones del adaptador, elige un runtime compatible o solicita una versión compatible de la biblioteca. No fuerces actualizaciones de paquetes Spark administrados por Fabric con %pip o una sobreescritura del Environment sin probarlas.
Cargar y publicar la biblioteca
En Libraries del Environment, selecciona Custom libraries, carga el .whl local, guarda y pulsa Publish. Elige el modo de publicación que ofrece Fabric; Full crea una instantánea estable y puede tardar más que Quick. Espera a que termine y confirma el estado de la biblioteca. Consulta administrar bibliotecas y crear y usar un Environment.
Si la publicación o resolución de dependencias informa un conflicto, conserva el error completo y compáralo con los paquetes integrados del runtime. No cambies pandas ni PySpark a ciegas. Usa un runtime compatible o una versión de JaviMapper validada para ese runtime.
Conectar el Environment
Crea o abre un Spark notebook de Fabric, selecciona el nuevo Environment y confirma. Inicia una sesión nueva después de conectarlo o cambiarlo; una sesión activa no lo adopta. Ejecuta la primera celda para verificar javimapper.__version__ == "0.6.0b1" e imprimir las versiones de Python, PySpark y Spark. El notebook reutiliza el spark que proporciona Fabric.
Crear o conectar un Lakehouse
Crea un Lakehouse dedicado o conecta uno existente solo para el laboratorio y establécelo como predeterminado del notebook. En Lakehouse Explorer crea Files/javimapper/input/ y carga north.csv, south.csv y east.csv desde labs/javimapper-mapping-lab/data/. Conserva los nombres. La primera celda comprueba los tres archivos.
Los notebooks Spark de Fabric admiten rutas relativas al Lakehouse predeterminado como Files/...; pandas también puede usar el montaje /lakehouse/default/Files/.... Este notebook lee los archivos pequeños con la sesión Spark conectada y convierte únicamente estos ejemplos sintéticos de dos filas a pandas para el adaptador pandas. Consulta cargar datos en un Lakehouse y rutas de NotebookUtils.
Usa esta estructura en el Lakehouse (el notebook de incorporación crea la carpeta de configuración con versión):
Files/
└── javimapper/
├── input/
│ ├── north.csv
│ ├── south.csv
│ ├── east.csv
│ └── east_delivery_02.csv
├── config/east-market/
│ ├── approved-mapping-v1.json
│ └── east-market-aliases-v1.json (opcional)
└── output/
└── mapping-report.html
Importar y ejecutar el notebook
Abre labs/javimapper-mapping-lab/notebooks/javimapper-mapping-lab.ipynb en Fabric (cárgalo o impórtalo al workspace). Conserva EXECUTION_MODE = "fabric", conecta el Environment publicado y el Lakehouse predeterminado, y selecciona Run all. El orden es: (1) comprobar Environment y archivos, y ver sugerencias iniciales; (2) revisión y aprobación humana; (3) mapeo pandas; (4) mapeo Fabric Spark; (5) reutilizar alias en los tres esquemas; (6) generar el informe HTML. Se mantienen los cinco campos destino y las reglas de aprobación de la práctica local.
Las capturas siguientes son evidencia de las ejecuciones de Microsoft Fabric proporcionadas; las pruebas automatizadas del notebook son comprobaciones locales independientes. La ejecución de seis ejercicios generó y guardó el informe, y la captura muestra su renderizado en línea. En Fabric, displayHTML() es la opción compatible cuando no se representa la salida de IPython.
Notebook: javimapper-mapping-lab.ipynb
Vista de solo lectura del archivo del notebook. Nada en esta página ejecuta código.
Celda 1MarkdownJaviMapper in Microsoft Fabric: review a mapping from proposal to application
JaviMapper in Microsoft Fabric: review a mapping from proposal to application
This notebook is designed for a Fabric Spark notebook attached to a dedicated lab workspace, a published Fabric Environment with the private
javimapper==0.6.0b1wheel, and a default Lakehouse containing the three fictional merchant CSVs. The cells use Fabric’s pre-createdsparksession. Every row is synthetic. JaviMapper proposes column relationships; a person reviews and approves them before either adapter applies them. A score is a name-similarity heuristic, not a probability.Before running: build the wheel locally, upload it to the Environment’s Custom libraries, publish, attach that Environment to this notebook, start a new session, and upload the three CSVs to
Files/javimapper/input/. See the accompanying lab page for full steps and compatibility checks. The saved outputs shown here were captured in a local Spark environment; Fabric output has not been observed yet.EXECUTION_MODEbelow defaults tofabric. For the optional local route, set it tolocaland run from the repository or extracted lab bundle after installing JaviMapper, pandas, PySpark, and Java.Celda 2MarkdownPrerequisites and Fabric session check
Prerequisites and Fabric session check
Confirm the package version, Python/PySpark/Spark versions, active session, and all three Lakehouse files before continuing. If the Fabric check fails, fix the attached and published Environment or Lakehouse rather than installing or replacing packages blindly.
Celda 3PySparkCode61 líneas
from pathlib import Path import sys import pandas as pd import pyspark import javimapper from javimapper import MatchConfig, Matcher, Schema, render_html from javimapper.adapters.pandas import apply_mapping as pandas_apply from javimapper.adapters.pandas import schema_from_pandas EXECUTION_MODE = "fabric" # change to "local" only for the optional local path EXPECTED_VERSION = "0.6.0b1" assert javimapper.__version__ == EXPECTED_VERSION, f"Expected {EXPECTED_VERSION}, found {javimapper.__version__}" if EXECUTION_MODE == "fabric": assert "spark" in globals(), "Run this as a Fabric Spark notebook with its provided spark session." assert "notebookutils" in globals(), "Attach a default Lakehouse and run in Fabric." DATA_DIR = "Files/javimapper/input" required_files = {"north.csv", "south.csv", "east.csv"} found_files = {item.name for item in notebookutils.fs.ls(DATA_DIR) if item.isFile} assert required_files <= found_files, f"Missing Lakehouse files: {sorted(required_files - found_files)}" else: from pyspark.sql import SparkSession cwd = Path.cwd().resolve() candidates = [base / relative for base in (cwd, *cwd.parents) for relative in ("labs/javimapper-mapping-lab", ".", "javimapper-mapping-lab")] LAB_ROOT = next((path for path in candidates if (path / "data/north.csv").is_file()), None) if LAB_ROOT is None: raise FileNotFoundError("Could not locate the lab data folder. Run from the repository or extracted bundle.") DATA_DIR = str(LAB_ROOT / "data") required_files = {"north.csv", "south.csv", "east.csv"} found_files = {path.name for path in Path(DATA_DIR).glob("*.csv")} assert required_files <= found_files, f"Missing local fixture files: {sorted(required_files - found_files)}" if "spark" not in globals(): spark = SparkSession.builder.master("local[1]").appName("JaviMapperNotebookLab").getOrCreate() print(f"Execution mode: {EXECUTION_MODE.upper()} (saved outputs were captured locally)") print(f"JaviMapper: {javimapper.__version__} | Python: {sys.version.split()[0]} | PySpark: {pyspark.__version__} | Spark: {spark.version}") print("Synthetic CSV files found:", ", ".join(sorted(required_files))) TARGET = Schema.of(["transaction_id", "transaction_date", "customer_id", "gross_amount", "currency"]) TRUTH = { "north": {"TxnID": "transaction_id", "TxnDate": "transaction_date", "CustomerID": "customer_id", "GrossAmount": "gross_amount", "Currency": "currency"}, "south": {"transaction_id": "transaction_id", "booked_date": "transaction_date", "buyer_id": "customer_id", "total_amount": "gross_amount", "currency_code": "currency"}, "east": {"RefNo": "transaction_id", "DateOfSale": "transaction_date", "ClientNo": "customer_id", "SaleValue": "gross_amount", "Currency": "currency"}, } ALIASES = { "transaction_id": ["TxnID", "RefNo"], "transaction_date": ["TxnDate", "booked_date", "DateOfSale"], "customer_id": ["CustomerID", "buyer_id", "ClientNo"], "gross_amount": ["GrossAmount", "total_amount", "SaleValue"], "currency": ["Currency", "currency_code"], } def read_source(merchant): path = f"{DATA_DIR}/{merchant}.csv" if EXECUTION_MODE == "fabric": return spark.read.option("header", True).option("inferSchema", False).csv(path).toPandas() return pd.read_csv(path, dtype=str) north = read_source("north") first_plan = Matcher().suggest(schema_from_pandas(north), TARGET) print("Source | suggested target | method | state") for result in first_plan.results: print(f"{result.source} | {result.suggested_target or '?'} | {result.method.value if result.method else '?'} | {result.state.value}")Salida
Execution mode: LOCAL (saved outputs were captured locally) JaviMapper: 0.6.0b1 | Python: 3.12.10 | PySpark: 4.3.0 | Spark: 4.3.0 Synthetic CSV files found: east.csv, north.csv, south.csv Source | suggested target | method | state TxnID | transaction_id | normalized | suggested TxnDate | transaction_date | normalized | suggested CustomerID | customer_id | normalized | suggested GrossAmount | gross_amount | normalized | suggested Currency | currency | normalized | suggested
Celda 4MarkdownExercise 2 — Human review and approval
Exercise 2 — Human review and approval
Bulk approval accepts only the package’s safe default methods. Make an explicit, reasoned decision for any unresolved North Market field. Finalize only after every required target has an approved source.
Celda 5PySparkCode11 líneas
bulk_approved = first_plan.approve_suggestions() individual_decisions = [] for source_name, target_name in TRUTH["north"].items(): if first_plan.result(source_name).approved_target is None: first_plan.approve(source_name, target_name, accept_semantic_risk=True, note="Reviewed against this synthetic lab fixture") individual_decisions.append((source_name, target_name)) approved_mapping = first_plan.finalize() assert len(approved_mapping.renames) == len(TARGET.names) print(f"Bulk-approved suggestions: {len(bulk_approved)}") print(f"Individual reviewed decisions: {len(individual_decisions)}") print("Finalized mappings: " + ", ".join(f"{source} -> {target}" for source, target in approved_mapping.renames.items()))Salida
Bulk-approved suggestions: 5 Individual reviewed decisions: 0 Finalized mappings: TxnID -> transaction_id, TxnDate -> transaction_date, CustomerID -> customer_id, GrossAmount -> gross_amount, Currency -> currency
Celda 6MarkdownExercise 3 — Apply the approved mapping with pandas
Exercise 3 — Apply the approved mapping with pandas
This small synthetic fixture is converted to pandas for the adapter exercise. Compare the exact rows and canonical column order with the authored reference mapping.
Celda 7PySparkCode7 líneas
pandas_result = pandas_apply(north, approved_mapping, unmapped="drop", order="target") expected_north = north.rename(columns=TRUTH["north"])[list(TARGET.names)] assert pandas_result.equals(expected_north) print("pandas columns:", list(pandas_result.columns)) print("pandas rows:") for row in pandas_result.to_dict(orient="records"): print(row)Salida
pandas columns: ['transaction_id', 'transaction_date', 'customer_id', 'gross_amount', 'currency'] pandas rows: {'transaction_id': 'N-1001', 'transaction_date': '2026-01-02', 'customer_id': 'C-20', 'gross_amount': '18.50', 'currency': 'USD'} {'transaction_id': 'N-1002', 'transaction_date': '2026-01-03', 'customer_id': 'C-21', 'gross_amount': '42.00', 'currency': 'USD'}Celda 8MarkdownExercise 4 — Apply the same approved mapping with Fabric Spark
Exercise 4 — Apply the same approved mapping with Fabric Spark
Fabric provides
spark; this cell reuses it and does not create or stop a second session. Only the two-row fixture is collected for a parity assertion. The adapter itself creates a lazy projection; avoid collecting production-sized data to the driver.Celda 9PySparkCode7 líneas
from javimapper.adapters.spark import apply_mapping as spark_apply north_spark = spark.read.option("header", True).option("inferSchema", False).csv(f"{DATA_DIR}/north.csv") spark_result = spark_apply(north_spark, approved_mapping, unmapped="drop", order="target").toPandas() assert spark_result.equals(pandas_result) print("PySpark columns:", list(spark_result.columns)) print(f"PySpark rows match pandas: {len(spark_result)}")Salida
PySpark columns: ['transaction_id', 'transaction_date', 'customer_id', 'gross_amount', 'currency'] PySpark rows match pandas: 2
Celda 10MarkdownExercise 5: Reuse reviewed aliases across all three schemas
Exercise 5: Reuse reviewed aliases across all three schemas
An alias records a name relationship reviewed by a person; it is a useful starting point for later deliveries, not proof that the business meaning is the same. First compare the safe, no-alias proposals with proposals after alias reuse. In this synthetic fixture,
RefNostays unmatched because JaviMapper flags a semantic conflict: both names identify something, but one is a reference and the other a transaction. A reference number could identify many different things, so a person must resolve it explicitly.The scores are heuristic name-similarity rankings. They are not probabilities, confidence guarantees, or evidence of verified business meaning. ?Approved? means accepted by the safe bulk rule or explicitly reviewed here; ?Suggested? remains unapplied; ?Needs Review? is ambiguous or risky; ?Rejected? means a reviewer declined it; and ?Unmatched? means no supported suggestion was made. Even a clean run on these two-row fictional files does not establish production accuracy.
Celda 11PySparkCompare how many decisions remain after safe bulk approval, with and without aliases35 líneas
# Compare how many decisions remain after safe bulk approval, with and without aliases. no_alias_suggestions = 0 no_alias_manual_decisions = 0 initial_report_html = None for merchant in TRUTH: frame = read_source(merchant) proposal = Matcher().suggest(schema_from_pandas(frame), TARGET) no_alias_suggestions += sum(result.suggested_target is not None for result in proposal.results) if merchant == "east": initial_report_html = render_html(proposal, title="East Market initial proposals (unapproved)") proposal.approve_suggestions() no_alias_manual_decisions += sum(result.approved_target is None for result in proposal.results) alias_plans = {} alias_suggestions = 0 alias_manual_decisions = 0 for merchant, expected in TRUTH.items(): frame = read_source(merchant) plan = Matcher(MatchConfig(aliases=ALIASES)).suggest(schema_from_pandas(frame), TARGET) alias_plans[merchant] = plan alias_suggestions += sum(result.suggested_target is not None for result in plan.results) plan.approve_suggestions() alias_manual_decisions += sum(result.approved_target is None for result in plan.results) for source_name, target_name in expected.items(): if plan.result(source_name).approved_target is None: plan.approve(source_name, target_name, accept_semantic_risk=True, note="Reviewed against this synthetic lab fixture") mapping = plan.finalize() actual = pandas_apply(frame, mapping, unmapped="drop", order="target") expected_frame = frame.rename(columns=expected)[list(TARGET.names)] assert actual.equals(expected_frame), merchant print(f"{merchant}: {sum(result.suggested_target is not None for result in plan.results)}/5 suggested; approved output matches the fixture") print(f"Without aliases: {no_alias_suggestions}/15 suggested; {no_alias_manual_decisions} rows remained for a human decision after safe bulk approval.") print(f"With reviewed aliases: {alias_suggestions}/15 suggested; {alias_manual_decisions} rows remained for a human decision after safe bulk approval.") print("These are counts from the supplied synthetic fixture; no review time was measured.")Salida
north: 5/5 suggested; approved output matches the fixture south: 3/5 suggested; approved output matches the fixture east: 4/5 suggested; approved output matches the fixture Without aliases: 9/15 suggested; 8 rows remained for a human decision after safe bulk approval. With reviewed aliases: 12/15 suggested; 3 rows remained for a human decision after safe bulk approval. These are counts from the supplied synthetic fixture; no review time was measured.
Celda 12MarkdownExercise 6: Generate and display the HTML review reports
Exercise 6: Generate and display the HTML review reports
The first report below is the East Market proposal before approval. The second is the final reviewed plan, including the explicit
RefNodecision and its note. The report summarizes mapping decisions and review rationale; it does not validate business meaning or prove production accuracy. The alias comparison above records only how many rows remained for a human decision on these fixtures. It does not estimate time saved.The notebook saves the final standalone report to
Files/javimapper/output/mapping-report.htmlin Fabric (oroutput/mapping-report.htmllocally). It displays the same in-memory HTML, without rereading the saved file. If inline HTML is unavailable in the notebook, use the saved file in Lakehouse Explorer. Reports use the library's read-only HTML output and do not load external resources or scripts.Celda 13PySparkCode42 líneas
report_html = render_html(alias_plans["east"], title="JaviMapper synthetic merchant schema: reviewed decisions") if EXECUTION_MODE == "fabric": report_dir = "Files/javimapper/output" notebookutils.fs.mkdirs(report_dir) report_path = f"{report_dir}/mapping-report.html" notebookutils.fs.put(report_path, report_html, True) print(f"HTML report generated in the default Lakehouse: {report_path} ({len(report_html.encode('utf-8'))} bytes)") else: output_dir = LAB_ROOT / "output" output_dir.mkdir(exist_ok=True) report_path = output_dir / "mapping-report.html" report_path.write_text(report_html, encoding="utf-8") print(f"HTML report generated locally: output/{report_path.name} ({report_path.stat().st_size} bytes)") report_display_path = report_path if EXECUTION_MODE == "fabric" else "output/mapping-report.html" inline_displayed = False display_error = None try: from IPython.display import HTML, display print("Inline reports: initial unapproved proposals, then reviewed decisions") display(HTML(initial_report_html)) display(HTML(report_html)) inline_displayed = True except Exception as exc: display_error = exc # Some Fabric notebook kernels expose displayHTML even when IPython MIME display is absent. if not inline_displayed and EXECUTION_MODE == "fabric" and callable(globals().get("displayHTML")): try: displayHTML(initial_report_html) displayHTML(report_html) inline_displayed = True except Exception as exc: display_error = exc if inline_displayed: print("Inline HTML display submitted; confirm rendering in the target Fabric notebook.") else: print(f"Inline HTML display unavailable; open the saved report at {report_display_path}.") if display_error is not None: print(f"Display fallback: {type(display_error).__name__}")Salida
HTML report generated locally: output/mapping-report.html (18189 bytes) Inline HTML display unavailable; open the saved report at output/mapping-report.html. Display fallback: ModuleNotFoundError
Celda 14MarkdownReview the reports and compare decisions
Review the reports and compare decisions
Compare the initial East Market proposals with the final reviewed report. The
RefNomapping appears only after an explicit human decision because a reference identifier is not automatically the same business concept as a transaction identifier. Approved aliases can make later schemas easier to review, while every new dataset still needs business validation.On the supplied synthetic fixture, the no-alias proposals produced 9 of 15 suggestions and left 8 rows for a human decision after safe bulk approval; reviewed-alias proposals produced 12 of 15 suggestions and left 3 rows. These counts are locally observed fixture results, not measured time savings or a prediction of production accuracy. The saved outputs in this notebook are local; inline HTML rendering and file access still need confirmation in a live Fabric workspace.
Revisar resultados
Compara el informe inicial de propuestas con el informe final revisado. Approved indica una aceptacion por la regla segura o una revisión explicita; Suggested aun no se aplica; Needs Review señala ambiguedad o riesgo; Rejected registra el rechazo de una persona; y Unmatched significa que no hubo una propuesta respaldada. Las puntuaciones heurísticas ordenan la similitud de nombres: no son probabilidades ni confirman el significado del negocio. RefNo requiere revisión explicita porque una referencia puede identificar un objeto distinto de una transacción. En este fixture sintético, sin alias hubo 9/15 propuestas y 8 filas que requerían decision humana tras la aprobación segura; con alias revisados, 12/15 y 3 filas. Son conteos del fixture, no ahorros de tiempo medidos ni evidencia de precisión en producción. El informe final se guarda en Files/javimapper/output/mapping-report.html.
Usar JaviMapper en una canalización real de Fabric
Los dos notebooks siguientes reutilizan el mismo Environment publicado de Fabric y un único wheel JaviMapper 0.6.0b1. Conecta ese Environment y el mismo Lakehouse predeterminado a ambos notebooks. Carga east.csv y east_delivery_02.csv en Files/javimapper/input/. El notebook de incorporación muestra las propuestas y registra decisiones de referencia didácticas para estos datos ficticios; esas decisiones programadas no son una aprobación interactiva de una persona responsable de los datos.
Incorporación de comercios
Revisa el primer informe, sus advertencias semánticas y las decisiones explícitas. El notebook guarda Files/javimapper/config/east-market/approved-mapping-v1.json. Este JSON de mapeo aprobado contiene los esquemas de origen y destino y el contrato de correspondencias que usa la ingesta. El archivo opcional east-market-aliases-v1.json es diferente: contiene sugerencias revisadas para futuras correspondencias. No reemplaza el mapeo aprobado y la ingesta recurrente no lo carga. Los archivos versionados se crean sin sobrescribir; elige un nombre de versión nuevo para una aprobación posterior.
Notebook: merchant-onboarding.ipynb
Vista de solo lectura del archivo del notebook. Nada en esta página ejecuta código.
Celda 1MarkdownMerchant onboarding with JaviMapper
Merchant onboarding with JaviMapper
This Fabric Spark notebook demonstrates how a team can review a new merchant schema once and save an approved mapping for later ingestion. It uses only fictional East Market data. It does not create or modify Fabric items automatically.
Attach the same published Environment that contains the private
javimapper==0.6.0b1wheel and attach the lab Lakehouse as the default Lakehouse. Uploadeast.csvandeast_delivery_02.csvfromlabs/javimapper-mapping-lab/data/toFiles/javimapper/input/. The approved mapping is written toFiles/javimapper/config/east-market/approved-mapping-v1.json; an optional alias export is a separate file.Approval note: the decisions in this notebook are scripted educational reference decisions for the fictional fixture. They are not an interactive approval by a data owner. In a real onboarding workflow, stop after reviewing the proposal and have an authorized person approve the decisions before saving them.
Celda 2Markdown1. Verify the Environment and source file
1. Verify the Environment and source file
Fabric supplies the running
sparksession. The notebook does not install packages or start another Fabric session. In local mode, it uses a local Spark session only when one was not supplied.Celda 3PySparkCode49 líneas
from datetime import date from pathlib import Path import sys import pyspark import javimapper from javimapper import AliasSet, Field, MatchMethod, Matcher, Schema, render_html from javimapper.adapters.spark import schema_from_spark EXECUTION_MODE = "fabric" # set to "local" only for local notebook testing EXPECTED_VERSION = "0.6.0b1" assert javimapper.__version__ == EXPECTED_VERSION, f"Expected {EXPECTED_VERSION}; found {javimapper.__version__}" if EXECUTION_MODE == "fabric": assert "spark" in globals(), "Use a Fabric Spark notebook with its provided spark session." assert "notebookutils" in globals(), "Attach the default Lakehouse in Fabric." INPUT_DIR = "Files/javimapper/input" CONFIG_DIR = "Files/javimapper/config/east-market" OUTPUT_DIR = "Files/javimapper/output" required_files = {"east.csv", "east_delivery_02.csv"} found_files = {item.name for item in notebookutils.fs.ls(INPUT_DIR) if item.isFile} assert required_files <= found_files, f"Missing Lakehouse files: {sorted(required_files - found_files)}" SOURCE_PATH = f"{INPUT_DIR}/east.csv" else: from pyspark.sql import SparkSession LOCAL_LAKEHOUSE_ROOT = Path(globals().get("LOCAL_LAKEHOUSE_ROOT", Path.cwd() / ".codex-artifacts/javimapper-local-lakehouse")).resolve() if "spark" not in globals(): spark = SparkSession.builder.master("local[1]").appName("JaviMapperOnboardingLab").getOrCreate() local_input = LOCAL_LAKEHOUSE_ROOT / "Files/javimapper/input" required_files = {"east.csv", "east_delivery_02.csv"} found_files = {p.name for p in local_input.glob("*.csv")} assert required_files <= found_files, f"Copy both synthetic East Market CSVs to {local_input}" INPUT_DIR = str(local_input) CONFIG_DIR = LOCAL_LAKEHOUSE_ROOT / "Files/javimapper/config/east-market" OUTPUT_DIR = LOCAL_LAKEHOUSE_ROOT / "Files/javimapper/output" SOURCE_PATH = str(local_input / "east.csv") print(f"JaviMapper {javimapper.__version__} | Python {sys.version.split()[0]} | PySpark {pyspark.__version__} | Spark {spark.version}") print(f"Source file: {Path(SOURCE_PATH).name} (fictional East Market data)") source_df = spark.read.option("header", True).option("inferSchema", False).csv(SOURCE_PATH) source_schema = schema_from_spark(source_df) TARGET_SCHEMA = Schema.of([ Field("transaction_id", "string", required=True), Field("transaction_date", "string", required=True), Field("customer_id", "string", required=True), Field("gross_amount", "string", required=True), Field("currency", "string", required=True), ]) print("Source columns and Spark types:", [(field.name, field.dtype) for field in source_schema]) print("Required canonical fields:", TARGET_SCHEMA.names)Salida
JaviMapper 0.6.0b1 | Python 3.12.10 | PySpark 4.3.0 | Spark 4.3.0 Source file: east.csv (fictional East Market data) Source columns and Spark types: [('RefNo', 'string'), ('DateOfSale', 'string'), ('ClientNo', 'string'), ('SaleValue', 'string'), ('Currency', 'string')] Required canonical fields: ['transaction_id', 'transaction_date', 'customer_id', 'gross_amount', 'currency']Celda 4Markdown2. Inspect the initial proposal
2. Inspect the initial proposal
The report is a read-only summary of suggestions, warnings and alternatives. It does not inspect row values or decide whether two names have the same business meaning. In particular,
RefNois not automatically treated as a transaction identifier: the semantic safeguard sees a reference-versus-transaction conflict.Celda 5PySparkCode19 líneas
plan = Matcher().suggest(source_schema, TARGET_SCHEMA) print(plan.explain()) for result in plan.results: for warning in result.warnings: print(f"Review warning for {result.source}: {warning.message}") refno_risks = plan.semantic_risks("RefNo", "transaction_id", MatchMethod.MANUAL) for risk in refno_risks: print(f"RefNo semantic warning ({risk.kind.value}): {risk.message}") initial_report_html = render_html(plan, title="East Market onboarding: initial unapproved proposals") print("Initial proposal HTML prepared from memory.") try: from IPython.display import HTML, display display(HTML(initial_report_html)) except Exception as display_error: if EXECUTION_MODE == "fabric" and callable(globals().get("displayHTML")): displayHTML(initial_report_html) else: print(f"Inline HTML display unavailable ({type(display_error).__name__}); the report remains available in this cell's code-generated preview only.")Salida
source suggested target method score state notes ---------- ---------------- ---------- ------ ------------ ----- RefNo - - - unmatched DateOfSale - - - unmatched ClientNo customer_id fuzzy 0.7324 needs_review fuzzy_match; semantic_risk SaleValue - - - unmatched Currency currency normalized 1.0000 suggested [conflict] required target 'transaction_id' has no suggested source [conflict] required target 'transaction_date' has no suggested source [conflict] required target 'gross_amount' has no suggested source Scores are heuristic name-similarity scores, not probabilities. Review warning for RefNo: no target candidate for 'RefNo' Review warning for DateOfSale: no target candidate for 'DateOfSale' Review warning for ClientNo: 'ClientNo' -> 'customer_id' is a fuzzy suggestion (heuristic score 0.7324); review it Review warning for ClientNo: 'ClientNo' has ['number'] and 'customer_id' has ['identifier'], which the other lacks Review warning for SaleValue: no target candidate for 'SaleValue' RefNo semantic warning (role_conflict): both are 'identifier' columns, but of different things: 'reference' vs 'transaction' Initial proposal HTML prepared from memory. Inline HTML display unavailable (ModuleNotFoundError); the report remains available in this cell's code-generated preview only.
Celda 6Markdown3. Review and explicitly approve the educational example
3. Review and explicitly approve the educational example
The following decisions describe this synthetic reference file only. The code makes the approvals explicit so the saved JSON records the chosen source-to-target pairs and the
RefNosemantic-risk override. A production process should collect approval from an authorized person and record a real reviewer identity or ticket.Celda 7PySparkScripted teaching example only; this is not a live human approval workflow38 líneas
# Scripted teaching example only; this is not a live human approval workflow. approved_safe = plan.approve_suggestions() EDUCATIONAL_REFERENCE = { "RefNo": "transaction_id", "DateOfSale": "transaction_date", "ClientNo": "customer_id", "SaleValue": "gross_amount", "Currency": "currency", } for source_name, target_name in EDUCATIONAL_REFERENCE.items(): if plan.result(source_name).approved_target is None: if source_name == "RefNo": plan.approve( source_name, target_name, accept_semantic_risk=True, note="EDUCATIONAL REFERENCE ONLY: confirm this business meaning with an authorized data owner before use.", approved_by="synthetic lab example; no human approval recorded", ) else: plan.approve( source_name, target_name, note="EDUCATIONAL REFERENCE ONLY: mapping checked against the fictional fixture.", approved_by="synthetic lab example; no human approval recorded", ) assert not plan.missing_required(), f"Required fields still need decisions: {plan.missing_required()}" approved_mapping = plan.finalize(description="East Market fictional onboarding reference; version 1") assert approved_mapping.missing_required == [] print(f"Clean suggestions approved by the safe rule: {len(approved_safe)}") print("Final reference mapping:", approved_mapping.renames) print("Required fields mapped:", approved_mapping.target_schema.names) approved_report_html = render_html(plan, title="East Market onboarding: educational approved reference") try: from IPython.display import HTML, display display(HTML(approved_report_html)) except Exception as display_error: if EXECUTION_MODE == "fabric" and callable(globals().get("displayHTML")): displayHTML(approved_report_html) else: print(f"Inline HTML display unavailable ({type(display_error).__name__}); approved report HTML was generated.")Salida
Clean suggestions approved by the safe rule: 1 Final reference mapping: {'RefNo': 'transaction_id', 'DateOfSale': 'transaction_date', 'ClientNo': 'customer_id', 'SaleValue': 'gross_amount', 'Currency': 'currency'} Required fields mapped: ['transaction_id', 'transaction_date', 'customer_id', 'gross_amount', 'currency'] Inline HTML display unavailable (ModuleNotFoundError); approved report HTML was generated.Celda 8Markdown4. Save a versioned approved mapping and optional aliases
4. Save a versioned approved mapping and optional aliases
Approved mapping JSON is the complete, validated contract Notebook 2 needs: source schema metadata, target schema metadata, approved source-to-target pairs, methods, notes and any accepted safeguards. The alias JSON is a separate optional matching aid for future onboarding. Aliases do not replace the approved mapping and are not proof that future data has the same meaning.
Version 1 is create-only. If the file already exists, do not overwrite it; review the change and deliberately choose a new versioned filename.
Celda 9PySparkCode34 líneas
MAPPING_FILENAME = "approved-mapping-v1.json" ALIAS_FILENAME = "east-market-aliases-v1.json" mapping_json = approved_mapping.to_json() alias_set = AliasSet.from_mapping( approved_mapping, namespace="east-market", description="Optional reviewed hints exported from the fictional onboarding reference.", reviewed_at=date.today().isoformat(), ) alias_json = alias_set.to_json() if EXECUTION_MODE == "fabric": notebookutils.fs.mkdirs(CONFIG_DIR) notebookutils.fs.put(f"{CONFIG_DIR}/{MAPPING_FILENAME}", mapping_json, False) notebookutils.fs.put(f"{CONFIG_DIR}/{ALIAS_FILENAME}", alias_json, False) notebookutils.fs.mkdirs(OUTPUT_DIR) notebookutils.fs.put(f"{OUTPUT_DIR}/east-market-approved-v1.html", approved_report_html, False) print(f"Created {CONFIG_DIR}/{MAPPING_FILENAME}") print(f"Created optional alias set {CONFIG_DIR}/{ALIAS_FILENAME}") else: CONFIG_DIR.mkdir(parents=True, exist_ok=True) OUTPUT_DIR.mkdir(parents=True, exist_ok=True) for path, content in ( (CONFIG_DIR / MAPPING_FILENAME, mapping_json), (CONFIG_DIR / ALIAS_FILENAME, alias_json), (OUTPUT_DIR / "east-market-approved-v1.html", approved_report_html), ): if path.exists(): raise FileExistsError(f"Refusing to overwrite versioned lab artifact: {path.name}; choose a new version.") path.write_text(content, encoding="utf-8") print(f"Created Files/javimapper/config/east-market/{MAPPING_FILENAME}") print(f"Created optional alias set Files/javimapper/config/east-market/{ALIAS_FILENAME}") print(f"Approved mapping format: {approved_mapping.to_dict()['format']} v{approved_mapping.to_dict()['format_version']}") print(f"Optional alias format: {alias_set.to_dict()['format']} v{alias_set.to_dict()['format_version']}")Salida
Created Files/javimapper/config/east-market/approved-mapping-v1.json Created optional alias set Files/javimapper/config/east-market/east-market-aliases-v1.json Approved mapping format: javimapper.approved-mapping v1 Optional alias format: javimapper.alias-set v2
Celda 10MarkdownWhat this example does not approve
What this example does not approve
JaviMapper proposes names; it does not transform values, establish business semantics, or approve decisions on behalf of a person. An unsupported or ambiguous field must remain unresolved until reviewed. This example's explicit
RefNooverride exists only to exercise the audit trail on fictional data. Do not copy it into a production mapping without independent approval.
Ingesta recurrente
El segundo notebook empieza con un espacio de Python nuevo y carga directamente desde OneLake el JSON guardado. No importa variables del notebook de incorporación ni ejecuta búsqueda difusa. Comprueba nombres, orden y tipos Spark de origen, campos obligatorios de salida y claves duplicadas antes de escribir. Si detecta una diferencia, detiene el proceso para revisión.
JaviMapper transforma las columnas de origen aprobadas en columnas canónicas. El notebook —no JaviMapper— añade metadatos del comercio, archivo, entrega y hora de ingesta, define la clave (source_merchant, transaction_id), comprueba duplicados, crea la tabla Delta del laboratorio javimapper_lab_standardized_transactions y ejecuta MERGE. Resultados observados en Fabric: primera ejecución entrada=2, insertadas=2, coincidencias/upserts=0, almacenadas=2, claves duplicadas=0; repetición entrada=2, insertadas=0, coincidencias/upserts=2, almacenadas=2, claves duplicadas=0. La repetición actualizó ingested_at_utc; por eso idempotencia sin duplicados no significa filas idénticas byte a byte. Esta tabla del laboratorio está separada de las tablas de negocio.
Notebook: recurring-ingestion.ipynb
Vista de solo lectura del archivo del notebook. Nada en esta página ejecuta código.
Celda 1MarkdownRecurring ingestion with an approved JaviMapper contract
Recurring ingestion with an approved JaviMapper contract
This notebook is intentionally independent from the onboarding notebook's Python variables. It loads the saved
ApprovedMappingJSON from the default Lakehouse, checks the second fictional East Market delivery against the stored source schema, applies only that approved mapping with PySpark, and upserts the standardized rows into a lab-specific Delta table.Attach the same published Environment containing
javimapper==0.6.0b1and the same default Lakehouse. Notebook 1 must have createdFiles/javimapper/config/east-market/approved-mapping-v1.json. Uploadeast_delivery_02.csvtoFiles/javimapper/input/. This notebook never invokesMatcher, runs fuzzy matching, or approves a new mapping.Celda 2Markdown1. Verify the Environment and load saved configuration
1. Verify the Environment and load saved configuration
The approved mapping JSON is authoritative for this ingestion run. The optional alias JSON is only a future matching aid and is not loaded here.
Celda 3PySparkCode35 líneas
from pathlib import Path import sys import pyspark import javimapper from javimapper import ApprovedMapping from javimapper.adapters.spark import apply_mapping, schema_from_spark EXECUTION_MODE = "fabric" # set to "local" only for local notebook testing EXPECTED_VERSION = "0.6.0b1" assert javimapper.__version__ == EXPECTED_VERSION, f"Expected {EXPECTED_VERSION}; found {javimapper.__version__}" TABLE_NAME = "javimapper_lab_standardized_transactions" MAPPING_RELATIVE = "Files/javimapper/config/east-market/approved-mapping-v1.json" SOURCE_RELATIVE = "Files/javimapper/input/east_delivery_02.csv" if EXECUTION_MODE == "fabric": assert "spark" in globals(), "Use the Fabric-provided Spark session." assert "notebookutils" in globals(), "Attach the default Lakehouse in Fabric." mapping_json = notebookutils.fs.head(MAPPING_RELATIVE, 1_000_000) SOURCE_PATH = SOURCE_RELATIVE else: from pyspark.sql import SparkSession LOCAL_LAKEHOUSE_ROOT = Path(globals().get("LOCAL_LAKEHOUSE_ROOT", Path.cwd() / ".codex-artifacts/javimapper-local-lakehouse")).resolve() if "spark" not in globals(): spark = SparkSession.builder.master("local[1]").appName("JaviMapperRecurringIngestionLab").getOrCreate() mapping_path = LOCAL_LAKEHOUSE_ROOT / MAPPING_RELATIVE mapping_json = mapping_path.read_text(encoding="utf-8") SOURCE_PATH = str(LOCAL_LAKEHOUSE_ROOT / SOURCE_RELATIVE) LOCAL_TABLE_PATH = LOCAL_LAKEHOUSE_ROOT / "Tables" / f"{TABLE_NAME}.json" mapping = ApprovedMapping.from_json(mapping_json) assert mapping.target_schema.names == ["transaction_id", "transaction_date", "customer_id", "gross_amount", "currency"] assert not mapping.missing_required, f"Mapping does not cover required fields: {mapping.missing_required}" print(f"JaviMapper {javimapper.__version__} | Python {sys.version.split()[0]} | PySpark {pyspark.__version__} | Spark {spark.version}") print(f"Loaded approved mapping JSON: {MAPPING_RELATIVE}") print(f"Approved source columns: {mapping.source_schema.names}")Salida
JaviMapper 0.6.0b1 | Python 3.12.10 | PySpark 4.3.0 | Spark 4.3.0 Loaded approved mapping JSON: Files/javimapper/config/east-market/approved-mapping-v1.json Approved source columns: ['RefNo', 'DateOfSale', 'ClientNo', 'SaleValue', 'Currency']
Celda 4Markdown2. Stop on source schema drift
2. Stop on source schema drift
The expected source names, order and Spark type metadata come from the saved mapping file. Any missing, unexpected, reordered or type-changed column stops the notebook before applying the mapping. Resolve a real schema change in onboarding; do not guess a new match during recurring ingestion.
Celda 5PySparkCode13 líneas
source_df = spark.read.option("header", True).option("inferSchema", False).csv(SOURCE_PATH) current_source_schema = schema_from_spark(source_df) expected_source_columns = mapping.source_schema.names actual_source_columns = current_source_schema.names missing_columns = sorted(set(expected_source_columns) - set(actual_source_columns)) unexpected_columns = sorted(set(actual_source_columns) - set(expected_source_columns)) if missing_columns or unexpected_columns: raise ValueError(f"Source columns differ from approved mapping. Missing={missing_columns}; unexpected={unexpected_columns}") if current_source_schema != mapping.source_schema: raise ValueError(f"Source schema metadata or column order changed. Expected={mapping.source_schema.to_dict()}; actual={current_source_schema.to_dict()}") mapping.check_columns(actual_source_columns, keep_unmapped=False) print("Source columns and Spark type metadata match the approved onboarding schema.") print(f"Input: {Path(SOURCE_PATH).name}; columns={actual_source_columns}")Salida
Source columns and Spark type metadata match the approved onboarding schema. Input: east_delivery_02.csv; columns=['RefNo', 'DateOfSale', 'ClientNo', 'SaleValue', 'Currency']
Celda 6Markdown3. Apply only the approved mapping and validate output
3. Apply only the approved mapping and validate output
JaviMapper renames and orders columns; it does not cast values. This fixture keeps source and canonical values as strings. Production pipelines should define and test any required type conversions separately.
Celda 7PySparkCode31 líneas
from pyspark.sql import functions as F SOURCE_MERCHANT = "east_market" SOURCE_FILE = "east_delivery_02.csv" DELIVERY_ID = "east_market_delivery_02" canonical_columns = mapping.target_schema.names required_columns = [field.name for field in mapping.target_schema if field.required] standardized = apply_mapping(source_df, mapping, unmapped="drop", order="target") if standardized.columns != canonical_columns: raise ValueError(f"Canonical output columns differ: {standardized.columns}") missing_required = sorted(set(required_columns) - set(standardized.columns)) if missing_required: raise ValueError(f"Required canonical columns are absent: {missing_required}") null_required = [name for name in required_columns if standardized.filter(F.col(name).isNull()).limit(1).count()] if null_required: raise ValueError(f"Required canonical columns contain nulls: {null_required}") # Pipeline metadata is added after JaviMapper; it is not part of the mapping contract. incoming = (standardized .withColumn("source_merchant", F.lit(SOURCE_MERCHANT)) .withColumn("source_file", F.lit(SOURCE_FILE)) .withColumn("delivery_id", F.lit(DELIVERY_ID)) .withColumn("ingested_at_utc", F.current_timestamp())) key_columns = ["source_merchant", "transaction_id"] duplicate_input_keys = (incoming.groupBy(*key_columns).count().filter(F.col("count") > 1).limit(1).count()) if duplicate_input_keys: raise ValueError(f"Delivery contains duplicate upsert keys: {key_columns}") input_rows = incoming.count() print(f"Canonical output columns: {canonical_columns}") print(f"Required fields present and non-null: {required_columns}") print(f"Input rows ready for idempotent upsert: {input_rows}")Salida
Canonical output columns: ['transaction_id', 'transaction_date', 'customer_id', 'gross_amount', 'currency'] Required fields present and non-null: ['transaction_id', 'transaction_date', 'customer_id', 'gross_amount', 'currency'] Input rows ready for idempotent upsert: 2
Celda 8Markdown4. Upsert into the lab-specific Delta table
4. Upsert into the lab-specific Delta table
Fabric writes to the dedicated table
javimapper_lab_standardized_transactions. First creation fails if that table already exists; later runs use DeltaMERGEkeyed by(source_merchant, transaction_id). A repeated delivery updates the existing key rather than inserting a duplicate. This notebook never overwrites another table.For local testing only, the notebook uses a dedicated JSON file because the repository's local Spark environment does not include Fabric's Delta runtime and may lack Windows Hadoop helpers. It applies the same key-based replacement logic to the tiny fixture; this is not evidence of a live Fabric Delta write.
Celda 9PySparkCode73 líneas
import json from datetime import date, datetime if EXECUTION_MODE == "fabric": from delta.tables import DeltaTable table_exists = spark.catalog.tableExists(TABLE_NAME) if table_exists: existing = spark.table(TABLE_NAME) existing_types = [(field.name, field.dataType.simpleString()) for field in existing.schema.fields] incoming_types = [(field.name, field.dataType.simpleString()) for field in incoming.schema.fields] if existing_types != incoming_types: raise ValueError(f"Existing lab Delta table schema changed. Existing={existing_types}; incoming={incoming_types}") existing_keys = existing.select(*key_columns).distinct() inserted_rows = incoming.select(*key_columns).join(existing_keys, key_columns, "left_anti").count() matched_rows = input_rows - inserted_rows condition = " AND ".join(f"target.{name} = source.{name}" for name in key_columns) (DeltaTable.forName(spark, TABLE_NAME).alias("target") .merge(incoming.alias("source"), condition) .whenMatchedUpdateAll() .whenNotMatchedInsertAll() .execute()) else: inserted_rows = input_rows matched_rows = 0 incoming.write.format("delta").mode("errorifexists").saveAsTable(TABLE_NAME) stored = spark.table(TABLE_NAME) stored_rows = stored.count() stored_duplicates = stored.groupBy(*key_columns).count().filter(F.col("count") > 1).limit(1).count() current_delivery_rows = stored.filter(F.col("delivery_id") == DELIVERY_ID).count() stored.orderBy("transaction_id").show(truncate=False) storage_format = "Fabric Delta" else: # The local Spark test environment has no Delta runtime and may lack winutils; persist only the # tiny fictional fixture with standard Python JSON I/O after Spark has transformed it. LOCAL_TABLE_PATH.parent.mkdir(parents=True, exist_ok=True) schema_signature = [[field.name, field.dataType.simpleString()] for field in incoming.schema.fields] if LOCAL_TABLE_PATH.exists(): local_state = json.loads(LOCAL_TABLE_PATH.read_text(encoding="utf-8")) if local_state.get("schema") != schema_signature: raise ValueError("Existing local lab table schema differs; refusing to replace it.") stored_records = local_state["rows"] else: stored_records = [] incoming_records = [] for row in incoming.collect(): record = row.asDict(recursive=True) if isinstance(record.get("ingested_at_utc"), datetime): record["ingested_at_utc"] = record["ingested_at_utc"].isoformat() + "Z" incoming_records.append(record) existing_keys = {(row["source_merchant"], row["transaction_id"]) for row in stored_records} incoming_keys = [(row["source_merchant"], row["transaction_id"]) for row in incoming_records] incoming_key_set = set(incoming_keys) inserted_rows = sum(key not in existing_keys for key in incoming_keys) matched_rows = input_rows - inserted_rows retained = [row for row in stored_records if (row["source_merchant"], row["transaction_id"]) not in incoming_key_set] merged_records = retained + incoming_records LOCAL_TABLE_PATH.write_text(json.dumps({"schema": schema_signature, "rows": merged_records}, indent=2, default=str) + "\n", encoding="utf-8") stored_records = merged_records stored_rows = len(stored_records) stored_keys = [(row["source_merchant"], row["transaction_id"]) for row in stored_records] stored_duplicates = int(len(stored_keys) != len(set(stored_keys))) current_delivery_rows = sum(row["delivery_id"] == DELIVERY_ID for row in stored_records) print(json.dumps(sorted(stored_records, key=lambda row: row["transaction_id"]), indent=2)) storage_format = "local JSON test fallback" if stored_duplicates: raise AssertionError("Upsert produced duplicate merchant transaction keys.") if current_delivery_rows != input_rows: raise AssertionError(f"Expected {input_rows} rows for this delivery; found {current_delivery_rows}.") assert inserted_rows + matched_rows == input_rows print(f"Storage: {storage_format} | table: {TABLE_NAME}") print(f"Reconciliation: input={input_rows}, inserted={inserted_rows}, matched/upserted={matched_rows}, stored={stored_rows}, delivery_rows={current_delivery_rows}") print("Duplicate upsert keys in stored table: 0")Salida
[ { "transaction_id": "E-3003", "transaction_date": "2026-03-08", "customer_id": "C-42", "gross_amount": "19.95", "currency": "GBP", "source_merchant": "east_market", "source_file": "east_delivery_02.csv", "delivery_id": "east_market_delivery_02", "ingested_at_utc": "2026-11-29T17:13:31.922159Z" }, { "transaction_id": "E-3004", "transaction_date": "2026-03-09", "customer_id": "C-43", "gross_amount": "72.10", "currency": "GBP", "source_merchant": "east_market", "source_file": "east_delivery_02.csv", "delivery_id": "east_market_delivery_02", "ingested_at_utc": "2026-11-29T17:13:31.922159Z" } ] Storage: local JSON test fallback | table: javimapper_lab_standardized_transactions Reconciliation: input=2, inserted=2, matched/upserted=0, stored=2, delivery_rows=2 Duplicate upsert keys in stored table: 0Celda 10MarkdownRerun and failure behavior
Rerun and failure behavior
Run this notebook again with the same delivery ID to exercise idempotency: the expected result is zero new inserts and two matched/upserted keys, with no duplicate
(source_merchant, transaction_id)rows. Unexpected source columns, missing required fields, schema metadata changes and duplicate keys fail before the write. If an earlier write partially completes, rerunning the same delivery safely reconciles the same keys.A different file or source schema must go through onboarding first. Create a new approved mapping version there; never auto-match or auto-approve changes in this ingestion notebook.
Las pruebas locales usan un respaldo de persistencia JSON porque el Spark local no incluye el runtime Delta de Fabric. Confirma en un workspace Fabric real la creación de la tabla Delta, MERGE, las rutas de OneLake y la compatibilidad del Environment antes de considerarlos validados en Fabric.
Solución de problemas y limpieza
- Falla el import o cambia la versión: confirma el Environment conectado, que la publicación terminó y que iniciaste una sesión nueva; comprueba
javimapper.__version__. - Conflicto Python/Spark o al publicar: compara las versiones activas con los requisitos. Elige un runtime compatible o solicita una versión admitida; no sobrescribas paquetes sin revisión.
- Falta un CSV: verifica el Lakehouse predeterminado, los nombres exactos y
Files/javimapper/input/. - No existe
notebookutils: usa un Spark notebook de Fabric con Lakehouse conectado, no un kernel Python local. - No aparece el informe: revisa
Files/javimapper/output/en Lakehouse Explorer tras el éxito de la celda.
Al terminar, detén la sesión. Elimina Environment, notebook o Lakehouse solo si los creaste exclusivamente para esta práctica y ya no los necesitas; no borres recursos compartidos.
Ruta local opcional de pandas/PySpark
Desde la raíz del repositorio:
python -m pip install -e "./libraries/javimapper[pandas,spark]"
python labs/javimapper-mapping-lab/run_lab.py
Configura Java compatible con PySpark. Para el notebook cambia EXECUTION_MODE a local; encontrará los fixtures en el repositorio o en el bundle privado extraído y solo creará una sesión Spark local si no existe. El script escribe resultados bajo output/ del laboratorio. El bundle y el wheel siguen siendo privados; ninguno se descarga desde el sitio.
Avanzado: crear el wheel desde el código fuente
Desde la raíz del repositorio, genera un wheel local privado cuando lo necesites:
python -m pip install --upgrade build
python -m build --wheel --outdir .codex-artifacts/private-wheels libraries/javimapper
python -m zipfile -l .codex-artifacts/private-wheels/javimapper-0.6.0b1-py3-none-any.whl
Confirma la versión y los metadatos LICENSE/NOTICE de Apache-2.0. El wheel no debe contener credenciales, datos locales, entornos virtuales ni rutas específicas de una máquina. Fabric proporciona pandas y PySpark según el runtime; no añadas wheels opcionales sin comprobar su compatibilidad. Mantén el resultado en .codex-artifacts/, que está excluido de Git, nunca en public/ o dist/.