For AI agents: the complete documentation index is available at https://docs.dataplatform.ovh.net/ja/llms.txt, the full documentation bundle is available at https://docs.dataplatform.ovh.net/ja/llms-full.txt, and this page is available as Markdown at https://docs.dataplatform.ovh.net/ja/tutorials-python-sdk-transform.md.
  • 🇯🇵 日本語
  • Python SDK を使用してソースからデータを変換する

    よくあるユースケースの詳細なガイドとサンプルスクリプトを用意しました。これにより、迅速かつ効率的に始めることができます

    目的

    よくあるユースケースの詳細なガイドとサンプルスクリプトを用意しました。これにより、迅速かつ効率的に始めることができます。これらの例では、カスタムアクションをさまざまなシナリオで活用する方法を示しています。これにより、データプラットフォームのさまざまなコンポーネント間でデータを抽出、変換、読み込み(ETL)することができます。

    1. Lakehouse Manager テーブルを使用したカスタムアクション

    概要:

    この短い例では、Lakehouse Manager のテーブルからデータを抽出し、変換してから Lakehouse Manager に挿入または更新する方法を示します。

    このコードは Custom Action コンテキストで記述されており、Getting Started チュートリアルの stations_rides テーブルを使用しています。このチュートリアルを実施した場合は、以下のコードをコピーして貼り付けてテストできます。それ以外の場合は、テーブルとデータソースに合わせてコードを適応させる必要があります。

    例アプリケーション:

    Warning

    Lakehouse Manager で使用するテーブルを構築し、DPE Load Action で読み込むことを忘れないでください。以下のコードを使用する前にテーブルを読み込む必要があります。それ以外の場合は動作しません。

    import sys
    import pandas as pd
    import logging
    
    from forepaas.dwh import connect
    from forepaas.dwh import bulk_insert
    
    logger = logging.getLogger(__name__)
    def customfunc(event):
        try:
            logger.notice("Begin function")
    
            # make connection to the default dataset
            cn = connect("dwh/default_dataset/")
    
            # option 1 : extract data from the table with no SQL required
            df = cn.select("stations_rides")
    
            # option 2 : extract data with custom SQL
            df = cn.query("SELECT station_id, date, rides, station_name FROM stations_rides")
    
            # perform your custom transform in the dataframe
            df.loc[df["station_name"] == 'Harlem-Lake', "rides"] = 0
    
            # reinsert your dataframe in the destination table
            stats = bulk_insert(cn, "stations_rides", df) 
    
            # show insertion statistics (if DBMS compatible) 
            logger.info(stats)
    
            # delete rows where station name is "Davis"
            cn.delete("stations_rides", {"station_name":"Davis"})
    
            # update rows set rides to 0 where station_id=40040
            cn.update("stations_rides", {"rides":0}, {"station_id":40040})
    
            # when finished, disconnect cn
            del cn    
            logger.notice("END function")
        except Exception as err: 
            raise Exception("err:{} L:{}".format(err,sys.exc_info()[2].tb_lineno))

    2. Data Platform バケットを使用したカスタムアクション

    概要:

    時には、Load Action の機能を超えた複雑なファイル形式を処理する必要があります。 このような場合、Data Platform Buckets をプロジェクトで保存して操作することをお勧めします。

    Info

    現在の Data Platform SDK では、Datastore コネクタが Data Platform Buckets とのやり取りに使用されます。Datastore を単純にバケットコンテナと考えることができます。

    例アプリケーション:

    import sys
    import pandas as pd
    from logging import getLogger
    
    from forepaas.dwh import connect
    from forepaas.dwh import bulk_insert
    
    logger = getLogger(__name__)
    def extract_func(event):
        try:
            # we get data from a bucket and we will archive them in another bucket
            bucket_source_name = "your_source_bucket_name_here"
            bucket_archives_name = "your_source_bucket_name_here"
    
            # create a connector to handle bucket   
            bucket_connector = connect("data_store/{}".format(bucket_source_name))
    
            # list files from bucket
            files = bucket_connector.list()
    
            # retrieve a file from Data Store bucket to temporary local folder
            bucket_filepath = "stations_rides.csv"
            local_filepath = "/tmp/stations_rides.csv"
            bucket_connector.fget(bucket_filepath, local_filepath)
    
            # read then transform the file as you need
            # here the date column format is simply adjusted for compatibility reasons 
            df = pd.read_csv(local_filepath, sep=';')
            df['date'] = pd.to_datetime(df['date'])
    
            # load the dataframe into a project table named 'raw_file'
            cn = connect("dwh/default_dataset/")
            bulk_insert(cn, "stations_rides_artur", df)
            del cn
            
            # option 1 : copy the file into the archives bucket
            bucket_archive_filepath = "archives/stations_rides.csv"
            bucket_connector.fcopy_to(bucket_archives_name, bucket_archive_filepath, bucket_filepath)
           
            # option 2 : put a file into the archives
            bucket_archives = connect("data_store/{}".format(bucket_archives_name))
            bucket_archives.fput(bucket_archive_filepath, local_filepath)
            del bucket_archives
    
            # delete file from source bucket
            bucket_connector.delete(bucket_filepath)
    
            # disconnect from datastore
            del bucket_connector
        except Exception as err: 
            raise Exception("err:{} L:{}".format(err,sys.exc_info()[2].tb_lineno))

    以下は、シンプルな URL から画像をバケットにアップロードする例コードです。

    from forepaas.dwh import connect
    
    data_store = connect('data_store')
    
    # Get bucket and upload image from URL to path uploads/test.jpg.
    # And finally get the image from the bucket
    bucket_test = data_store.get_bucket('test')
    
    lists = bucket_test.list(recursive=True)
    
    bucket_test.put_request("https://i.stack.imgur.com/r8jTK.jpg", path='uploads/test.jpg')
    data = bucket.get('hello/test.jpg')
    
    # Create a bucket if it does not already exists
    if data_store.bucket_exists('test-exists') is False:
        data_store.create_bucket('test-exists')
    
    # Connect directly to the bucket test and remove the file
    bucket_test2 = connect('data_store/test')
    bucket_test2.delete('hello/test.jpg')
    Tip

    これは、S31 互換ソースとして Connectors で定義した任意の Object Store でも動作します。

    3. Connectors ソースを使用したカスタムアクション

    概要:

    この例では、Connectors ソース から直接ファイルを取得し、処理して処理済みデータを Lakehouse Manager テーブル に入れる方法を示します。

    このコードは Custom Action コンテキストで記述されており、Getting Started Tutorialchicago_files ソースを使用しています。このチュートリアルを実施した場合は、以下のコードをコピーして貼り付けてテストできます。それ以外の場合は、テーブルとデータソースに合わせてコードを適応させる必要があります。

    Tip

    これは、FTPDropbox などの Source プロトコルでも動作します。

    例アプリケーション:

    import sys
    from forepaas.dwh.connect import connect
    from forepaas.dwh import bulk_insert
    import logging
    
    logger = logging.getLogger(__name__)
    
    def customfunc(event):
        try:
            # here we are connecting to a source named 'chicago_files'
            source_address = "dwh/chicago_files_artur/"
    
            # specify unsupported filename from list of files in source
            filename_w_extension = "stations_rides.csv"
    
            # connecto to file toget the address 
            source_file_connector = connect(source_address + filename_w_extension) 
    
            # connect to file directly
            file_address = source_file_connector.get()
            file_connector = connect(file_address) 
    
            # Extract and treat the file so it is usable
            df = file_connector.extract(return_type='dataframe') 
    
            # Treat the data
            # - - - - 
    
            # connect to the Lakehouse Manager
            dm_connector = connect("dwh/default_dataset/")
    
            # insert into an existing destination table
            stats = bulk_insert(dm_connector, "chicago_calendar_full", df) 
    
            logger.info(stats)
    
            # disconnect from datastore and remote source
            del source_connector
            del dm_connector
    
        except Exception as err:
                raise Exception(f"err:{err} L:{sys.exc_info()[2].tb_lineno}")

    さらに深く掘り下げる

    当社のソリューションを実装するためのトレーニングや技術サポートが必要な場合は、営業担当者にお問い合わせください、またはこのリンクをクリックして見積もりを受け取り、当社のプロフェッショナルサービスの専門家にプロジェクトのカスタム分析を依頼してください。

    Data Platform を構築するチームと直接質問をし、フィードバックを共有し、交流するには、専用の Discord チャネル にアクセスしてください。

    OVHcloud サービスについてサポートが必要な場合は、ヘルプセンター でリクエストを作成してください。

    ユーザーコミュニティ に参加してください。

    1: S3 は Amazon Technologies, Inc. の商標です。OVHcloud のサービスは、Amazon Technologies, Inc. によってスポンサーされ、承認され、またはその他の方法で提携しているものではありません。