Export Destinations¶
This guide explains when to use each export destination family and how to install only the optional dependencies you need.
For sink internals and data-flow architecture, see Architecture Overview. For full CLI syntax, see Command Line Interface (CLI).
Installation¶
# Install all tabular export dependencies
pip install "imednet[export]"
# Or install destination-specific extras
pip install "imednet[duckdb]"
pip install "imednet[mongodb]"
pip install "imednet[neo4j]"
pip install "imednet[snowflake]"
Destination decision matrix¶
Destination |
Best fit |
Data-shape characteristics |
Operational constraints |
|---|---|---|---|
MongoDB |
Application-facing document reads, schema-preserving archival |
Keeps nested |
Requires |
Neo4j |
Relationship-heavy exploration and lineage queries |
Preserves the hierarchy |
Requires |
Snowflake |
Warehouse-native analytics and bulk loading at scale |
Writes Parquet batch files, uploads to an internal stage, then issues
|
Requires |
SDK examples¶
Note
Every sink configuration (MongoDbSinkConfig, Neo4jSinkConfig, and
SnowflakeSinkConfig) enables PHI masking by default (mask_phi=True),
resolves committed StudyConfiguration governance rules automatically via
ConfigVersionStore (failing closed to global_sensitivity_registry
redaction when no configuration history or encryption key is present),
supports pre-write Record readiness filtering via
quality_gate_enabled=True and min_schema_readiness_score, and shares
CDISC SDTM transformation and standards readiness controls (as_sdtm,
sdtm_domain, standards_profile, min_standards_score, and
naming_convention; see Record Mapping Process and
Command Line Interface (CLI)).
MongoDB (document export):
from imednet import ImednetSDK
from imednet_sinks import MongoDbSinkConfig, export_to_mongodb
sdk = ImednetSDK(api_key="mock", security_key="mock")
mongodb_cfg = MongoDbSinkConfig(
study_key="MY_STUDY",
uri="mongodb://localhost:27017",
database="imednet",
collection="records",
batch_size=500,
idempotent=True,
)
rows = export_to_mongodb(sdk, "MY_STUDY", config=mongodb_cfg)
print(rows)
Neo4j (graph export):
from imednet import ImednetSDK
from imednet_sinks import Neo4jSinkConfig, export_to_neo4j
sdk = ImednetSDK(api_key="mock", security_key="mock")
neo4j_cfg = Neo4jSinkConfig(
study_key="MY_STUDY",
uri="bolt://localhost:7687",
auth=("neo4j", "..."),
database="neo4j",
batch_size=500,
idempotent=True,
quality_gate_enabled=True,
min_schema_readiness_score=90.0,
)
rows = export_to_neo4j(sdk, "MY_STUDY", config=neo4j_cfg)
print(rows)
Snowflake (warehouse-native export):
from imednet import ImednetSDK
from imednet_sinks import SnowflakeSinkConfig, export_to_snowflake
sdk = ImednetSDK(api_key="mock", security_key="mock")
snowflake_cfg = SnowflakeSinkConfig(
study_key="MY_STUDY",
account="myorg-myaccount",
user="loader",
password="...",
database="IMEDNET_DB",
schema="PUBLIC",
warehouse="COMPUTE_WH",
stage="MY_STAGE",
table="RECORDS",
)
rows = export_to_snowflake(sdk, "MY_STUDY", config=snowflake_cfg)
print(rows)
Incremental streaming checkpoints¶
Warehouse, document, graph, and all 12 tabular and standards exporters in imednet.integrations
(export_to_parquet(),
export_to_csv(),
export_to_excel(),
export_to_json(),
export_to_odm(),
export_to_dataset_json(),
export_to_sql(),
export_to_sql_by_form(),
export_to_long_sql(),
export_to_duckdb(),
export_to_duckdb_by_form(), and
export_to_hive_parquet()) share eight streaming checkpoint
and filter options on SinkConfig,
run_streaming_export(), and
ImednetExportOperator:
incremental(bool) – Enable transactional high-water mark reads and commits.stream_name(str | None) – Logical stream key in the ledger (for example"mongodb_records"or"vitals_parquet").ledger_path(str | Path | None) – Path for file-backed checkpoint state viaExtractionStateLedger(FileStateProvider).state_provider(StateProviderProtocol | None) – Explicit provider instance such asExtractionStateLedger(...),AirflowStateProvider, orget_state_provider().modified_since(datetime | str | None) – Initial UTC lower-bound watermark used when the stream has no prior checkpoint.record_filter(dict[str, Any] | str | None) –Recordmetadata filter pushed down toRecordsEndpoint.record_data_filter(str | None) –Variablepayload filter expression (recordDataFilter).include_deleted(bool) – Include voided (deleted=True)Recorditems directly in batches instead of reconciling deletes separately.
When incremental=True (or modified_since / state_provider is supplied),
idempotent=True, and include_deleted=False, all 12 tabular and standards helpers perform
keyed recordId (recordId, record_id, or RECORD_ID) upserts and prune
newly voided (deleted=True) Record items without duplicating history:
CSV and Parquet (
export_to_csv(),export_to_parquet()): stage incoming batches and voided IDs viareconcile_deleted, deduplicate deltas by canonicalrecordId, unify columns or Arrow schemas while streaming non-superseded rows to a.tmpfile, and atomically replace the destination file onflush().Excel and JSON (
export_to_excel(),export_to_json()): deduplicate delta rows byrecordId, prune superseded anddeleted=TrueRecordentries across Excel workbooks, flat JSON arrays, and hierarchicalSubject → Visit → FormJSON archives (hierarchical=True), and atomically rewrite the target file.CDISC ODM 1.3.2 and Dataset-JSON v1.1 (
export_to_odm(),export_to_dataset_json()): merge incrementalRecorddeltas by deterministicrecordId/ItemGroupRepeatKeyidentifiers, prune newly voideddeleted=TrueRecordentries viareconcile_deleted, validate against bundled CDISC schemas, write to a.tmpfile, and atomically replace the destination archive or per-domain Dataset-JSON files onflush()with PHI masking enabled by default.SQL and DuckDB (
export_to_sql(),export_to_sql_by_form(),export_to_long_sql(),export_to_duckdb(),export_to_duckdb_by_form()): delete supersededrecordId/record_idrows before appending updated batches (chunkedDELETE FROM ... WHERE ... IN (...)on SQLAlchemy targets;DELETE FROMplusINSERT INTO ... BY NAMEin DuckDB) and delete newly voideddeleted=TrueRecordIDs viareconcile_deleted.Hive Parquet (
export_to_hive_parquet()): write new per-Formpartition Parquet files understudy_key=<study>/form_key=<form>and rewrite pre-existing partition Parquet files to prune superseded anddeleted=TruerecordIdrows before committing per-Formcheckpoints.
State providers registered under imednet.state_providers (default, file, and
airflow) commit the updated watermark only after every batch, delete reconciliation,
and sink.flush() complete cleanly. When quality_gate_enabled=True and
apply_quality_gate() drops low-readiness Record items,
both run_streaming_export() and multi-Form tabular
streaming cap the committed max_ts watermark at min_rejected_ts (selecting the
highest exported Record timestamp <= min_rejected_ts, or holding back watermark
advancement when no exported timestamp precedes min_rejected_ts or any rejected
Record lacks a timestamp) so remediated Record items are re-evaluated on
subsequent incremental runs. Below is a resumable run_streaming_export example using
ExtractionStateLedger with mask_phi=True preserved by default:
import tempfile
from pathlib import Path
from imednet import ImednetSDK
from imednet.spi.sink_base import run_streaming_export
from imednet_sinks import MongoDbExportSink, MongoDbSinkConfig
from imednet_workflows import ExtractionStateLedger
with tempfile.TemporaryDirectory() as tmp_dir:
ledger_file = Path(tmp_dir) / "export_state.json"
ledger = ExtractionStateLedger(str(ledger_file))
incremental_cfg = MongoDbSinkConfig(
study_key="MY_STUDY",
uri="mongodb://localhost:27017",
database="imednet",
collection="records",
mask_phi=True,
incremental=True,
stream_name="mongodb_records",
ledger_path=ledger_file,
state_provider=ledger,
modified_since="2026-01-01T00:00:00Z",
record_filter={"form_key": "F_VS"},
record_data_filter="V_WEIGHT>0",
include_deleted=False,
)
written_count = run_streaming_export(
ImednetSDK(simulation_mode=True),
"STUDY",
lambda: MongoDbExportSink(incremental_cfg),
incremental_cfg,
)
assert written_count >= 0
PHI protection and masking controls¶
All destination sinks, partitioned Parquet exports, flat and hierarchical JSON
exports, and DataFrame converters mask Protected Health Information (PHI) at
mapper ingress by default (mask_phi=True):
Default sensitive keys: Registered clinical and CDISC identifiers—including
patientName/patient_name,patientInitials,SUBJINIT,DOB/date_of_birth/birth_date,BRTHDTC,BRTHDAT,BRTHYR,SSN,phone,email, andaddress—are replaced with***MASKED***before column label mapping (use_labels_as_columns=True), hierarchy construction, or sink batch serialization. On CDISC SDTM exports (sdtm_dataframe,iter_sdtm_dataframes, andas_sdtm=True), maskedBRTHDTCvalues are redacted to four-digit ISO 8601 years (YYYY) orNonerather than***MASKED***text.Relational identifiers preserved: Join, graph, and CDISC subject/study keys (
study_key,subject_key,record_id,STUDYID,USUBJID, andSUBJID) are explicitly exempted from masking so relational joins, MongoDB_iddocuments, Hive partitions, CDISC domain merges, and Neo4jMERGEgraph edges remain intact.Automatic Study governance resolution: Exports automatically inspect committed
StudyConfigurationrules fromConfigVersionStore(whenimednet-workflowsis installed) to enforce customphiFields,terminologyLookups, andmappingsacross flat, hierarchical, and sink paths. Store errors, missing plugins, or missing encryption keys fail closed soglobal_sensitivity_registryPHI redaction still applies.Pre-write quality-gate filtering: Quality-gate filtering is opt-in (
quality_gate_enabled=Falseby default across all CSV, Parquet, Excel, JSON, DuckDB, SQL, warehouse, document, and graph exports). Settingquality_gate_enabled=True(and optionalmin_schema_readiness_score) onSnowflakeSinkConfig,MongoDbSinkConfig,Neo4jSinkConfig, or tabular exports runsapply_quality_gate()before batch writes to drop empty drafts or invalidRecorditems while retaining sparseRecordpayloads that omit optionalVariablefields across warehouse, document, graph, and tabular targets. On incremental runs,run_streaming_exportand multi-Formtabular streaming capmax_tsatmin_rejected_tswheneverapply_quality_gatedropsRecorditems (or leavemax_tsuncommitted when no exported timestamp is<= min_rejected_tsor a rejectedRecordhas no timestamp) so droppedRecorditems are re-fetched after remediation.Study-specific rules: Study-level
StudyConfiguration(phiFields=[...])rules normalize camelCase, PascalCase, uppercase acronyms, andsnake_casefield names automatically across bothdocumentandtabularmapper modes and replace matched values with***MASKED***. Additional global identifiers can also be registered viaglobal_sensitivity_registry(exposed onimednet.spi.utilsfor extension plugins).
Customizing study PHI fields with CentralizedMapper:
from imednet.integrations.enrichment import CentralizedMapper
from imednet.models.study_config import StudyConfiguration
study_cfg = StudyConfiguration(
studyKey="MY_STUDY",
version="1.0",
reportingProfile="general",
phiFields=["patientName", "DOB", "SSN", "medicalRecordNumber"],
)
mapper = CentralizedMapper(mode="tabular", study_config=study_cfg)
Opting out for authorized identifiable data transfers:
When protocol governance explicitly authorizes transferring unmasked clinical
identifiers (for example, an approved 21 CFR Part 11 enclave archive or EDC
migration), pass mask_phi=False on the sink configuration, mapper, Airflow
ImednetExportOperator, or export helper—or pass --no-mask-phi on
imednet export CLI commands. Opting out applies only to that operation and
never mutates global_sensitivity_registry:
from imednet import ImednetSDK
from imednet_sinks import MongoDbSinkConfig, export_to_mongodb
sdk = ImednetSDK(api_key="mock", security_key="mock")
authorized_cfg = MongoDbSinkConfig(
study_key="MY_STUDY",
uri="mongodb://localhost:27017",
database="imednet",
collection="authorized_records",
mask_phi=False,
)
export_to_mongodb(sdk, "MY_STUDY", config=authorized_cfg)
imednet export json MY_STUDY /secure/enclave/study_archive.json --hierarchical --no-mask-phi
imednet export neo4j MY_STUDY bolt://localhost:7687 neo4j "$NEO4J_PASSWORD" --quality-gate --no-mask-phi