Help Center/ AI DataLake/ Getting Started/ Data Processing Using PySpark
Updated on 2026-11-06 GMT+08:00

Data Processing Using PySpark

Scenarios

AI DataLake is a fully managed lakehouse analytics service from Huawei Cloud. It provides end-to-end data management and analytics, supporting multi-engine job development to meet diverse big data needs.

This section demonstrates how to analyze data using AI DataLake by creating a Spark endpoint and submitting a job via an API.

Procedure

Before using the following sample, complete necessary operations. For details, see Preparations.

  1. Planning and Creating an OBS Parallel File System: Create an OBS parallel file system to store job scripts.
  2. Creating a Workspace: Create a workspace and associate it with a LakeFormation instance.
  3. Creating a SparkJob Endpoint for Running Jobs: Create a SparkJob endpoint to run jobs.
  4. Submitting a Job via an API: Use an API to encapsulate REST requests and submit AI DataLake jobs to the SparkJob endpoint for execution.

Preparations

  • You have registered an account and completed real-name authentication. The account balance is sufficient, and the account is not frozen.
  • You have enabled AI DataLake and obtained the required permissions for the cloud resources.
  • You have enabled LakeFormation and created an instance.
  • You have obtained OBS permissions and configured the required agency.
  • You have obtained an IAM token. For details, see Obtaining an IAM User Token.

Step 1: Plan and Create an OBS Parallel File System

AI DataLake Spark uses OBS to submit jobs and store data. You must create a bucket and a folder on the OBS console, and then import sample data or job scripts.

  1. Log in to the Huawei Cloud OBS console.
  2. Choose Buckets and click Create Bucket. On the page that appears, configure the parameters and click Create Now.
    • Bucket Name: Enter a name for the bucket as required.
    • Configure other parameters based on your business requirements.
  3. In the bucket list, click the name of the new bucket.
  4. On the Objects tab, click Upload Object to upload the job script to the created OBS parallel file system.

    For example, upload the Spark RDD data conversion script simple-rdd-job.py. Its content is shown below:

    from __future__ import print_function
    from pyspark.sql import SparkSession
    if __name__ == "__main__":
        spark = SparkSession
            .builder
            .appName("SimpleSpark")
            .getOrCreate()
        # Basic RDD operations
        rdd = spark.sparkContext.parallelize([1, 2, 3, 4, 5], 3)
        data = rdd.map(lambda x: x + 2).collect()
        print("Result:", data)
        spark.stop()

Step 2: Create a Workspace

  1. Log in to the AI DataLake console.
  2. In the left navigation pane, click the workspace area.
  3. Select Create Workspace from the drop-down list.
  4. On the Create Workspace page, set the following workspace parameters.
    Table 1 Basic workspace information

    Category

    Parameter

    Mandatory

    Description

    Basic Information

    Workspace Name

    Yes

    The name of the workspace to create. Workspace names must be unique within the same account.

    • The name can contain only letters, digits, hyphens (-), and underscores (_).
    • The name must be 4 to 32 characters long.

    The workspace name is case-insensitive. Uppercase letters are automatically converted to lowercase.

    Description

    No

    A brief description of the workspace. It cannot exceed 255 characters.

    Enterprise Project

    No

    If the workspace you are creating belongs to an enterprise project, select that enterprise project.

    EPS provides enterprise projects that group cloud resources by project to manage resources and users within specific projects.

    For details about how to configure enterprise projects, see Enterprise Management User Guide.

    NOTE:

    This parameter appears only for users with the EPS service enabled.

    Multimodal Data Management

    LakeFormation Instance

    Yes

    Select the LakeFormation instance associated with the current workspace. Each workspace must be associated with one LakeFormation instance. You cannot change this instance after the workspace is created.

    • Select a LakeFormation instance to centrally manage metadata and control data access.
    • If no instance is available, first create a LakeFormation instance.
  5. Verify that all configurations are correct.

    Click Create Now to create the workspace.

    After the workspace is created, you can view it in the workspace management list.

Step 3: Create a SparkJob Endpoint for Running Jobs

  1. On the AI DataLake console, use the drop-down list in the upper-left corner to switch to the workspace created in Step 2: Create a Workspace.
  2. In the left navigation pane, choose Engine Endpoints > Spark. The Spark engine endpoint list appears.
  3. Click Create Endpoint in the upper right corner of the page and configure the parameters as prompted.
    1. Configure the basic information for the endpoint.
      Table 2 Basic endpoint information

      Parameter

      Example Value

      Description

      Endpoint Type

      SparkJob

      Select an endpoint type.

      • SparkSQL: This endpoint type is designed for data querying and analysis using Spark SQL. Data analysts can write SQL statements to rapidly filter, aggregate, and compute datasets, enabling them to explore data efficiently.
      • SparkJob: This endpoint type is designed for Spark jobs that perform complex data processing tasks, such as large-scale data transformation, machine learning model training, and ETL (extract, transform, load) workflows.

      Endpoint Name

      spark-job-01

      The endpoint name is a unique identifier within the system and is used in API calls and CLI commands.

      NOTE:

      The endpoint name cannot be changed after the endpoint is created.

      Naming rules:

      • The name can contain only lowercase letters, digits, and hyphens (-), and must start with a letter and end with a letter or digit.
      • The name can contain a maximum of 63 characters.

      Endpoint Display Name

      Dedicated Spark job endpoint for data analysis team-01

      The endpoint display name can be changed after the endpoint is created.

      The endpoint display name appears on the console to help users identify the endpoint.

      Naming rules:

      • The name can contain only letters, digits, and hyphens (-).
      • The name can contain a maximum of 63 characters.

      Add Description

      Dedicated to the data analysis team

      Enter a description to specify the purpose and background of the endpoint, helping other users understand its application scenarios.

    2. Configure the resource settings for the endpoint.
      Table 3 Endpoint resource settings

      Parameter

      Example Value

      Description

      Resource Allocation

      On-demand

      Currently, Spark endpoints support only the on-demand resource allocation mode.

      In the on-demand resource allocation mode, elastic resources are used. You do not need to purchase resources in advance. Instead, you pay only for what you use. If no workloads are running, you incur no fees.

      This mode is well-suited for short-term or ad-hoc tasks, including development, testing, and temporary projects.

      Maximum Resource Quota

      216

      When selecting the on-demand resource allocation mode, you must configure the maximum resource quota. This sets an upper limit on elastic resource consumption, preventing uncontrolled resource expansion due to sudden traffic surges and avoiding the exhaustion of cluster compute capacity.

      Additionally, the system uses this maximum vCPU configuration to efficiently schedule and allocate resources.

    3. Configure the scheduling settings for the endpoint.
      Table 4 Scheduling settings

      Parameter

      Example Value

      Description

      Job Concurrency per Endpoint

      5

      Configure the maximum number of jobs that can run concurrently on an endpoint. This limit prevents node overload and maintains stable response times when multiple users access the endpoint at the same time.

      Job Scheduling Policy

      Random

      • Random: Jobs are selected at random for processing. During each scheduling cycle, a job is selected at random for execution.
      • First-in, first-out (FIFO): Jobs are queued and processed in the order of their arrival. The first job to arrive is processed first, followed sequentially by subsequent jobs.
    4. Configure Spark parameters.

      Specify Spark job submission properties in a key=value format.

      • Key: Enter the configuration parameter required by the Spark job, such as spark.executor.memory.
      • Value: Enter the value for the corresponding key, such as 4294967296. The default unit for memory is bytes.
    5. Configure the storage settings for the endpoint.
      Table 5 Storage settings

      Parameter

      Example Value

      Description

      OBS Parallel File System

      aidatalake-obs

      Select an existing OBS parallel file system from the drop-down list to store job logs and temporary data.

      The OBS parallel file system cannot be changed after the endpoint is created. If no file system is available, click Create OBS parallel file system to create one.

      Agency

      aidatalake-agency-log

      Configure an agency (such as an IAM agency) with read and write permissions for event logs, error logs, and temporary data.

      Select an existing agency from the drop-down list. The agency cannot be changed after the endpoint is created. If no agency is available, click Create agency to create one. For details, see Creating a Custom Agency.

    6. Configure the job agency settings for the endpoint.

      Parameter

      Example Value

      Description

      Agency

      aidatalake-agency-job

      Agency-assigned endpoint permissions are automatically converted to credentials and updated in the Spark cluster at runtime. You can use agency credentials in the Spark cluster to access the required services. For details, see Creating a Custom Agency.

  4. After completing the configuration, click Create Now. The system will begin creating the endpoint.

    Once the endpoint is created, you can view its details in the endpoint list. After the status changes to Running, you can submit jobs to the endpoint.

Step 4: Submit a Job via an API

Run the request.py script to submit an AI DataLake Spark job to the specified SparkJob endpoint. This example uses the requests library to demonstrate how to create and submit a Spark job. The following is an example request script:

# -*- coding: utf-8 -*-
import requests
import urllib3
# Suppress SSL warnings.
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# ==================== Configuration area ====================
# Replace these sample values with your actual values.
TOKEN = "XXX"  # IAM token
WORKSPACE_ID = "3fa4b5a6-9208-4254-b823-119aa29c4016"  # Workspace ID
X_CLIENT_TOKEN = "68d2002f-866c-4c4d-84d2-747137b12e9d" # Service transaction ID used to trace requests. You can customize this ID. If you resubmit a job, you must enter a new ID.
# Request header
HEADERS = {
    "X-Client-Token": X_CLIENT_TOKEN,
    "X-auth-token": TOKEN,
    "Content-Type": "application/json"
}
ENDPOINT = "fabric.cn-southwest-2.myhuaweicloud.com" # Replace this with the endpoint for your region. In this example, the endpoint for the Guiyang 1 region is used.

# API URL
URL_SUBMIT = f"{ENDPOINT}/v2/workspaces/{WORKSPACE_ID}/spark-jobs"

# Job configuration
JOB_CONFIG = {
    "execution_mode": "batch",
    "name": "sparkpython_airan", # Job name
    "endpoint_name": "spark-job-01", # SparkJob endpoint name
    "catalog_name": "spark_catalog",  # Catalog name
    "description": "spark_test", # Job description
    "job_agency": "aidatalake-agency-job",  # Job agency name
    "spark_version": "4.0.0",  # Spark version
    "job_config": {
        "job_type": "spark_python_job",
        "spark_py_parameter": {
            "main_python_file": "obs://bucket/dir1/",  # OBS path for storing the job script
            "main_args": []
        }
    },
    "resource_config": {
        "executor_number": 3,
        "driver_resource_spec": {
            "cpu": 2000,
            "memory": 4096,
            "disk": 10
        },
        "executor_resource_spec": {
            "cpu": 2000,
            "memory": 4096,
            "disk": 10
        }
    },
    "spark_config": {
        "spark.executor.memoryOverhead": "1g",
        "spark.driver.memoryOverhead": "512m",
        "spark.dynamicAllocation.enabled": "true",
        "spark.dynamicAllocation.maxExecutors": "3",
        "spark.shuffle.service.enabled": "false",
        "spark.dynamicAllocation.shuffleTracking.enabled": "true",
        "spark.default.parallelism": "4000",
        "spark.hadoop.fs.obs.security.provider": "com.huawei.spark.provider.JobAgencyCredentialProvider"
    },
    "restore_strategy": {
        "max_retry": 0,
        "retry_delay": 30,
        "launching_timeout": 10800,
        "running_timeout": -1
    },
    "labels": [
        {
            "key": "environment0",
            "value": "dev0"
        }
    ]
}
def submit_spark_job(config=None):
    """Submit a Spark job."""
    payload = config or JOB_CONFIG
    try:
        response = requests.post(
            URL_SUBMIT, headers=HEADERS, json=payload, verify=False
        )
        if response.status_code in [200, 201, 202]:
            result = response.json()
            job_id = result.get("job_id", "unknown")
            print(f"Job submitted successfully.")
            print(f"Job ID: {job_id}")
            print(f"Response: {response.text}")
            return job_id
        else:
            print(f"Failed to submit the job. (Code: {response.status_code})")
            print(response.text)
            return None
    except Exception as e:
        print(f"Request failed: {e}")
        return None


if __name__ == "__main__":
    submit_spark_job()