

# 使用 SAP OData 状态管理脚本


要在 Amazon Glue 作业中使用 SAP OData 状态管理脚本，请执行以下步骤：
+ 从公共 Amazon S3 存储桶下载状态管理脚本：`s3://aws-blogs-artifacts-public/artifacts/BDB-4789/sap_odata_state_management.zip `。
+ 将脚本上传到您的 Amazon Glue 作业有权访问的 Amazon S3 存储桶。
+ 在 Amazon Glue 作业中引用脚本：创建或更新 Amazon Glue 作业时，传递引用 Amazon S3 存储桶中脚本路径的 `'--extra-py-files'` 选项。例如：`--extra-py-files s3://your-bucket/path/to/sap_odata_state_management.py`
+ 在 Amazon Glue 作业脚本中导入和使用状态管理库。

## 基于增量令牌的增量传输示例


以下是有关如何使用状态管理脚本进行基于增量令牌的增量传输的示例：

```
from sap_odata_state_management import StateManagerFactory, StateManagerType, StateType

# Initialize the state manager
state_manager = StateManagerFactory.create_manager(
    manager_type=StateManagerType.JOB_TAG,
    state_type=StateType.DELTA_TOKEN,
    options={
        "job_name": args['JOB_NAME'],
        "logger": logger
    }
)

# Get connector options (including delta token if available)
key = "SAPODataNode"
connector_options = state_manager.get_connector_options(key)

# Use the connector options in your Glue job
df = glueContext.create_dynamic_frame.from_options(
    connection_type="SAPOData",
    connection_options={
        "connectionName": "connectionName",
        "ENTITY_NAME": "entityName",
        "ENABLE_CDC": "true",
        **connector_options
    }
)

# Process your data here...

# Update the state after processing
state_manager.update_state(key, sapodata_df.toDF())
```

## 基于时间戳的增量传输示例


以下是有关如何使用状态管理脚本进行基于增量令牌的增量传输的示例：

```
from sap_odata_state_management import StateManagerFactory, StateManagerType, StateType

# Initialize the state manager
state_manager = StateManagerFactory.create_manager(
    manager_type=StateManagerType.JOB_TAG,
    state_type=StateType.DELTA_TOKEN,
    options={
        "job_name": args['JOB_NAME'],
        "logger": logger
    }
)

# Get connector options (including delta token if available)
key = "SAPODataNode"
connector_options = state_manager.get_connector_options(key)

# Use the connector options in your Glue job
df = glueContext.create_dynamic_frame.from_options(
    connection_type="SAPOData",
    connection_options={
        "connectionName": "connectionName",
        "ENTITY_NAME": "entityName",
        "ENABLE_CDC": "true",
        **connector_options
    }
)

# Process your data here...

# Update the state after processing
state_manager.update_state(key, sapodata_df.toDF())
```

在这两个示例中，状态管理脚本处理在两次作业运行之间存储状态（增量令牌或时间戳）的复杂性。它会在获取连接器选项时自动检索上次已知状态，并在处理后更新状态，从而确保每次运行的作业仅处理新的或更改的数据。