ステップ 4: 台帳のテーブルにクエリを実行する - Amazon Quantum Ledger Database (Amazon QLDB)

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

ステップ 4: 台帳のテーブルにクエリを実行する

Amazon QLDB 台帳にテーブルを作成し、データをロードした後は、クエリを実行して、挿入した車両登録データを確認できます。QLDB は PartiQL をクエリ言語として使用し、Amazon Ion をドキュメント指向のデータモデルとして使用します。

PartiQL は、Ion で動作するように拡張されたオープンソースの SQL 互換のクエリ言語です。PartiQL を使用すると、使い慣れた SQL 演算子を使用してデータを挿入、クエリ、および管理できます。Amazon Ion は JSON のスーパーセットです。Ion はオープンソースのドキュメントベースのデータ形式であり、構造化データ、半構造化データ、およびネストされたデータを柔軟に保存および処理できます。

このステップでは、SELECT ステートメントを使用して、vehicle-registration 台帳のテーブルからデータを読み取ります。

警告

インデックス付きルックアップなしで QLDB でクエリを実行すると、完全なテーブルスキャンが呼び出されます。PartiQL は SQL 互換であるため、このようなクエリをサポートしています。ただし、QLDB の本番環境のユースケースではテーブルスキャンを実行しないでください。テーブルスキャンより、同時実行の競合やトランザクションのタイムアウトなど、大きなテーブルでパフォーマンスの問題が発生する可能性があります。

テーブルスキャンを回避するには、インデックス付きフィールドまたはドキュメント ID で等価演算子を使用する WHERE 述語句でステートメントを実行する必要があります (例: WHERE indexedField = 123 または WHERE indexedField IN (456, 789))。詳細については、「クエリパフォーマンスの最適化」を参照してください。

テーブルのクエリを実行するには
  1. 次のプログラム (find_vehicles.py) を使用して台帳の人物に登録されているすべての車両をクエリします。

    3.x
    # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 # # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitation the rights to use, copy, modify, # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # This code expects that you have AWS credentials setup per: # https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html from logging import basicConfig, getLogger, INFO from pyqldbsamples.model.sample_data import get_document_ids, print_result, SampleData from pyqldbsamples.constants import Constants from pyqldbsamples.connect_to_ledger import create_qldb_driver logger = getLogger(__name__) basicConfig(level=INFO) def find_vehicles_for_owner(driver, gov_id): """ Find vehicles registered under a driver using their government ID. :type driver: :py:class:`pyqldb.driver.qldb_driver.QldbDriver` :param driver: An instance of the QldbDriver class. :type gov_id: str :param gov_id: The owner's government ID. """ document_ids = driver.execute_lambda(lambda executor: get_document_ids(executor, Constants.PERSON_TABLE_NAME, 'GovId', gov_id)) query = "SELECT Vehicle FROM Vehicle INNER JOIN VehicleRegistration AS r " \ "ON Vehicle.VIN = r.VIN WHERE r.Owners.PrimaryOwner.PersonId = ?" for ids in document_ids: cursor = driver.execute_lambda(lambda executor: executor.execute_statement(query, ids)) logger.info('List of Vehicles for owner with GovId: {}...'.format(gov_id)) print_result(cursor) def main(ledger_name=Constants.LEDGER_NAME): """ Find all vehicles registered under a person. """ try: with create_qldb_driver(ledger_name) as driver: # Find all vehicles registered under a person. gov_id = SampleData.PERSON[0]['GovId'] find_vehicles_for_owner(driver, gov_id) except Exception as e: logger.exception('Error getting vehicles for owner.') raise e if __name__ == '__main__': main()
    2.x
    # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 # # Permission is hereby granted, free of charge, to any person obtaining a copy of this # software and associated documentation files (the "Software"), to deal in the Software # without restriction, including without limitation the rights to use, copy, modify, # merge, publish, distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, # INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A # PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE # SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # # This code expects that you have AWS credentials setup per: # https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html from logging import basicConfig, getLogger, INFO from pyqldbsamples.model.sample_data import get_document_ids, print_result, SampleData from pyqldbsamples.constants import Constants from pyqldbsamples.connect_to_ledger import create_qldb_session logger = getLogger(__name__) basicConfig(level=INFO) def find_vehicles_for_owner(transaction_executor, gov_id): """ Find vehicles registered under a driver using their government ID. :type transaction_executor: :py:class:`pyqldb.execution.executor.Executor` :param transaction_executor: An Executor object allowing for execution of statements within a transaction. :type gov_id: str :param gov_id: The owner's government ID. """ document_ids = get_document_ids(transaction_executor, Constants.PERSON_TABLE_NAME, 'GovId', gov_id) query = "SELECT Vehicle FROM Vehicle INNER JOIN VehicleRegistration AS r " \ "ON Vehicle.VIN = r.VIN WHERE r.Owners.PrimaryOwner.PersonId = ?" for ids in document_ids: cursor = transaction_executor.execute_statement(query, ids) logger.info('List of Vehicles for owner with GovId: {}...'.format(gov_id)) print_result(cursor) if __name__ == '__main__': """ Find all vehicles registered under a person. """ try: with create_qldb_session() as session: # Find all vehicles registered under a person. gov_id = SampleData.PERSON[0]['GovId'] session.execute_lambda(lambda executor: find_vehicles_for_owner(executor, gov_id), lambda retry_attempt: logger.info('Retrying due to OCC conflict...')) except Exception: logger.exception('Error getting vehicles for owner.')
    注記

    まず、このプログラムでは、GovId LEWISR261LL を使用してドキュメントの Person テーブルに対してクエリを実行し、id メタデータフィールドを取得します。

    次に、このドキュメント id を外部キーとして使用して、PrimaryOwner.PersonId によって VehicleRegistration テーブルをクエリします。また、VehicleRegistrationVIN フィールドの Vehicle テーブルと結合されます。

  2. このプログラムを実行するには、次のコマンドを入力します。

    python find_vehicles.py

vehicle-registration 台帳のテーブルのドキュメントの変更方法については、「ステップ 5: 台帳内のドキュメントを変更する」を参照してください。