This project demonstrates a Python-based solution for incrementally synchronizing data from a Delta Lake table to an Azure AI Search index. It handles new records, updates to existing records, and deletions.
delta-ais-incremental-sync/
├── data/ # Auto-generated: Stores the Delta table and state file
│ ├── my_delta_pdf_extractions/ # Delta table files
│ └── sync_state.json # Stores the last processed Delta table version
├── src/
│ ├── data_generator.py # Generates sample data and writes to Delta Lake
│ └── delta_to_ais_sync.py # Reads from Delta Lake and syncs to Azure AI Search
└── README.md # This file
-
src/data_generator.py:- Simulates real-world data changes by generating sample PDF extraction-like data.
- Creates an initial batch of records.
- Subsequent runs generate a mix of new records, updates to existing records, and records marked for deletion.
- Writes these changes to a local Delta Lake table (
./data/my_delta_pdf_extractions). - Uses an
actioncolumn (upsertordelete) to indicate the intended operation for each record in the batch.
-
src/delta_to_ais_sync.py:- Reads data incrementally from the Delta Lake table.
- Tracks the last processed Delta table version using a state file (
./data/sync_state.json) to avoid reprocessing data. - Connects to an Azure AI Search service.
- Transforms records from the Delta table into the format expected by the Azure AI Search index.
- Uploads new/updated documents and deletes documents marked for deletion in Azure AI Search.
- Python 3.7+
- Azure AI Search Service:
- An active Azure AI Search service.
- An existing Search Index. The schema of this index must be compatible with the data being sent. Key fields include:
id(string, key field)doc_id_source(string)element_type(string)page_number(int32)text_content(string)image_location(string)content_vector(collection of single - for embeddings) //sample dimension is 5 herebounding_box(collection of double)additional_metadata(string)last_modified_delta(datetimeoffset) You may need to adjusttransform_to_search_documentindelta_to_ais_sync.pyif your index schema differs.
- Required Python Packages:
pandasdeltalakepyarrowFaker(fordata_generator.py)azure-search-documentsazure-core
-
Clone the Repository (if applicable) or Create Files: Ensure you have the
src/data_generator.pyandsrc/delta_to_ais_sync.pyfiles in your project structure. -
Install Dependencies: Open your terminal in the root
delta-ais-incremental-syncdirectory and run:pip install pandas deltalake pyarrow Faker azure-search-documents azure-core
-
Azure Access Setup for Managed Identity
This project uses Managed Identity to securely access Azure AI Search, eliminating the need for storing secrets like admin keys in the configuration.
To run the Python scripts that interact with Azure AI Search, you need to ensure that the environment where the script executes (e.g., an Azure Virtual Machine, Azure App Service, Azure Functions, or your local machine if using Azure CLI login) has an identity with the necessary permissions on your Azure AI Search service.
-
Ensure your Execution Environment has a Managed Identity or You are Logged in via Azure CLI: * Azure Hosted Services (VM, App Service, Functions, etc.):
- Enable a System-Assigned Managed Identity for your Azure resource.
- Alternatively, create a User-Assigned Managed Identity and associate it with your Azure resource. * Local Development:
- Ensure you are logged in with the Azure CLI:
az login - The
DefaultAzureCredentialused in the script will pick up these credentials. - Alternatively, you can set environment variables for a service principal if you prefer not to use your personal Azure CLI login for automation.
-
Grant Permissions to the Managed Identity (or your user/service principal): * Navigate to your Azure AI Search service in the Azure portal. * Go to Access control (IAM). * Click on + Add and then Add role assignment. * Select the role: Search Index Data Contributor. This role allows the identity to read, upload, and delete documents in the search index.
- If you also need to manage indexes (create, update, delete them programmatically, though not currently implemented in
delta_to_ais_sync.py), you might consider the Search Service Contributor role, but it has broader permissions. * Assign access to: - Managed identity: Select the system-assigned or user-assigned managed identity of your Azure resource.
- User, group, or service principal: If developing locally and using Azure CLI, search for your Azure AD user. If using a service principal, search for its name. * Click Save.
- If you also need to manage indexes (create, update, delete them programmatically, though not currently implemented in
-
Configure Environment Variables (if not hardcoded): * The script
delta_to_ais_sync.pywill look for the following environment variables:AZURE_SEARCH_SERVICE_ENDPOINT: The full URL of your Azure AI Search service (e.g.,https://your-search-service-name.search.windows.net).AZURE_SEARCH_INDEX_NAME: The name of your target search index. * While the script currently has these hardcoded as fallbacks, it's best practice to set them as environment variables, especially for the endpoint.
```bash
# Example for bash/zsh
export AZURE_SEARCH_SERVICE_ENDPOINT="https://your-search-service-name.search.windows.net"
export AZURE_SEARCH_INDEX_NAME="your-index-name"
# Example for PowerShell
$env:AZURE_SEARCH_SERVICE_ENDPOINT="https://your-search-service-name.search.windows.net"
$env:AZURE_SEARCH_INDEX_NAME="your-index-name"
```
- Install
azure-identity: * Ensure theazure-identityPython package is installed in your environment:pip install azure-identity
Once these steps are completed, the DefaultAzureCredential in the Python script should be able to authenticate with Azure AI Search using the Managed Identity (or your Azure CLI credentials for local development) and perform the necessary operations.
Execute the scripts from within the src directory.
-
Navigate to the
srcdirectory:cd path/to/delta-ais-incremental-sync/src -
Generate Data (Initial Load and Updates): Run the
data_generator.pyscript.python data_generator.py
- The first time you run this, it will create the Delta table in the
../data/my_delta_pdf_extractionsdirectory and populate it with initial data. - Subsequent runs will append new data, including updates and deletions, to the Delta table.
- The first time you run this, it will create the Delta table in the
-
Synchronize Data to Azure AI Search: Run the
delta_to_ais_sync.pyscript.python delta_to_ais_sync.py
- This script will read the
../data/sync_state.jsonfile to determine the last Delta table version it processed. - It will then read any new versions from the Delta table.
- Based on the
actioncolumn in the Delta records, it will perform upsert or delete operations on your Azure AI Search index. - After successful processing, it updates
sync_state.jsonwith the latest processed Delta table version.
- This script will read the
Running Sequentially:
Typically, you would run data_generator.py to simulate new data arriving, and then run delta_to_ais_sync.py to process these changes.
# Example workflow
python data_generator.py # First batch of data
python delta_to_ais_sync.py # Syncs the first batch
python data_generator.py # Simulate more data changes
python delta_to_ais_sync.py # Syncs only the new changes- Delta Lake: Used for reliable data storage. Its versioning capability is key to enabling incremental processing.
- Azure AI Search: The target search service where data is indexed for querying.
- Incremental Sync: Only changes since the last sync are processed, making the process efficient. This is managed by tracking the Delta table version in
sync_state.json. actionColumn: A column in the Delta table (upsertordelete) explicitly tells the sync script how to handle each record in Azure AI Search. This simplifies the logic for handling different types of operations, especially when not using Delta Lake's Change Data Feed (CDF) feature directly in this example.
- Data Schema: Modify the
generate_pdf_extraction_datafunction indata_generator.pyand thetransform_to_search_documentfunction indelta_to_ais_sync.pyto match your specific data structures. - Azure AI Search Index: Ensure your Azure AI Search index schema matches the data being sent by
transform_to_search_document. - Error Handling: The provided scripts have basic error handling. For production use, more robust error handling and logging should be implemented.
- Change Data Feed (CDF): For more advanced and efficient change tracking with Delta Lake, consider enabling and using its Change Data Feed (CDF) feature. The current example uses the
actioncolumn and processes the table state at the current version for simplicity.