<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Akihiro Okuno on Medium]]></title>
        <description><![CDATA[Stories by Akihiro Okuno on Medium]]></description>
        <link>https://medium.com/@choplin?source=rss-1d4c8d1b8d59------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*__rHQcmT-ZIC1Txj.jpg</url>
            <title>Stories by Akihiro Okuno on Medium</title>
            <link>https://medium.com/@choplin?source=rss-1d4c8d1b8d59------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 04:50:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@choplin/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ScalarDB Analytics with Sparkをリリースしました]]></title>
            <link>https://medium.com/scalar-engineering-ja/scalardb-analytics-with-spark%E3%82%92%E3%83%AA%E3%83%AA%E3%83%BC%E3%82%B9%E3%81%97%E3%81%BE%E3%81%97%E3%81%9F-86206a46232f?source=rss-1d4c8d1b8d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/86206a46232f</guid>
            <category><![CDATA[product]]></category>
            <category><![CDATA[scalar]]></category>
            <category><![CDATA[spark-sql]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[scalardb]]></category>
            <dc:creator><![CDATA[Akihiro Okuno]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 07:49:45 GMT</pubDate>
            <atom:updated>2024-06-11T07:49:45.436Z</atom:updated>
            <content:encoded><![CDATA[<p>ScalarDB 3.12において、ScalarDBを用いて管理しているデータベース上でApache Sparkを用いた分析的クエリの実行を可能とするScalarDB Analytics with Sparkを新たにリリースしました。本記事ではScalarDB Analytics with Sparkの概要や利用方法などについて説明します。</p><h3>ScalarDB Analytics with Sparkとは？</h3><p>ScalarDBは汎用的なトランザクションマネージャであり、RDBMSやNoSQL等を含む様々なデータベースの上で、複数のデータベースをまたいだトランザクション処理を実行することを可能とします。ScalarDBは多数のシンプルなトランザクションを処理するようなワークロードを主な対象としており、SQLを用いた処理はサポートしているものの、可能な操作としてはキーに基づいたCRUDや一部のScanのみに限られています。</p><p>ScalarDB Analyticsは、ScalarDB管理下にあるデータベースに対して結合や集計を含む広範なクエリの実行をサポートし、アドホック分析などの高度な処理を行うことを可能にするものです。ScalarDB Analyticsシリーズとして、昨年<a href="https://medium.com/scalar-engineering-ja/scalardb-analytics-with-postgresql%E3%82%92%E3%83%AA%E3%83%AA%E3%83%BC%E3%82%B9%E3%81%97%E3%81%BE%E3%81%97%E3%81%9F-6bc56c139f82">ScalarDB Analytics with PostgreSQLをリリース</a>しており、PostgreSQLにおいて外部データの読み込みを可能とする外部データラッパの機能を利用して、PostgreSQL上においてScalarDB管理下にあるデータベースに対してクエリを実行することができるようになりました。今回リリースしたScalarDB Analytics with Sparkは、新たなScalarDB Analyticsシリーズの一つであり、Apache SparkからScalarDB管理下のデータベースに対してクエリを実行することができます。Apache Sparkは分析的な処理を主な対象とする分散処理エンジンであり、<a href="https://spark.apache.org/docs/latest/sql-ref.html">様々な分析的クエリの実行をサポート</a>しています。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VmZlCsjC4YFJWSGuajMNRg.png" /><figcaption>ScalarDB Analytics with Sparkの概要</figcaption></figure><p>ScalarDB Analyticsシリーズの位置付けとしては、ScalarDB Analytics with PostgreSQLがOSSとして提供されており自由に利用できるのに対して、ScalarDB Analytics with Sparkはエンタープライズ版の製品であり、利用するためには有償ライセンスが必要となります。Sparkは複数のノードを用いた分散処理が可能であるため、PostgreSQLと比較して、よりスケーラブルに分析的クエリの実行が可能となることが期待されます。</p><h3>ScalarDB Analytics with Sparkの仕組み</h3><p>ScalarDB Analytics with SparkはApache Sparkのプラグインとして実装されています。ScalarDB Analytics with Sparkは、名前空間やテーブルなどのメタデータを扱うCatalogプラグインと、外部のデータソースからScalarDBライブラリを経由してデータを読み取るConnectorプラグインから、主に構成されています。</p><p>Catalogプラグインは、ScalarDBの設定ファイルに記載されているデータベースの接続情報などを用い、ScalarDB内にどのようなデータ（名前空間、テーブル、列）が含まれているかを取得して、Sparkのカタログ情報として提供します。Sparkはテーブル情報を管理するためのデフォルトのカタログ実装を内部に持っていますが、ユーザ側で別のカタログ実装を指定することが可能になっています。ScalarDB Analytics with Sparkが提供するカタログ実装を指定することにより、Spark上でScalarDBのカタログを用いることが可能になります。具体的な設定方法については、次の節で説明します。</p><p>Catalogプラグインには複数の実装方法がありますが、ScalarDB Analytics with Sparkのように外部に存在するカタログ情報を丸ごと利用するような用途には、<a href="https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/connector/catalog/CatalogPlugin.html"><em>CatalogPlugin</em></a>インターフェースを実装することによって一から独自のカタログを実装することが可能となっており、ScalarDB Analytics with Sparkではこの方法によって、ScalarDBのカタログ情報をSparkのカタログとして扱うことを可能にするCatalogプラグインを実装しています。</p><p>Catalogプラグインは、カタログ情報を提供するだけではなく、ユーザがクエリを指定した際に、適切なConnectorプラグインを起動して読み取り処理を開始することも役割の一つです。多くのCatalogプラグイン実装では、対象とする外部データソースが一種類であるため、常に単一のConnectorプラグインを用いるようになっていますが、上の図にあるようにScalarDBは多くの種類のデータベースをサポートしているため、それぞれのデータベースに対応したConnectorプラグインを用いる必要があります。ただし、全てのデータベースに対して個別のConnectorプラグインを用意することは手間がかかるため、いくつかの個別のConnectorプラグインに加えて、ScalarDB Analytics with Sparkで独自に提供しているScalarDB Connectorプラグインとを併用する形になっています。</p><p>ScalarDB Connectorプラグインは、内部でScalarDBライブラリを用いて外部のデータベースからデータを読み取る実装になっています。ScalarDBは分析的クエリに用いられる大量のデータのスキャンや複雑な絞り込みなどを得意としていないため、利用が可能な場合には個別のConnectorを用いた方が効率的な実行が可能になると考えられます。そのため、独自Connectorプラグインを利用可能なデータベースの場合にはそのConnectorプラグインを用い、それ以外の場合にはScalarDB Connectorプラグインを用いることによって、ScalarDBがサポートしている全てのデータベースからの読み取りを可能とする仕組みになっています。現在のバージョン3.12.0では、JDBCデータベースの場合にはSparkが同梱するJDBC Connectorを利用し、それ以外の場合にはScalarDB Connectorを利用するようになっています。</p><p>Connectorプラグインは歴史的な経緯から複数の実装方法があるようですが、ScalarDB Connectorプラグインでは<a href="https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/connector/catalog/Table.html"><em>Table</em></a>インタフェースを実装する方法を用いています。</p><p>これまでに説明したCatalogプラグインとConnectorプラグインを用いることで、Spark上でScalarDB管理化のテーブルのデータを読み取ることが可能になりますが、このテーブルの生データにはScalarDBがトランザクション処理を行うためのメタデータが含まれています。また、これらのトランザクションメタデータを考慮せずにデータを読んでしまうことになるため、トランザクションによる一貫性の保証を得ることができません。例えば、別の実行中のトランザクションで書き込みをしようとしている未コミットのデータを読んでしまう可能性があります。そのため、ScalarDB Analytics with Sparkでは生データに含まれているトランザクションメタデータを解釈しつつ、ユーザのデータのみをテーブルのデータとして表示するための、WAL-Interpreted Viewを作成します。WAL-Interpreted Viewによって、ユーザはScalarDB上のテーブルと同等のテーブルがSpark上に存在するかのようにデータにアクセスすることができるようになります。また、WAL-Interpreted Viewを通したデータのアクセスは、トランザクションメタデータを解釈しているため、一定の一貫性（正確にはRead Committed）が保証されています。ユーザは、Catalogプラグインが提供する生のテーブルではなく、こちらのWAL-Interpreted Viewを通してデータにアクセスします。</p><h3>ScalarDB Analytics with Sparkを用いたクエリの実行</h3><p>ScalarDB Analytics with Sparkを用いるためには、まずCatalogプラグインを有効化する必要があります。対象とするSparkの設定（`spark.conf`）に以下の設定を追加します。</p><pre>spark.sql.catalog.scalardb_catalog = com.scalar.db.analytics.spark.datasource.ScalarDbCatalog       (1)<br>spark.sql.catalog.scalardb_catalog.config = /&lt;PATH_TO_YOUR_SCALARDB_PROPERTIES&gt;/config.properties   (2)<br>spark.sql.catalog.scalardb_catalog.namespaces = &lt;YOUR_NAMESPACE_NAME_2&gt;,&lt;YOUR_NAMESPACE_NAME_2&gt;     (3)<br>spark.sql.catalog.scalardb_catalog.license.key = {&quot;your&quot;:&quot;license&quot;, &quot;key&quot;:&quot;in&quot;, &quot;json&quot;:&quot;format&quot;}    (4)<br>spark.sql.catalog.scalardb_catalog.license.cert_path = /&lt;PATH_TO_YOUR_LICENSE&gt;/cert.pem             (5)</pre><p>(1)では、Catalogプラグインの実装クラスを指定します。常に<em>ScalarDbCatalog</em>のクラスを指定します。また、キーの最右端部の<em>scalardb_catalo</em>gはSpark上でのカタログ名を指定する文字列であり、ユニークな値であれば任意の文字列を指定できます。この記事では<em>scalardb_catalo</em>gを用います。</p><p>(2)では、ScalarDB Analytics with Sparkでデータを読み込みたいScalarDBの設定ファイルのパスを指定します。</p><p>(3)では、ScalarDB Analytics with Sparkでデータを読み込む対象とするScalarDB内の名前空間を列挙します。複数の名前空間を指定する場合にはカンマで区切ります。</p><p>(4)(5)では、それぞれライセンスのキー（JSON）と証明書を指定します。ScalarDB Analytics with Sparkでは、クエリの実行時にこれらのライセンス情報の正当性をチェックしており、チェックに失敗した場合にはクエリの実行も失敗するようになっています。</p><p>以上が正しく設定された状態でSparkを起動すると、指定したカタログ名でScalarDBのテーブルを表示できるようになります。例として、<a href="https://scalardb.scalar-labs.com/docs/latest/scalardb-samples/scalardb-analytics-spark-sample/">ScalarDB Analytics with Sparkのサンプルアプリケーション</a>のScalarDBを用い、Spark Shellを実行すると、以下のようカタログ内の情報を表示することができます。</p><pre>scala&gt; sql(&quot;SHOW NAMESPACES in scalardb_catalog&quot;).show() // (1)<br>+-----------+<br>|  namespace|<br>+-----------+<br>|   dynamons|<br>| postgresns|<br>|cassandrans|<br>+-----------+<br><br><br>scala&gt; sql(&quot;SHOW TABLES in scalardb_catalog.postgresns&quot;).show() // (2)<br>+----------+---------+-----------+<br>| namespace|tableName|isTemporary|<br>+----------+---------+-----------+<br>|postgresns|   orders|      false|<br>+----------+---------+-----------+<br><br><br>scala&gt; sql(&quot;DESCRIBE scalardb_catalog.postgresns.orders&quot;).show() // (3)<br>+--------------------+---------+-------+<br>|            col_name|data_type|comment|<br>+--------------------+---------+-------+<br>|          o_orderkey|      int|   NULL|<br>|           o_custkey|      int|   NULL|<br>|       o_orderstatus|   string|   NULL|<br>|        o_totalprice|   double|   NULL|<br>|         o_orderdate|   string|   NULL|<br>|     o_orderpriority|   string|   NULL|<br>|             o_clerk|   string|   NULL|<br>|      o_shippriority|      int|   NULL|<br>|           o_comment|   string|   NULL|<br>|               tx_id|   string|   NULL|<br>|            tx_state|      int|   NULL|<br>|          tx_version|      int|   NULL|<br>|      tx_prepared_at|   bigint|   NULL|<br>|     tx_committed_at|   bigint|   NULL|<br>|        before_tx_id|   string|   NULL|<br>|     before_tx_state|      int|   NULL|<br>|   before_tx_version|      int|   NULL|<br>|before_tx_prepare...|   bigint|   NULL|<br>|before_tx_committ...|   bigint|   NULL|<br>|before_o_orderstatus|   string|   NULL|<br>+--------------------+---------+-------+<br>only showing top 20 rows</pre><p>(1)ではScalarDB内の名前空間の一覧を、(2)では<em>postgresns</em>という名前空間内のテーブルの一覧を、(3)では<em>postgresns.orders</em>というテーブルの詳細情報を表示しています。</p><p>表示されたテーブル情報から分かるように、ユーザが定義した列に加えて、トランザクションメタデータが含まれています。このままでは使いづらいので、上述したようにこれら生のテーブルに対してWAL-Interpreted Viewを作成します。ScalarDB Analytics with SparkではWAL-Interpreted Viewを作成するためのヘルパークラスを提供しており、以下のコードを実行することによって、カタログ内に存在する全てのテーブルに対して一括してWAL-Interpreted Viewを作成することができます。</p><pre>scala&gt; import com.scalar.db.analytics.spark.view.SchemaImporter<br>scala&gt; new SchemaImporter(spark, &quot;scalardb_catalog&quot;).run()</pre><p><em>new SchemaImporter</em>の第一引数には<em>SparkSession</em>のインスタンスを、第二引数には設定で指定したカタログ名を渡します。このインスタンスの<em>run()</em>を呼ぶことによって、WAL-Interpreted Viewを作成することができます。WAL-Interpreted ViewはSparkの現在のカタログ上に作成されます。通常はSparkのデフォルトカタログになります。</p><pre>scala&gt; sql(&quot;SHOW NAMESPACES&quot;).show() // (1)<br>+-----------+<br>|  namespace|<br>+-----------+<br>|cassandrans|<br>|    default|<br>|   dynamons|<br>| postgresns|<br>+-----------+<br><br><br>scala&gt; sql(&quot;SHOW TABLES in postgresns&quot;).show() // (2)<br>+----------+---------+-----------+<br>| namespace|tableName|isTemporary|<br>+----------+---------+-----------+<br>|postgresns|   orders|      false|<br>+----------+---------+-----------+<br><br><br>scala&gt; sql(&quot;DESCRIBE postgresns.orders&quot;).show() // (3)<br>+---------------+---------+-------+<br>|       col_name|data_type|comment|<br>+---------------+---------+-------+<br>|     o_orderkey|      int|   NULL|<br>|      o_custkey|      int|   NULL|<br>|  o_orderstatus|   string|   NULL|<br>|   o_totalprice|   double|   NULL|<br>|    o_orderdate|   string|   NULL|<br>|o_orderpriority|   string|   NULL|<br>|        o_clerk|   string|   NULL|<br>| o_shippriority|      int|   NULL|<br>|      o_comment|   string|   NULL|<br>+---------------+---------+-------+</pre><p>(1)、(2)では現在のカタログ上に、<em>scalardb_catalog</em>のものと同じ名前の名前空間とテーブル（正確にはビュー）が作成されていることが分かります。（3）で表示したビューの詳細情報を見ると、トランザクションメタデータは含まれておらず、ユーザが定義した列のみが含まれています。このビューを通してデータにアクセスすることによって、ScalarDBと同等の構造のテーブルに対して、Sparkがサポートしている任意のクエリを実行することが可能になります。例えば、以下のように複数のテーブルの結合や、複雑な絞り込み、集約が含まれているクエリの実行が可能です。</p><pre>scala&gt; sql(&quot;&quot;&quot;<br>     |      SELECT<br>     |        l_orderkey,<br>     |        sum(l_extendedprice * (1 - l_discount)) AS revenue,<br>     |        o_orderdate,<br>     |        o_shippriority<br>     |      FROM<br>     |        dynamons.customer,<br>     |        postgresns.orders,<br>     |        cassandrans.lineitem<br>     |      WHERE<br>     |        c_mktsegment = &#39;AUTOMOBILE&#39;<br>     |        AND c_custkey = o_custkey<br>     |        AND l_orderkey = o_orderkey<br>     |        AND o_orderdate &lt; &#39;1995-03-15&#39;<br>     |        AND l_shipdate &gt; &#39;1995-03-15&#39;<br>     |      GROUP BY<br>     |        l_orderkey,<br>     |        o_orderdate,<br>     |        o_shippriority<br>     |      ORDER BY<br>     |        revenue DESC,<br>     |        o_orderdate,<br>     |        l_orderkey<br>     |      LIMIT 10;<br>     |      &quot;&quot;&quot;).show()<br>+----------+------------------+-----------+--------------+<br>|l_orderkey|           revenue|o_orderdate|o_shippriority|<br>+----------+------------------+-----------+--------------+<br>|   1071617|128186.99915996166| 1995-03-10|             0|<br>|   1959075| 33104.51278645416| 1994-12-23|             0|<br>|    430243|19476.115819260962| 1994-12-24|             0|<br>+----------+------------------+-----------+--------------+</pre><h3>まとめ</h3><p>本記事では、ScalarDB Analytics with Sparkの紹介とその簡単な仕組みを紹介しました。より詳細な情報は<a href="https://scalardb.scalar-labs.com/docs/latest/scalardb-analytics-spark/">ドキュメント</a>をご参照下さい。Scalarでは、データの管理をより信頼できるというミッションのもと、データ管理に対するより広範なニーズに応えていくために、Scalar製品の可能性を拡げていきます。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86206a46232f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scalar-engineering-ja/scalardb-analytics-with-spark%E3%82%92%E3%83%AA%E3%83%AA%E3%83%BC%E3%82%B9%E3%81%97%E3%81%BE%E3%81%97%E3%81%9F-86206a46232f">ScalarDB Analytics with Sparkをリリースしました</a> was originally published in <a href="https://medium.com/scalar-engineering-ja">Scalar Engineering (JA)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Announcing ScalarDB Analytics with Spark]]></title>
            <link>https://medium.com/scalar-engineering/announcing-scalardb-analytics-with-spark-bec969c9a099?source=rss-1d4c8d1b8d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/bec969c9a099</guid>
            <category><![CDATA[product]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[scalar]]></category>
            <category><![CDATA[scalardb]]></category>
            <category><![CDATA[spark-sql]]></category>
            <dc:creator><![CDATA[Akihiro Okuno]]></dc:creator>
            <pubDate>Tue, 11 Jun 2024 07:48:44 GMT</pubDate>
            <atom:updated>2024-06-11T07:48:44.512Z</atom:updated>
            <content:encoded><![CDATA[<p>In ScalarDB 3.12, we launched ScalarDB Analytics with Spark, a new feature enabling the execution of analytical queries by using Apache Spark on databases managed by ScalarDB. This article will provide an overview and usage guide for ScalarDB Analytics with Spark.</p><h3>What is ScalarDB Analytics with Spark?</h3><p>ScalarDB is a universal transaction manager that allows for cross-database transactions over various databases, including RDBMS and NoSQL. It primarily targets workloads involving numerous simple transactions, supporting operations limited to key-based CRUD and some scans.</p><p>ScalarDB Analytics enhances the query capabilities over databases managed by ScalarDB to include joins and aggregations, facilitating complex ad-hoc analyses. As part of the ScalarDB Analytics feature set, we released ScalarDB Analytics with PostgreSQL last year, which utilizes the foreign data wrapper feature to execute queries on ScalarDB-managed databases in PostgreSQL. The newly released ScalarDB Analytics with Spark enables querying ScalarDB-managed databases from Apache Spark, a distributed processing engine designed for analytical workloads.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VmZlCsjC4YFJWSGuajMNRg.png" /><figcaption>Overview of ScalarDB Analytics with Spark</figcaption></figure><p>While ScalarDB Analytics with PostgreSQL is available as open-source software (OSS), ScalarDB Analytics with Spark is an enterprise version of the product, which requires a paid license. Given Spark’s ability to handle distributed processing across multiple nodes, it is expected to perform analytical queries more scalably compared to PostgreSQL.</p><h3>How ScalarDB Analytics with Spark works</h3><p>ScalarDB Analytics with Spark is implemented as a plugin for Apache Spark. ScalarDB Analytics with Spark consists mainly of the catalog plugin, which handles ScalarDB metadata, such as namespaces and tables, and the connector plugin, which reads data from external data sources via the ScalarDB library.</p><p>The catalog plugin uses database connection information in the ScalarDB configuration file to retrieve the data (namespaces, tables, and columns) contained in ScalarDB and provide this as a catalog in Spark. By specifying the catalog implementation provided by ScalarDB Analytics with Spark, it is possible to use ScalarDB’s catalog in Spark. The specific configuration is described in the next section.</p><h4>Catalog implementation</h4><p>There are several ways to implement catalogs. For applications such as ScalarDB Analytics with Spark, where the entire catalog information exists externally, it is possible to implement your own catalog by implementing the <a href="https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/connector/catalog/CatalogPlugin.html"><em>CatalogPlugin</em></a> interface. ScalarDB Analytics with Spark uses this method to implement a catalog plugin that turns ScalarDB catalog information into a Spark catalog.</p><p>The catalog plugin is not only responsible for providing catalog information but also for invoking the appropriate connector plugin to initiate the read process when a user runs a query. Most catalog plugin implementations only use a single connector plugin for a single external data source. On the other hand, as shown in the figure above, ScalarDB supports many types of databases, so it is necessary to choose a connector plugin for each database. Since preparing separate connector plugins for every database supported by ScalarDB is time consuming, ScalarDB Analytics with Spark provides its own ScalarDB connector plugin in addition to several database-specific connector plugins.</p><p>The ScalarDB connector plugin is implemented internally by using the ScalarDB library to read data from external databases. Because ScalarDB is more suited for scanning smaller amounts of data or performing simple analytical queries, it is considered more efficient to use the separate connector plugin when possible. For this reason, the database-specific plugins are used when available, and the ScalarDB connector plugin is used in other cases to support all ScalarDB-supported databases for ScalarDB Analytics with Spark. As of ScalarDB 3.12, ScalarDB Analytics with Spark uses only the JDBC connector, included with Spark, as the database specific connector.</p><p>There are several ways to implement Connector plugin due to the historical reason. The ScalarDB Connector plugin uses the <a href="https://spark.apache.org/docs/latest/api/java/org/apache/spark/sql/connector/catalog/Table.html"><em>Table</em></a> interface to implement.</p><p>The catalog and connector plugins described so far allow Spark to read data from ScalarDB-managed databases. However, the raw data from these databases contain transaction metadata columns that ScalarDB needs to process transactions. Also, since the data would be read without considering this transactional metadata, it is not possible to guarantee transactional consistency. For example, Spark could read uncommitted data that is about to be written by another running transaction. Therefore, based on the raw tables, ScalarDB Analytics with Spark creates WAL-Interpreted Views that interprets the transaction metadata contained in the raw data but displays only the user data as data in the table. The WAL-Interpreted Views allow the user to see the equivalent table in Spark as it exists in ScalarDB.</p><p>In addition, accessing data through WAL-Interpreted Views guarantees a certain degree of consistency (Read Committed) by interpreting transactional metadata. So, users generally access data through the WAL-Interpreted Views here rather than the raw tables provided by the catalog plugin.</p><h3>Running a query by using ScalarDB Analytics with Spark</h3><p>To use ScalarDB Analytics with Spark, you must first activate the catalog plugin. Add the following settings to your Spark configuration (spark.conf):</p><pre>spark.sql.catalog.scalardb_catalog = com.scalar.db.analytics.spark.datasource.ScalarDbCatalog       (1)<br>spark.sql.catalog.scalardb_catalog.config = /&lt;PATH_TO_YOUR_SCALARDB_PROPERTIES&gt;/config.properties   (2)<br>spark.sql.catalog.scalardb_catalog.namespaces = &lt;YOUR_NAMESPACE_NAME_2&gt;,&lt;YOUR_NAMESPACE_NAME_2&gt;     (3)<br>spark.sql.catalog.scalardb_catalog.license.key = {&quot;your&quot;:&quot;license&quot;, &quot;key&quot;:&quot;in&quot;, &quot;json&quot;:&quot;format&quot;}    (4)<br>spark.sql.catalog.scalardb_catalog.license.cert_path = /&lt;PATH_TO_YOUR_LICENSE&gt;/cert.pem             (5)</pre><p>In (1), you specify the implementation class of the catalog plugin. You always need to specify the sample value, <em>ScalarDbCatalog</em>. The rightmost part of the key, <em>scalardb_catalog</em>, is an arbitrary string that specifies the name of the catalog on Spark. In this article, <em>scalardb_catalog</em> is used.</p><p>In (2), you specify the path to the ScalarDB configuration file from which you want to load data in ScalarDB Analytics with Spark.</p><p>In (3), you list the namespaces in ScalarDB into which you want to read data in ScalarDB Analytics with Spark. When specifying multiple namespaces, you can separate them with commas.</p><p>In (4) and (5), you specify the license key (JSON) and the certificate, respectively. ScalarDB Analytics with Spark checks the validity of this license information when executing a query, and if the check fails, the query execution will also fail.</p><p>When you launch Spark with the above correctly configured, you will be able to view ScalarDB tables with the specified catalog name. As an example, when using the ScalarDB Analytics with Spark sample application and executing the Spark Shell, the catalog information will be displayed as follows:</p><pre>scala&gt; sql(&quot;SHOW NAMESPACES in scalardb_catalog&quot;).show() // (1)<br>+-----------+<br>|  namespace|<br>+-----------+<br>|   dynamons|<br>| postgresns|<br>|cassandrans|<br>+-----------+<br><br><br>scala&gt; sql(&quot;SHOW TABLES in scalardb_catalog.postgresns&quot;).show() // (2)<br>+----------+---------+-----------+<br>| namespace|tableName|isTemporary|<br>+----------+---------+-----------+<br>|postgresns|   orders|      false|<br>+----------+---------+-----------+<br><br><br>scala&gt; sql(&quot;DESCRIBE scalardb_catalog.postgresns.orders&quot;).show() // (3)<br>+--------------------+---------+-------+<br>|            col_name|data_type|comment|<br>+--------------------+---------+-------+<br>|          o_orderkey|      int|   NULL|<br>|           o_custkey|      int|   NULL|<br>|       o_orderstatus|   string|   NULL|<br>|        o_totalprice|   double|   NULL|<br>|         o_orderdate|   string|   NULL|<br>|     o_orderpriority|   string|   NULL|<br>|             o_clerk|   string|   NULL|<br>|      o_shippriority|      int|   NULL|<br>|           o_comment|   string|   NULL|<br>|               tx_id|   string|   NULL|<br>|            tx_state|      int|   NULL|<br>|          tx_version|      int|   NULL|<br>|      tx_prepared_at|   bigint|   NULL|<br>|     tx_committed_at|   bigint|   NULL|<br>|        before_tx_id|   string|   NULL|<br>|     before_tx_state|      int|   NULL|<br>|   before_tx_version|      int|   NULL|<br>|before_tx_prepare...|   bigint|   NULL|<br>|before_tx_committ...|   bigint|   NULL|<br>|before_o_orderstatus|   string|   NULL|<br>+--------------------+---------+-------+<br>only showing top 20 rows</pre><p>(1) shows the list of namespaces in ScalarDB, (2) shows the list of tables in the namespace named `postgresns`, and (3) shows detailed information about the table, `postgresns.orders`.</p><p>As you can see from the table information, it contains transaction metadata columns in addition to user-defined columns. Since it is difficult to use as it is, we will create WAL-Interpreted Views for these raw tables. ScalarDB Analytics with Spark provides a helper class to create WAL-Interpreted Views. By executing the following code, you can create WAL-Interpreted Views for all tables in the catalog at once:</p><pre>scala&gt; import com.scalar.db.analytics.spark.view.SchemaImporter<br>scala&gt; new SchemaImporter(spark, &quot;scalardb_catalog&quot;).run()</pre><p>The first argument of <em>new SchemaImporter</em> is an instance of <em>SparkSession</em> and the second argument is the catalog name specified in the configuration. By calling <em>run()</em> on this instance, WAL-Interpreted Views will be created on Spark’s current catalog. Normally, the current catalog is Spark’s default catalog. You can see the details of the created WAL-Interpreted Views as follows:</p><pre>scala&gt; sql(&quot;SHOW NAMESPACES&quot;).show() // (1)<br>+-----------+<br>|  namespace|<br>+-----------+<br>|cassandrans|<br>|    default|<br>|   dynamons|<br>| postgresns|<br>+-----------+<br><br><br>scala&gt; sql(&quot;SHOW TABLES in postgresns&quot;).show() // (2)<br>+----------+---------+-----------+<br>| namespace|tableName|isTemporary|<br>+----------+---------+-----------+<br>|postgresns|   orders|      false|<br>+----------+---------+-----------+<br><br><br>scala&gt; sql(&quot;DESCRIBE postgresns.orders&quot;).show() // (3)<br>+---------------+---------+-------+<br>|       col_name|data_type|comment|<br>+---------------+---------+-------+<br>|     o_orderkey|      int|   NULL|<br>|      o_custkey|      int|   NULL|<br>|  o_orderstatus|   string|   NULL|<br>|   o_totalprice|   double|   NULL|<br>|    o_orderdate|   string|   NULL|<br>|o_orderpriority|   string|   NULL|<br>|        o_clerk|   string|   NULL|<br>| o_shippriority|      int|   NULL|<br>|      o_comment|   string|   NULL|<br>+---------------+---------+-------+</pre><p>In (1) and (2) we see that namespaces and tables (more precisely, views) with the same name as the those in <em>scalardb_catalog</em> have been created in the current catalog. The detailed information of the view displayed in (3) shows that it does not contain transactional metadata, only user-defined columns. By accessing the data through this view, it is possible to execute an arbitrary query supported by Spark on tables with the same schema as ScalarDB.</p><p>For example, it is possible to execute a query that contains multiple table joins, complex selections, and aggregations, as shown below:</p><pre>scala&gt; sql(&quot;&quot;&quot;<br>     |      SELECT<br>     |        l_orderkey,<br>     |        sum(l_extendedprice * (1 - l_discount)) AS revenue,<br>     |        o_orderdate,<br>     |        o_shippriority<br>     |      FROM<br>     |        dynamons.customer,<br>     |        postgresns.orders,<br>     |        cassandrans.lineitem<br>     |      WHERE<br>     |        c_mktsegment = &#39;AUTOMOBILE&#39;<br>     |        AND c_custkey = o_custkey<br>     |        AND l_orderkey = o_orderkey<br>     |        AND o_orderdate &lt; &#39;1995-03-15&#39;<br>     |        AND l_shipdate &gt; &#39;1995-03-15&#39;<br>     |      GROUP BY<br>     |        l_orderkey,<br>     |        o_orderdate,<br>     |        o_shippriority<br>     |      ORDER BY<br>     |        revenue DESC,<br>     |        o_orderdate,<br>     |        l_orderkey<br>     |      LIMIT 10;<br>     |      &quot;&quot;&quot;).show()<br>+----------+------------------+-----------+--------------+<br>|l_orderkey|           revenue|o_orderdate|o_shippriority|<br>+----------+------------------+-----------+--------------+<br>|   1071617|128186.99915996166| 1995-03-10|             0|<br>|   1959075| 33104.51278645416| 1994-12-23|             0|<br>|    430243|19476.115819260962| 1994-12-24|             0|<br>+----------+------------------+-----------+--------------</pre><h3>Wrap-up</h3><p>This article introduces the newly released ScalarDB Analytics with Spark. For more details, please refer to the <a href="https://scalardb.scalar-labs.com/docs/latest/scalardb-analytics-spark/">documentation</a>. We’ll continue to expand the possibilities of Scalar products to meet a wider range of data management needs, in line with our mission, “Making Data Management More Reliable.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bec969c9a099" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scalar-engineering/announcing-scalardb-analytics-with-spark-bec969c9a099">Announcing ScalarDB Analytics with Spark</a> was originally published in <a href="https://medium.com/scalar-engineering">Scalar Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Announcing ScalarDB Analytics with PostgreSQL]]></title>
            <link>https://medium.com/scalar-engineering/announcing-scalardb-analytics-with-postgresql-2d96d6f749b0?source=rss-1d4c8d1b8d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d96d6f749b0</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[product]]></category>
            <category><![CDATA[analytics]]></category>
            <dc:creator><![CDATA[Akihiro Okuno]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 02:15:13 GMT</pubDate>
            <atom:updated>2023-08-17T03:51:52.000Z</atom:updated>
            <content:encoded><![CDATA[<p>With the recent release of ScalarDB 3.9, we introduced ScalarDB Analytics with PostgreSQL so that users can take advantage of unified analytical queries on databases that ScalarDB manages. This article will explain an overview of ScalarDB Analytics with PostgreSQL and how to use it.</p><h3>What is ScalarDB Analytics with PostgreSQL?</h3><p>ScalarDB is a general-purpose transaction manager that allows users to perform transaction processing across multiple databases, including RDBMS, NoSQL, etc. ScalarDB primarily manages workloads that process a large number of simple transactions; thus, it supports a limited class of operations, including key-based CRUD and a simple scan operation. Due to these limitations, if users want to perform advanced processing, such as ad-hoc analysis with the data that ScalarDB manages, users have to implement complex operations, including joins, aggregations, and other operations on the application side on their own.</p><p>We introduced ScalarDB Analytics with PostgreSQL to support various queries, including joins and aggregations, against ScalarDB-managed databases and enable users to run advanced processing, such as ad-hoc analysis. ScalarDB Analytics with PostgreSQL, as the name suggests, uses PostgreSQL to execute queries with the data that ScalarDB manages, enabling users to perform various queries that PostgreSQL supports. ScalarDB Analytics with PostgreSQL reads data directly from the database that ScalarDB manages to enable users to read data that ScalarDB has written directly without ETL processing. A foreign data wrapper (FDW), which is a PostgreSQL extension framework for handling external data, is used for this read operation.</p><p>The relationship between ScalarDB and ScalarDB Analytics with PostgreSQL is illustrated below. Users can read and write data as usual through ScalarDB, but if they want to perform advanced queries, they can query by using ScalarDB Analytics with PostgreSQL. PostgreSQL reads data directly from ScalarDB-managed databases via FDWs, so ScalarDB Analytics with PostgreSQL can read data directly written to ScalarDB without additional operations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*9JV6HcAInRIy4ScOYTkdfA.png" /></figure><p>ScalarDB Analytics with PostgreSQL has several limitations. First, ScalarDB Analytics with PostgreSQL supports only read operations. PostgreSQL itself supports write operations, of course, but it cannot write to a database under ScalarDB management through an FDW. Therefore, attempts to execute commands, such as INSERT, will cause an error. Second, the isolation level guaranteed for reading through ScalarDB Analytics with PostgreSQL is Read Committed, while reading and writing from ScalarDB guarantees the strongest isolation level, Strict Serializable. Under the Read Committed isolation, the rows retrieved on a read are guaranteed to have been committed in the previous transactions, but the results may contain read skew and other anomalies.</p><h3>How does ScalarDB Analytics with PostgreSQL work?</h3><p>The architecture of ScalarDB Analytics with PostgreSQL is as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*mbOeDOjvgnlzkHgpDpi0tQ.png" /></figure><p>The boxes on the bottom are the databases that ScalarDB manages. To read the data written to these databases from PostgreSQL, ScalarDB Analytics with PostgreSQL uses FDWs. The PostgreSQL community develops and maintains many FDW implementations, such as jdbc_fdw and cassandra_fdw. ScalarDB Analytics with PostgreSQL uses such community-maintained FDWs internally. However, ScalarDB also supports databases that the existing FDWs don’t cover, such as DynamoDB. We developed our own FDW, scalardb_fdw, to read data from these databases. scalardb_fdw uses the Java Native Interface to directly utilize ScalarDB as a library inside the FDW and read data from external databases via scan operations for ScalarDB.</p><p>Since scalardb_fdw reads data by using ScalarDB, it can inherently support all databases that ScalarDB supports. For databases that the existing FDWs support, there are choices for the FDW to read data from, including existing FDWs and scalardb_fdw. With ScalarDB Analytics with PostgreSQL, users can use Schema Importer (described below) to determine which FDW to use and configure the settings automatically. Because of this, users don’t need to consider which FDW to use. Schema Importer chooses the existing FDWs preferentially if available; otherwise, scalardb_fdw is used as a fallback. This is because the existing FDWs developed for a particular database often support complex scans and thus provide better performance for complex queries.</p><p>In PostgreSQL, users define a foreign table to treat external data as data in a PostgreSQL table. ScalarDB Analytics with PostgreSQL creates one foreign table for each table defined in ScalarDB. These ScalarDB tables contain write-ahead logging (WAL) metadata columns that ScalarDB uses internally and columns that the user defines for the table. ScalarDB Analytics also uses these WAL metadata columns with PostgreSQL to create a WAL-interpreted view.</p><p>ScalarDB Analytics with PostgreSQL also creates a WAL-interpreted view for each external table. The WAL-interpreted view is responsible for:</p><ul><li>Interpreting the WAL metadata in the ScalarDB table to show only valid rows under the Read Committed isolation level to the user.</li><li>Providing the same schema as the table on the ScalarDB side without the WAL metadata.</li></ul><p>Because of that, users can consider the WAL-interpreted view as tables equivalent to those in ScalarDB.</p><p>Schema Importer is a CLI tool for automatically configuring the above database objects. The tool reads the ScalarDB configuration file, retrieves the schemas of the tables defined in ScalarDB, and creates the corresponding FDW external tables and WAL-interpreted views in that order.</p><h3>Example of ScalarDB Analytics with PostgreSQL</h3><p>The following example describes what kind of WAL-interpreted view Schema Importer actually creates.</p><p>Suppose the tables <em>dynamons.customer</em>, <em>postgresns.order</em>, and <em>cassandrans.lineitem</em> are created in ScalarDB as follows. Each table is configured to be stored in ScalarDB in DynamoDB, PostgreSQL, and Cassandra.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*kOmwUZgVAvqSHFo8gX4taQ.png" /></figure><p>If you run Schema Importer for those tables, it will create an external table and view for each of the three tables. For instance, for the `dynamons.customer` table, an external table named `dynamons._customer` and a view named `dynamons.customer` will be created.</p><pre>                            Foreign table &quot;dynamons._customer&quot;<br>         Column         |       Type       | Collation | Nullable | Default | FDW options<br>------------------------+------------------+-----------+----------+---------+-------------<br> c_custkey              | integer          |           |          |         |<br> c_name                 | text             |           |          |         |<br> c_address              | text             |           |          |         |<br> c_nationkey            | integer          |           |          |         |<br> c_phone                | text             |           |          |         |<br> c_acctbal              | double precision |           |          |         |<br> c_mktsegment           | text             |           |          |         |<br> c_comment              | text             |           |          |         |<br> tx_id                  | text             |           |          |         |<br> tx_version             | integer          |           |          |         |<br> tx_state               | integer          |           |          |         |<br> tx_prepared_at         | bigint           |           |          |         |<br> tx_committed_at        | bigint           |           |          |         |<br> before_tx_id           | text             |           |          |         |<br> before_tx_version      | integer          |           |          |         |<br> before_tx_state        | integer          |           |          |         |<br> before_tx_prepared_at  | bigint           |           |          |         |<br> before_tx_committed_at | bigint           |           |          |         |<br> before_c_name          | text             |           |          |         |<br> before_c_address       | text             |           |          |         |<br> before_c_nationkey     | integer          |           |          |         |<br> before_c_phone         | text             |           |          |         |<br> before_c_acctbal       | double precision |           |          |         |<br> before_c_mktsegment    | text             |           |          |         |<br> before_c_comment       | text             |           |          |         |<br>Server: multi_storage_dynamodb<br>FDW options: (namespace &#39;dynamons&#39;, table_name &#39;customer&#39;)</pre><pre><br>                     View &quot;dynamons.customer&quot;<br>    Column    |       Type       | Collation | Nullable | Default<br>--------------+------------------+-----------+----------+---------<br> c_custkey    | integer          |           |          |<br> c_name       | text             |           |          |<br> c_address    | text             |           |          |<br> c_nationkey  | integer          |           |          |<br> c_phone      | text             |           |          |<br> c_acctbal    | double precision |           |          |<br> c_mktsegment | text             |           |          |<br> c_comment    | text             |           |          |</pre><p>The <em>dynamons.customer</em> view has the same schema as the original table in ScalarDB. Users can query this view as if it were a table in ScalarDB. Since PostgreSQL supports a variety of analytical queries, users can run, for example, the following queries:</p><pre>&gt; SELECT<br>        l_returnflag,<br>        l_linestatus,<br>        sum(l_quantity) AS sum_qty,<br>        sum(l_extendedprice) AS sum_base_price,<br>        sum(l_extendedprice * (1 - l_discount)) AS sum_disc_price,<br>        sum(l_extendedprice * (1 - l_discount) * (1 + l_tax)) AS sum_charge,<br>        avg(l_quantity) AS avg_qty,<br>        avg(l_extendedprice) AS avg_price,<br>        avg(l_discount) AS avg_disc,<br>        count(*) AS count_order<br>FROM<br>        cassandrans.lineitem<br>WHERE<br>        to_date(l_shipdate, &#39;YYYY-MM-DD&#39;) &lt;= date &#39;1998-12-01&#39; - 3<br>GROUP BY<br>        l_returnflag,<br>        l_linestatus<br>ORDER BY<br>        l_returnflag,<br>        l_linestatus;<br><br> l_returnflag | l_linestatus | sum_qty |   sum_base_price   |   sum_disc_price   |     sum_charge     |       avg_qty       |     avg_price      |      avg_disc       | count_order<br>--------------+--------------+---------+--------------------+--------------------+--------------------+---------------------+--------------------+---------------------+-------------<br> A            | F            |    1519 | 2374824.6560430005 | 1387363.5818635763 | 1962762.9341866106 | 26.6491228070175439 | 41663.590456894744 |  0.4150182982456142 |          57<br> N            | F            |      98 | 146371.22954200002 |  85593.92837883368 | 121041.52567369482 | 32.6666666666666667 | 48790.409847333336 |  0.4098473333333333 |           3<br> N            | O            |    5374 |  8007373.247144971 |  4685645.630765834 |  6624209.157932242 | 24.4272727272727273 |  36397.15112338623 |   0.414759749999999 |         220<br> R            | F            |    1461 |  2190869.967642001 | 1284177.8484816086 | 1814150.7929095028 | 25.1896551724137931 |  37773.62013175864 | 0.41323520689655185 |          58<br>(4 rows)</pre><h3>Wrap-up</h3><p>This article introduced ScalarDB Analytics with PostgreSQL and how it works. To further enhance the value of data that ScalarDB manages, Scalar plans to enable data analysis with PostgreSQL and in various other environments in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d96d6f749b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scalar-engineering/announcing-scalardb-analytics-with-postgresql-2d96d6f749b0">Announcing ScalarDB Analytics with PostgreSQL</a> was originally published in <a href="https://medium.com/scalar-engineering">Scalar Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ScalarDB Analytics with PostgreSQLをリリースしました]]></title>
            <link>https://medium.com/scalar-engineering-ja/scalardb-analytics-with-postgresql%E3%82%92%E3%83%AA%E3%83%AA%E3%83%BC%E3%82%B9%E3%81%97%E3%81%BE%E3%81%97%E3%81%9F-6bc56c139f82?source=rss-1d4c8d1b8d59------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bc56c139f82</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[product]]></category>
            <dc:creator><![CDATA[Akihiro Okuno]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 02:09:08 GMT</pubDate>
            <atom:updated>2023-08-17T03:52:29.042Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://prtimes.jp/main/html/rd/p/000000037.000037795.html">先日リリースされたScalarDB 3.9</a>において、ScalarDBが管理するデータベース上で統一的に分析クエリを実現するScalarDB Analytics with PostgreSQLが新たに導入されました。本記事ではScalarDB Analytics with PostgreSQLの概要や利用方法などについて解説します。</p><h3>ScalarDB Analytics with PostgreSQLとは？</h3><p>ScalarDBは汎用的なトランザクションマネージャであり、RDBMSやNoSQL等を含む様々なデータベースの上で、複数のデータベースをまたいだトランザクション処理を実行することを可能とします。ScalarDBは多数のシンプルなトランザクションを処理するようなワークロードを主な対象としており、サポートしている操作はキーに基づいたCRUDや一部のScanのみに限られています。ScalarDBがサポートしている操作の一覧については<a href="https://scalardb.scalar-labs.com/docs/latest/api-guide/">APIガイド</a>をご参照ください。これらの制限のため、従来のScalarDBでは、ScalarDBが管理しているデータを用いたアドホックな分析など、より高度な処理を行いたい場合には、ユーザがアプリケーション側で独自に結合や集合処理などの実装を行う必要がありました。</p><p>ScalarDB Analytics with PostgreSQLは、ScalarDB管理下にあるデータベースに対して結合や集計を含む広範なクエリの実行をサポートし、アドホック分析などの高度な処理を行うことを可能にするために導入されたものです。ScalarDB Analytics with PostgreSQLは、名前が示す通り、ScalarDBが管理しているデータに対して、PostgreSQLを用いてクエリの実行を行うものとなっており、ユーザはPostgreSQLがサポートしている多様なクエリ処理を実行することが可能となります。また、ScalarDB Analytics with PostgreSQLでは、ScalarDB側で書き込んだデータをETL処理などを行わずにそのまま読み込めるようにするために、PostgreSQLを通してScalarDBが管理しているデータベースからデータを直接読み取ようになっています。この読み取りには、PostgreSQL本体が提供するForeign Data Wrapper（FDW）と呼ばれる外部データを扱うためのフレームワークを利用しています。</p><p>ScalarDBとScalarDB Analytics with PostgreSQLの関係を図示すると次のようになります。ユーザはScalarDBを通してこれまで通りにデータを読み書きしながら、高度なクエリを実行したい場合には、ScalarDB Analytics with PostgreSQLにクエリを投げることができます。ScalarDB Analytics with PostgreSQLはFDWを通して、ScalarDB管理下のデータベースから直接データを読み取るため、ScalarDB側で書き込んだデータは、追加の操作が必要とせずに、そのままScalarDB Analytics with PostgreSQLでも読み取りが可能です。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*9JV6HcAInRIy4ScOYTkdfA.png" /><figcaption>ScalarDB Analytics with PostgreSQLの概要</figcaption></figure><p>ScalarDB Analytics with PostgreSQLにはいくつか制限があります。第一に、ScalarDB Analytics with PostgreSQLでは読み取り操作のみがサポートされています。PostgreSQL本体ではもちろん書き込み操作もサポートされていますが、FDWを通したScalarDB管理下のデータベースへの書き込みを行うことができないため、INSERTなどのコマンドを実行しようとするとエラーになります。第二に、ScalarDB Analytics with PostgreSQLを通した読み込みで保証される分離レベルはRead-Committedになります。ScalarDBからの読み書きでは最も強い分離レベルであるSerializableが保証されますが、ScalarDB Analytics with PostgreSQLから読み込んだデータはRead-Committed、すなわち読み取りで取得した行は、いずれかのトランザクションでコミットされたものであることは保証されますが、取得した結果にはRead-skewなどのanomalyが含まれている可能性があります。</p><h3>ScalarDB Analytics with PostgreSQLの仕組みは？</h3><p>ScalarDB Analytics with PostgreSQLのアーキテクチャは以下のようになっています。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*mbOeDOjvgnlzkHgpDpi0tQ.png" /><figcaption>ScalarDB Analytics with PostgreSQLのアーキテクチャ</figcaption></figure><p>一番下がScalarDBが管理しているデータベースです。これらに書き込まれたデータをPostgreSQLから読み込むために、ScalarDB Analytics with PostgreSQLではFDWを利用しています。多くのFDWの実装がコミュニティによって提供されており、ScalarDB Analytics with PostgreSQLの内部では<a href="https://github.com/pgspider/jdbc_fdw">jdbc_fdw</a>や<a href="https://github.com/jaiminpan/cassandra2_fdw">cassandra_fdw</a>などを利用しています。しかし、ScalarDBでは多数のデータベースをサポートしているため、DynamoDBなどの既存のFDWでは対応できないものが存在します。ScalarDB Analytics with PostgreSQLでは、これらのデータベースからの読み込みをサポートするために、scalardb_fdwを新たに開発し利用しています。scalardb_fdwではJava Native Interfaceを用いて、FDWの内部においてScalarDBをライブラリとして直接利用し、ScalarDBのScan操作によって外部データベースのデータを読み込みます。scalardb_fdwはScalarDBを直接利用してデータを読み込んでいるため、必然的にScalarDBがサポートしているデータベースの全てをサポートすることが可能です。既存のFDWが存在するデータベースについては、データを読み込むためのFDWについて、既存のFDWとscalardb_fdwを含む複数の選択肢が存在することになりますが、ScalarDB Analytics with PostgreSQLでは、後述するSchema Importerによって、どのFDWを利用するかを自動的に決定して設定を行うため、ユーザはどのFDWを利用するかを意識する必要はありません。</p><p>PostgreSQLでは外部テーブル（Foreign Table）を定義することによって、FDWを通して読み取ったデータをPostgreSQL上のテーブルのデータとして扱うことができるようになります。ScalarDB Analytics with PostgreSQLでは、ScalarDB上で定義されたテーブル一つごとに、一つの外部テーブルを作成します。これらの外部テーブルは、ユーザがテーブルに定義した列に加えて、ScalarDBが内部的に利用するWALメタデータの列も同時に含むようにします。これらのWALメタデータの列は、次に説明するWAL-Interpreted Viewにおいて利用されます。</p><p>WAL-Interpreted Viewは、PostgreSQLのビューとして定義され、一つの外部テーブルごとに、一つのWAL-Interpreted Viewが作成されます。WAL-Interpreted Viewは、1. 外部テーブルに存在するWALメタデータを解釈することにより、Read-Committed分離レベルにおいて有効なデータのみをユーザに見せる 2. WALメタデータを省いてScalarDB上のテーブルと同じスキーマを提供する、という役割を担っています。これらにより、ユーザはWAL-Interpreted ViewをScalarDB上のテーブルと同等のものと考えることができるようになります。</p><p>Schema Importerは上記のデータベースオブジェクトを自動的に設定するためのCLIツールです。Schema Impoterは指定されたScalarDBの設定ファイルを読み、ScalarDB上に定義されたテーブルのスキーマを取得して、それらに対応したFDW、外部テーブル、WAL-Interpreted Viewを順に作成します。これにより、ユーザは、ScalarDB上に定義されたテーブルが、あたかもPostgreSQL上にあるかのように操作することが可能になります。</p><h3>サンプルコード</h3><p>実際にSchema ImporterによってどのようなWAL-Interpreted Viewが得られるのかを、具体例を用いながら説明します。以下のように、ScalarDB上で`dynamons.customer`, `postgresns.order`, `cassandrans.lineitem`のテーブルが作成されているとします。それぞれのテーブルは、ScalarDBによってDynamoDB、PostgreSQL、Cassandraに保存されています。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*kOmwUZgVAvqSHFo8gX4taQ.png" /></figure><p>この時に、Schema Importerを実行すると、3つのテーブルそれぞれについて、外部テーブルとビューが作成されます。例えば、<em>dynamons.customer</em> テーブルに対して、<em>dynamons._customer</em>という外部テーブルと、<em>dynamons.customer</em>というビューが作成されます。</p><pre>                            Foreign table &quot;dynamons._customer&quot;<br>         Column         |       Type       | Collation | Nullable | Default | FDW options<br>------------------------+------------------+-----------+----------+---------+-------------<br> c_custkey              | integer          |           |          |         |<br> c_name                 | text             |           |          |         |<br> c_address              | text             |           |          |         |<br> c_nationkey            | integer          |           |          |         |<br> c_phone                | text             |           |          |         |<br> c_acctbal              | double precision |           |          |         |<br> c_mktsegment           | text             |           |          |         |<br> c_comment              | text             |           |          |         |<br> tx_id                  | text             |           |          |         |<br> tx_version             | integer          |           |          |         |<br> tx_state               | integer          |           |          |         |<br> tx_prepared_at         | bigint           |           |          |         |<br> tx_committed_at        | bigint           |           |          |         |<br> before_tx_id           | text             |           |          |         |<br> before_tx_version      | integer          |           |          |         |<br> before_tx_state        | integer          |           |          |         |<br> before_tx_prepared_at  | bigint           |           |          |         |<br> before_tx_committed_at | bigint           |           |          |         |<br> before_c_name          | text             |           |          |         |<br> before_c_address       | text             |           |          |         |<br> before_c_nationkey     | integer          |           |          |         |<br> before_c_phone         | text             |           |          |         |<br> before_c_acctbal       | double precision |           |          |         |<br> before_c_mktsegment    | text             |           |          |         |<br> before_c_comment       | text             |           |          |         |<br>Server: multi_storage_dynamodb<br>FDW options: (namespace &#39;dynamons&#39;, table_name &#39;customer&#39;)</pre><pre>                     View &quot;dynamons.customer&quot;<br>    Column    |       Type       | Collation | Nullable | Default<br>--------------+------------------+-----------+----------+---------<br> c_custkey    | integer          |           |          |<br> c_name       | text             |           |          |<br> c_address    | text             |           |          |<br> c_nationkey  | integer          |           |          |<br> c_phone      | text             |           |          |<br> c_acctbal    | double precision |           |          |<br> c_mktsegment | text             |           |          |<br> c_comment    | text             |           |          |</pre><p><em>dynamons.customer</em>ビューは、ScalarDB上の元のテーブルと同等のスキーマになっています。ユーザはこのビューに対して、あたかもScalarDB上のテーブルに対して行っているかのように、クエリを実行することが可能です。PostgreSQLでは様々な分析クエリがサポートされているため、例えば、次のようなクエリを実行することが可能です。</p><pre>&gt; SELECT<br>        l_returnflag,<br>        l_linestatus,<br>        sum(l_quantity) AS sum_qty,<br>        sum(l_extendedprice) AS sum_base_price,<br>        sum(l_extendedprice * (1 - l_discount)) AS sum_disc_price,<br>        sum(l_extendedprice * (1 - l_discount) * (1 + l_tax)) AS sum_charge,<br>        avg(l_quantity) AS avg_qty,<br>        avg(l_extendedprice) AS avg_price,<br>        avg(l_discount) AS avg_disc,<br>        count(*) AS count_order<br>FROM<br>        cassandrans.lineitem<br>WHERE<br>        to_date(l_shipdate, &#39;YYYY-MM-DD&#39;) &lt;= date &#39;1998-12-01&#39; - 3<br>GROUP BY<br>        l_returnflag,<br>        l_linestatus<br>ORDER BY<br>        l_returnflag,<br>        l_linestatus;<br><br> l_returnflag | l_linestatus | sum_qty |   sum_base_price   |   sum_disc_price   |     sum_charge     |       avg_qty       |     avg_price      |      avg_disc       | count_order<br>--------------+--------------+---------+--------------------+--------------------+--------------------+---------------------+--------------------+---------------------+-------------<br> A            | F            |    1519 | 2374824.6560430005 | 1387363.5818635763 | 1962762.9341866106 | 26.6491228070175439 | 41663.590456894744 |  0.4150182982456142 |          57<br> N            | F            |      98 | 146371.22954200002 |  85593.92837883368 | 121041.52567369482 | 32.6666666666666667 | 48790.409847333336 |  0.4098473333333333 |           3<br> N            | O            |    5374 |  8007373.247144971 |  4685645.630765834 |  6624209.157932242 | 24.4272727272727273 |  36397.15112338623 |   0.414759749999999 |         220<br> R            | F            |    1461 |  2190869.967642001 | 1284177.8484816086 | 1814150.7929095028 | 25.1896551724137931 |  37773.62013175864 | 0.41323520689655185 |          58<br>(4 rows)</pre><h3>まとめ</h3><p>本記事では、ScalarDB Analytics with PostgreSQLの紹介とその仕組みを紹介しました。より詳細な使い方は<a href="https://scalardb.scalar-labs.com/docs/latest/scalardb-analytics-postgresql/getting-started/">ドキュメント</a>をご参照下さい。Scalarでは、ScalarDBで管理されたデータの価値をさらに高めていくため、PostgreSQLに限らず、更に多様な環境でのデータ分析を可能にしていく予定です。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bc56c139f82" width="1" height="1" alt=""><hr><p><a href="https://medium.com/scalar-engineering-ja/scalardb-analytics-with-postgresql%E3%82%92%E3%83%AA%E3%83%AA%E3%83%BC%E3%82%B9%E3%81%97%E3%81%BE%E3%81%97%E3%81%9F-6bc56c139f82">ScalarDB Analytics with PostgreSQLをリリースしました</a> was originally published in <a href="https://medium.com/scalar-engineering-ja">Scalar Engineering (JA)</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>