<?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 Oleksandr Tarasenko on Medium]]></title>
        <description><![CDATA[Stories by Oleksandr Tarasenko on Medium]]></description>
        <link>https://medium.com/@cupreous.bowels?source=rss-fb3698313f6d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*cmvjtMz9Y-XX8clty2YHYg.jpeg</url>
            <title>Stories by Oleksandr Tarasenko on Medium</title>
            <link>https://medium.com/@cupreous.bowels?source=rss-fb3698313f6d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 15:32:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@cupreous.bowels/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[How to Regex in HBase Shell]]></title>
            <link>https://medium.com/@cupreous.bowels/how-to-regex-in-hbase-shell-4eb952ef7214?source=rss-fb3698313f6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4eb952ef7214</guid>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[hbase]]></category>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[regex]]></category>
            <dc:creator><![CDATA[Oleksandr Tarasenko]]></dc:creator>
            <pubDate>Sun, 09 Oct 2022 17:19:48 GMT</pubDate>
            <atom:updated>2022-10-09T17:19:48.796Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve been living in a NoSQL area for years you could stop noticing the differences between databases and their concepts. A couple weeks ago I was asked to help with querying by a regular expression in the HBase shell. Suddenly I realised that HBase might be the most difficult database to deal with on a command line level. It differs from other database clients significantly. This is why my colleague suggested sharing this technique in the hope to help other people who have to deal with HBase without any preparation or proper training.</p><p>The task is to obtain from the table all Formula 1 pilots whose last names start with “Ham”. To make the explanation clear and shorter I use a similar SQL request mapped to HBase’s syntax.</p><figure><img alt="Mapping SQL pattern matching to HBase command line’s equivalent" src="https://cdn-images-1.medium.com/max/1024/0*VQy55v6u7f7ZPmAG" /><figcaption>Mapping SQL pattern matching to HBase command line equivalent</figcaption></figure><p>Please, import all the following classes before you run the query. Just copy, paste in HBase shell and run.</p><pre>import org.apache.hadoop.hbase.filter.SingleColumnValueFilter<br>import org.apache.hadoop.hbase.filter.CompareFilter<br>import org.apache.hadoop.hbase.filter.BinaryComparator<br>import org.apache.hadoop.hbase.filter.RegexStringComparator</pre><p>Then edit your “scan” request and execute it.</p><pre>scan ‘f1Drivers’, {FILTER =&gt; SingleColumnValueFilter.new(Bytes.toBytes(‘name’), Bytes.toBytes(‘last_name’), CompareFilter::CompareOp.valueOf(‘EQUAL’), RegexStringComparator.new(“^HAM.*”)), LIMIT =&gt; 10}</pre><p>If you have questions regarding <a href="https://www.linkedin.com/feed/hashtag/bigdata">#bigdata</a> <a href="https://www.linkedin.com/feed/hashtag/hbase">#hbase</a> <a href="https://www.linkedin.com/feed/hashtag/datawrangling">#datawrangling</a> <a href="https://www.linkedin.com/feed/hashtag/datalake">#datalake</a> <a href="https://www.linkedin.com/feed/hashtag/dataengineering">#dataengineering</a> <a href="https://www.linkedin.com/feed/hashtag/datamodeling">#datamodeling</a> <a href="https://www.linkedin.com/feed/hashtag/spark">#spark</a> <a href="https://www.linkedin.com/feed/hashtag/nosql">#nosql</a> <a href="https://www.linkedin.com/feed/hashtag/java">#java</a> <a href="https://www.linkedin.com/feed/hashtag/scala">#scala</a> areas please let me know and I’ll try to create similar answer for you :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4eb952ef7214" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Syto — pure Scala library for filter design/implementation and digital signal processing]]></title>
            <link>https://medium.com/@cupreous.bowels/syto-pure-scala-library-for-filter-design-implementation-and-digital-signal-processing-1916626b9de4?source=rss-fb3698313f6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1916626b9de4</guid>
            <category><![CDATA[elliptic]]></category>
            <category><![CDATA[digital-filters]]></category>
            <category><![CDATA[dsp]]></category>
            <category><![CDATA[cheryshev]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Oleksandr Tarasenko]]></dc:creator>
            <pubDate>Tue, 10 Sep 2019 21:15:41 GMT</pubDate>
            <atom:updated>2019-09-11T09:55:59.826Z</atom:updated>
            <content:encoded><![CDATA[<h3>Syto — pure Scala library for filter design/implementation and digital signal processing</h3><p><em>One year ago I worked on a project that extensively used digital signal processing methods, especially data filtering. The prototype was implemented with Matlab that has a quite mature filtering toolbox but production technology stack consisted of Spark/Scala. At first glance the task seemed to be trivial — translate approved and validated signal processing logic from Matlab to Scala.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/288/1*sYmmZAhtWmVGle0AU_GzSQ.jpeg" /></figure><h4>How did I get the inspiration to create Syto?</h4><p>Having done a lot of investigations I discovered a lack of appropriate tools in Scala domain. But the solution was found — invoke an external Python workflow based on Scipy within from Spark job. It made me implement a bridge between Spark Scala logic and Python library, <a href="https://medium.com/@cupreous.bowels/spark-pipe-a-one-pipe-problem-ea1672ee254b">using pipe technology, which I mentioned in one of the previous posts</a>. Scipy is a great Python library that contains digital signal processing functionality as well as many other scientific features and the project’s needs were covered successfully with this integration. But it gave me some food for thoughts — why there was no Scala library that provided digital filter design/implementation? Wouldn’t it be nice to have JVM-based functionality to be used by Scala developers seamlessly? This is how I decided to dive into digital signal processing theory and create Syto.</p><pre><em>Syto (ˈsiːto) a Ukrainian word, meaning sieve — a mesh strainer, which can be considered as a trivial mechanical filter. I decided to borrow this word from my native language to express the main idea behind a toolbox being under development. This is pure Scala open-source library for digital signal processing (DSP in further), primarily oriented on filter design and implementation.</em></pre><p>I understood that I would not be able to implement all DSP functionality existing in Scipy by the first release. So, the idea was to focus on digital filters that are an essential part of DSP and IIR filter family was chosen as a candidate for the debut.</p><h4>When do you have to use Syto?</h4><p>The answer is simple: you have to filter some sequence using Scala. Usually, scientists prefer Python, Matlab or R to tackle their needs. But sometimes it happens the technology stack is based on Scala. The very first use case can Spark which is originally written in Scala. However, I tend to leave the integration of Spark and Syto out of the scope of this post because I’m going to cover this subject with many details in the future. In the meantime, I’ll try to draw your attention to simpler but still practical example such as an electrocardiogram (ECG) filtering. ECG acts at very low frequency i.e. 0.5 Hz to 100 Hz. The original signal is affected by various kinds of noises i.e. power line interference, electrode contact noise. IIR filters, especially elliptic ones, are considered to be effective tools to remove noise at low frequencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*lPqMVO0oIrCPsM9wpQ8f-w.png" /><figcaption>ECG denoising [2]</figcaption></figure><h4>How to use Syto</h4><p>From the very beginning, I was convinced that Syto has to ship an intuitive approach to filtering. In this context “intuitive” means “following a common sense and based on general, the well-know procedure”. Let me briefly touch it. Filtering consists of two sub-parts: filter design and filtering itself. Let come through the filter design workflow depicted below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*pJ6SWCHq-oT_v7epZ8mkQg.png" /><figcaption>Filter design workflow</figcaption></figure><ol><li>Choose an approximation</li><li>Find normalized analog filter with defined approximation</li><li>Set up the sampling rate if a digital filter is desired</li><li>Make appropriate frequency transformation</li><li>Get polynomials coefficients of a transfer function</li></ol><p>At this point, we have all the parameters to start processing the data. The only step left is to choose filtering method — lfilt or filtfilt.</p><p>Expressed in Scala code the usage of Syto looks much simpler</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01ede10e8b1777dc25c8d3046211fe7e/href">https://medium.com/media/01ede10e8b1777dc25c8d3046211fe7e/href</a></iframe><p>Likely, the users will want to get more about the library’s usage. I encourage them to inspect the unit tests provided alongside the <a href="https://github.com/SashkoTar/syto">production source code</a>. These tests were written not only to validate the correctness of the calculations which sometimes are quite comprehensive. They serve as expressive documentation as well.</p><h4>Compare Scipy and Syto</h4><p>Scipy is a great collection of mathematical algorithms. There is no sense to compare the whole toolbox with young Syto. My first priority was to provide filter design/implementation API. Therefore, the table below matches filter design functionality from scipy.signal only and Syto.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*ISSKRShNJXQa3jZj7jFbWg.png" /><figcaption>Scipy.signal vs syto</figcaption></figure><p>However, my plan is to keep bringing new algorithm to Syto to be mature DSP library. A full comparison between scipy.signal and Syto you can find in the project’s <a href="https://github.com/SashkoTar/syto/wiki/Syto-VS-scipy.signal">Github repository</a></p><h4>Plan</h4><p>Syto has just started its way and there are a lot of things/feature to implement. It’s worth mentioning that the existing road map for the library not abstract but consist of a list of reachable tasks:</p><ul><li>Publish jar artifact to one of public Maven repository</li><li>Implement functionality for FIR filter family</li><li>Integrate Syto with Java to make it JVM library, not for Scala only</li><li>Implement multi-dimensional filter toolset</li><li>Implement multi-rating filters</li></ul><p>In addition to the tasks enlisted above, it’s worth mentioning that while developing filter design methods I’ve implemented several mathematical algorithms that are necessary for some kinds of approximations. For example, the elliptic filter doesn’t have an analytical solution to finding its poles and zeros. It made me dive into the numerical methods to implement such weird things like elliptic integrals, Jacobi elliptic functions, etc. This set of functionality is used internally but I believe one day after refactoring it should be also the part of Syto’s public API.</p><h4>Summary</h4><p>I hope this brief overview has shared some ideas behind Syto. Scala is a great language and Syto’s intention is to bring Scala’s power to the scientistic world. The library waits for its users as well as for their feedbacks and new expectations. Please find the library on its <a href="https://github.com/SashkoTar/syto">Github repo</a>.</p><h4>Sources</h4><ul><li>[1] Manish Chauhan, Rajesh Mehra: ECG Noise Reduction Filter Using Elliptic &amp; Kaiser Techniques</li><li>[2] How to deal with ECG noise: <a href="https://vheart.io/blog/2017/how-to-deal-with-ecg-noise">https://vheart.io/blog/2017/how-to-deal-with-ecg-noise</a></li><li>[3] Mahesh S. Chavan, Ra.Agarwala, M.D.Uplane: Digital Elliptic Filter Application For Noise Reduction In ECG Signal</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1916626b9de4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logging in Spark with Log4j. How to customize a driver and executors for YARN cluster mode.]]></title>
            <link>https://medium.com/@cupreous.bowels/logging-in-spark-with-log4j-how-to-customize-a-driver-and-executors-for-yarn-cluster-mode-1be00b984a7c?source=rss-fb3698313f6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1be00b984a7c</guid>
            <category><![CDATA[yarn]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[log4j]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Oleksandr Tarasenko]]></dc:creator>
            <pubDate>Thu, 24 Jan 2019 13:41:32 GMT</pubDate>
            <atom:updated>2019-01-24T13:57:08.212Z</atom:updated>
            <content:encoded><![CDATA[<h3>Logging in Spark with Log4j. How to customize the driver and executors for YARN cluster mode.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*tOLOSVsdsEjNXiuD3S3tSg.jpeg" /></figure><p><em>In this article, I’m going to describe several configurations for logging in Spark. There are a lot of posts on the Internet about logging in yarn-client mode. At the same time, there is a lack of instruction on how to customize logging for cluster mode ( </em><em>--master yarn-cluster). By default, Spark uses </em><em>$SPARK_CONF_DIR/log4j.properties to configure log4j and straightforward solution is to change this file. However, this approach can be not acceptable due to absence write permissions. Moreover, it is even worse if you have permission because this file is used all application deployed to the cluster. Solving your own issue you can destroy a day to another cluster user. Before you start the reading please note that in the scope of this post terms “container” and “executor” are interchangeable. The sample application has been tested on Spark 1.6.3 and Spark 2.2 You can download it from my </em><a href="https://github.com/SashkoTar/spark-logger"><em>Github</em></a></p><p><strong>Common custom log4j.properties</strong><br>Fortunately, there is a pretty simple solution — custom log4j.properties can be loaded alongside with application using — files option. Please keep in mind<br>that in cluster mode a driver is running on the client machine and local path/storage can be used as a path to the file. It means configurations file must be accessible for any container. HDFS solves this task in a natural way. The source code below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebb72559accb0ee0731d82321118b3c1/href">https://medium.com/media/ebb72559accb0ee0731d82321118b3c1/href</a></iframe><p>It’s a quite effective and obvious approach which configures your driver as well as the executors. But what if it’s not still flexible enough? Say,<br>we need DEBUG level for driver and WARN for executors</p><p><strong>Custom log4j.properties for driver only</strong><br>It’s to introduce such configuration properties as spark.driver.extraJavaOptions and spark.executor.extraJavaOptions. They pass additional options to driver and executor JVMs respectively. The option for our case is -Dlog4j.configuration. The next listing shows how to configure the driver to use custom configuration while executors will use default one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fabf88290a8068c14b02c5ccb4270ff3/href">https://medium.com/media/fabf88290a8068c14b02c5ccb4270ff3/href</a></iframe><p><strong>Distinct custom log4j.properties for driver and executors</strong><br>If you want more flexibility to deploy two different configurations for driver and executors you can extend the previous listing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc7a69560c3b34b8c7f7b1f6d6e47a15/href">https://medium.com/media/fc7a69560c3b34b8c7f7b1f6d6e47a15/href</a></iframe><p><strong>How to read it easy</strong><br>Now we can configure any in a YARN-cluster. But it leads us to the next question: “How to read the logged data?” The point is that every Spark/YARN node writes its log locally. It means we should collect log-files from all executors and driver which are distributed among different physical hosts. It looks untrivial however this is the case. But here we can rely on YARN which ships a utility doing the aggregation for us. Just run in the command line</p><p>yarn logs --applicationId &lt;appidentifier&gt;</p><p>and aggregated log for all containers will be sent to a console. Please note that containers are executed on the different physical machines and path /var/spark-log is notional just to refer any local log directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*DC-eMZ6d3tuUGcihGqBQxg.jpeg" /><figcaption>Yarn log aggregation workflow</figcaption></figure><p>At the same time, it can be senseless for jobs with a lot of containers — you’ll lose yourself at this infinity. This is why it’s better to redirect to a file and then analyze it. Someone can ask: “Does it mean that with the same appender all loggers for the same container will be flushing to the same file? Can I separate Spark logs and application logs and have them in different files?” Yes, it’s possible — just add one more appender which the application logger will be writing to. This solution origins next question — where the appender will store the additional log file? How to read it? Yes, it clearly understood that every container will create one more log file. Therefore it’s necessary to define the path for the additional log file and it seems to be tricky. If we set such path /var/spark-log/my.log there is a probability that some issue will arrive because of no guarantees that this directory will be open to writing in. Even if it’s open… It’s quite exhausting to research where, say, a driver was executed, go to that machine and manually download the required file. Let’s split this problem into two subproblems:</p><p>· Where to write a separate log file</p><p>· How to read then that file</p><p>Official Spark doc gives a clear answer to both questions: property spark.yarn.app.container.log.dir refers to the directory where YARN stores logs so that YARN can effectively collect them and send to console. For example, you can configure your additional logger and appender:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e83fc34d61b547f4595256ca7c7871a/href">https://medium.com/media/7e83fc34d61b547f4595256ca7c7871a/href</a></iframe><p>and all the magic will be done by YARN itself, it will place the log into the correct directory. Also when requested it’s will aggregate this log with remaining logs and output the result with mentioned above yarn logs utility. Now it’s recommended to add one option --show_container_log_info to find the container with a needed file. It can be convenient if additional appender was added for driver only.</p><pre>yarn logs --applicationId application_1518439089919_3998 --show_container_log_info</pre><p>Having known the container identifier this utility can be used one more time to retrieve log data from the specified file</p><pre>yarn logs --applicationId application_1518439089919_3998 -containerId container_e34_1518439089919_3998_01_000001 -log_files bowels.log</pre><p>and the only file we are interested in will be printed out. If you know that there is only one file you want to analyze you can skip--containerId option and pass to print out the content of the requested file</p><pre>yarn logs --applicationId application_1518439089919_3998 -log_files bowels.log</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qimhYDZyLJUBq7BkQpV_Tw.jpeg" /><figcaption>Log output for specific file</figcaption></figure><p>It worth mentioning that logging gives a lot of opportunities to researchers who want to understand how Spark internally works: they can configure loggers for inspected packages and classes, setting different levels, redirecting logs to separate files to analyze them without mix-up.</p><p>Examples source code can be downloaded from my <a href="https://github.com/SashkoTar/spark-logger">Github</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1be00b984a7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Registering Hive table from Spark without manual column listing]]></title>
            <link>https://medium.com/@cupreous.bowels/registering-hive-table-from-spark-without-manual-column-listing-91de650eb699?source=rss-fb3698313f6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/91de650eb699</guid>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[hive]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Oleksandr Tarasenko]]></dc:creator>
            <pubDate>Mon, 17 Dec 2018 16:16:56 GMT</pubDate>
            <atom:updated>2018-12-17T16:16:56.863Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently I had to import ORC file to Hive. The whole ETL workflow consisted of such steps:</p><p>1. Read archived files from HDFS</p><p>2. Parse specific format and create Dataframe</p><p>3. Write Dataframe records as ORC files back to HDFS</p><p>4. Register ORC files as Hive external table to be accessible for users</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/494/1*5oVPHlBc-d2qg9cgCVoWMA.jpeg" /><figcaption>ETL Workflow</figcaption></figure><p>Everything went smoothly until I reached item #4. The challenge was to create Hive table backed by ORC files. As it is known, Hive doesn’t recognize ORC schema automatically and DDL sent to Hive should enlist all columns in the request:</p><pre>CREATE EXTERNAL TABLE IF NOT EXISTS mydb.tbl1 (<br>row1 INT, <br>row2 STRING, <br>row3 DOUBLE) <br>STORED AS ORC LOCATION &#39;/hdfs/hive/your-directory&#39;</pre><p>Unfortunately, in my case according to the customer’s requirement Dataframe contained more than 100 columns and writing them down manually could take a whole day. Therefore, it was not the option. I had to solve this task and somehow create the list of columns automatically. After some investigation, I came up with the solution. Dataframe’s method schema() returns a structure that describes its schema. Iterating over it I could extract column names and column types (line 15) and prepared list of column definitions expected by CREATE TABLE statement. The code to execute such procedure is below. I believe it can save a lot of time for someone who will be in such a position as I was.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24e5bafcfbd6db9a5d0418b3980555e2/href">https://medium.com/media/24e5bafcfbd6db9a5d0418b3980555e2/href</a></iframe><p>In one of my next posts I’ll share some details about how to parse data in customer specific format and create Dataframe from it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=91de650eb699" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark pipe. A one-pipe problem]]></title>
            <link>https://medium.com/@cupreous.bowels/spark-pipe-a-one-pipe-problem-ea1672ee254b?source=rss-fb3698313f6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea1672ee254b</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[hadoop]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[pipes]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Oleksandr Tarasenko]]></dc:creator>
            <pubDate>Wed, 21 Nov 2018 11:58:53 GMT</pubDate>
            <atom:updated>2018-11-21T11:58:53.503Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What did make me recall Mr. Sherlock Holmes and his famous “a one-pipe problem”? Recently I faced a need to fork external process within from Spark-application. There was practical necessity to add to existing functionality digital signal processing — Butterworth filter, FFT, etc. Having done investigation I’ve discovered neither Scala nor Java has such library. But there is Scipy library for Python. So, I had two possible solutions: write digital signal processing myself or integrate somehow existing code with Python. I preferred solution #1, but the customer as true data scientist insisted on solution #2. So, the task was to integrate Scala-based Spark application with Python scripts to handle its RDD. <br>These example applications have been tested with Spark 2.11 and can be downloaded from my </em><a href="https://github.com/SashkoTar/spark-pipe"><em>Github</em></a><em>.</em></p><h4>How to use it</h4><p>Let’s start from a simple example. Say, I have a bash script which is run on a linux host. The script concatenates line from stdin, adds hostname and writes the line to stdout. Its code is below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a612c69ececa87080bb8a71ceaf49804/href">https://medium.com/media/a612c69ececa87080bb8a71ceaf49804/href</a></iframe><p>I can send three lines to it to see the output:</p><pre>[oltar@**006][SparkBowels/spark-pipe]$ echo -e “1 \n 2 \n 24” | ./concatenate.sh</pre><pre><strong>Host **006 received data: [ 1 2 24 ]</strong></pre><p>Let’s imagine we have RDD and we want to handle its data with this bash script. Is it possible? Actually, it is. This is where method pipe() comes into the play. So, we can invoke an external process using the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3686840694b5c5ed62fdde0b2ec90fec/href">https://medium.com/media/3686840694b5c5ed62fdde0b2ec90fec/href</a></iframe><p>Now it’s time to check logs to be sure the script did exactly what we expected:</p><pre>[oltar@h001]$ yarn logs --applicationId application_1537877055510_5806 -am 1</pre><pre><strong>…<br>LogType:stdout <br>LogLastModifiedTime:Fri Oct 26 14:08:09 +0000 2018<br>LogLength:226<br>LogContents:<br>Input RDD has 4 partitions<br>Output RDD has 4 partitions<br>Host h034 received data: [ 1 2 3 4 5 ]<br>Host h016 received data: [ 6 7 8 9 10 ]<br>Host h035 received data: [ 11 12 13 14 15 ]<br>Host h039 received data: [ 16 17 18 19 20 ]<br>…</strong></pre><p>Perhaps it seems unexpected why there are four partial results instead of one but it is ok — RDD consists of four partitions.</p><ol><li>dataRDD, consists of 20 records and is split into 4 partitions</li><li>Records are cast to String</li><li>External process is forked for every partition</li><li>All records from partition are sent to its external process’s stdin. They are delimited by newline symbols</li><li>External process handles input data and writes to stdout</li><li>Data from stdout are written to output partition</li><li>Finally, we receive pipeRDD, containing four partitions with one line in each. These lines include hostname where they were handled. It proves that partitions have been handled on different hosts.</li></ol><p>In this way, after invocation RDD will contain the same number of partitions as it had before. It can be considered as a replacement of input partitions by lines from external process’s stdout. This workflow is depicted below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*cSD7NJ-9VNIoHqIon45pZg.jpeg" /><figcaption>Рис. 1</figcaption></figure><h4>What else can be done with pipe</h4><p>I’m going to give one more example. Suppose we have an archive file, containing climate data for Yagotyn district. The file itself can be found on my <a href="https://github.com/SashkoTar/spark-pipe">Github</a> repository. We’ll take several first lines to study file format and discover that it is semi-structured</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5525d9cbf3be18043d8aa234fc708aca/href">https://medium.com/media/5525d9cbf3be18043d8aa234fc708aca/href</a></iframe><p>The task is to extract for research purposes such information: date and time(Local time in Yagotyn), temperature(T), atmospheric pressure (Po) and humidity (U) for observations where visibility(VV) was less than one kilometer. I think it’s most likely a fog. To extract these data we have to apply the sequence of transformations against these lines:</p><ol><li>Get rid of quotes because of the need to filter by visibility. It should be cast to numeric type from string.</li><li>Split line into columns</li><li>Filter out lines starting with non-digit</li><li>Select observations where visibility is less than one kilometer, i.e. VV &lt; 1.0</li><li>Extract from every line only required fields</li></ol><p>Pipe-based solution can quite laconic and expressive enough. And, what is more important, a major part of the calculation is passed outside of executors to operational systems they run on. This is how I’d prefer to solve out this task:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96769504d490add687f6d1663c74fd36/href">https://medium.com/media/96769504d490add687f6d1663c74fd36/href</a></iframe><p>As it obvious we read the file from HDFS. Next steps absolutely reflect with the sequence we defined above.</p><ol><li>We remove quotes with sed utility</li><li>Then redirect output to awk utility and split fields</li><li>awk filters lines starting with non-digit characters(/^[0–9]/)</li><li>Now our line is split into columns and we select it if its field 22 is less then 1 (kilometer).</li><li>On the last step, we extract the requested fields. Notice that field 1 contains date and time at the same time.</li></ol><p>Someone can blame this code because of its readability. Perhaps I would do it myself when finding something like that in a repository and I’d prefer to see explicit, self-expressing code. But Spark is often used in interactive mode especially by data scientists. They don’t save sources into Git, they don’t build it as they don’t have such needs. Algorithms are often written once and run once. This is the case when a user can be egoistic and care about his convenience only and such solution is justified.</p><p>It’s worth mentioning that examples above haven’t covered partition management. As we saw all the lines could be handled independently from each other. This is why there is no need to pay attention to the RDD partition management. But it’s not always true. And we should keep it in mind when invoking external processes for such operations like data aggregation.</p><h4>How it works</h4><p>You can be one of those guys who always want to understand how it works on a low level. This why I added this sequence diagram, describing the processes behind the scene. For sake of sanity, I skipped some non-essential details to not overload the diagram. The actual implementation consists of much more blocks. You can check it yourself exploring Spark source code. I did not want to bore the readers with all this stuff and outlined most important parts which define expected functionality</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*6ZQtAAa5K2SVe9I_V8BOYw.jpeg" /><figcaption>Fig. 2</figcaption></figure><p>Why does the diagram start with PipedRDD’s method compute() instead of pipe(). This is because pipe() method is just <strong>transformation </strong>which does not fire any <strong>action </strong>but just returns PipedRDD instance. And after that invocation is delegated to its compute() method.</p><p>What does then happen?</p><ol><li>java.lang.ProcessBuilder instance is created</li><li>ProccessBuilder forks new external process which was passed as input parameter to pipe()method</li><li>Method compute() instantiates Thread1 which reads error (if any) from stderr of external process</li><li>Method compute() instantiates Thread2 which writes lines from input partition to external process’s stdin</li><li>Then method compute() reads lines from external process’s stdout</li><li>On the last step compute() creates Iterator which contains lines that have been received from the external process</li></ol><p>This is how step 3 looks like on source code level:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf117b7dc70355c9b46f0a2dd1b87497/href">https://medium.com/media/cf117b7dc70355c9b46f0a2dd1b87497/href</a></iframe><h4>Summary</h4><p>I hope this post has given essential knowledge to stop avoiding pipe() and start using it effectively. Used carefully this technique can have a lot of applications. I’ve shown one of them in this document. In next posts I’ll try to show industry known usage of pipe() method. And of course, you can download examples from my <a href="https://github.com/SashkoTar/spark-pipe">Github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea1672ee254b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark pipe. Дело на одну трубку]]></title>
            <link>https://medium.com/@cupreous.bowels/spark-pipe-%D0%B4%D0%B5%D0%BB%D0%BE-%D0%BD%D0%B0-%D0%BE%D0%B4%D0%BD%D1%83-%D1%82%D1%80%D1%83%D0%B1%D0%BA%D1%83-56242eae780e?source=rss-fb3698313f6d------2</link>
            <guid isPermaLink="false">https://medium.com/p/56242eae780e</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[sparkcore]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[pipes]]></category>
            <dc:creator><![CDATA[Oleksandr Tarasenko]]></dc:creator>
            <pubDate>Mon, 05 Nov 2018 11:17:49 GMT</pubDate>
            <atom:updated>2018-11-05T15:27:38.236Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Вспомнить великого сыщика и его легендарное “я называю такие дела “делом на одну трубку” меня заставил недавний случай — у меня возникла необходимость вызова внешней функциональности из Spark-кода. Практическая необходимость была обусловлена такими обстоятельствами: в существующую функциональность надо было добавить цифровую обработку сигналов — фильтр Баттерворта, БПФ и т.д. После некоторого исследования я обнаружил, что подходящей библиотеки на Scala/Java не существует. Но она есть в виде библиотеки Scipy для Python. Итак, у меня возникло 2 варианта: писать самому необходимую реализацию на Scala или же как-то интегрироваться с Python. Мне был ближе вариант №1, но заказчик, смотрящий на мир глазами дата-саентиста, настоял на варианте №2. Итак, задача звучала просто — Spark-приложение, написанное на Scala, должно вызывать Python-скрипты для обработки своего RDD. Используемое в качестве примера приложение тестировалось на Spark 2.11 и может быть скачано с моего </em><a href="https://github.com/SashkoTar/spark-pipe"><em>Github</em></a><em>.</em></p><h4>Как этим пользоваться</h4><p>Начнем с примера. Представим, что у нас есть некоторый код написанный на shell-скрипте и запускаемый на Linux-машине. Пускай этот скрипт просто конкатенирует строки, поступающие на стандартный вход (stdin), добавляет к ним имя хоста и пишет это в стандартный выход(stdout). Ниже приведен его код:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a612c69ececa87080bb8a71ceaf49804/href">https://medium.com/media/a612c69ececa87080bb8a71ceaf49804/href</a></iframe><p>Пошлем ему на вход три строки и посмотрим, что выйдет:</p><pre>[oltar@**006][SparkBowels/spark-pipe]$ echo -e “1 \n 2 \n 24” | ./concatenate.sh</pre><pre><strong>Host **006 received data: [ 1 2 24 ]</strong></pre><p>Теперь представим что у нас есть RDD и мы по какой-то причине хотим обработать из него данные этим bash-скриптом. Можно ли это сделать? Оказывается можно. Именно для такого случая и есть метод pipe. Сама последовательность будет выглядеть приблизительно так:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3686840694b5c5ed62fdde0b2ec90fec/href">https://medium.com/media/3686840694b5c5ed62fdde0b2ec90fec/href</a></iframe><p>Посмотрим логи, чтобы убедиться, что скрипт выполнил что он него ожидали:</p><pre>[oltar@h001]$ yarn logs --applicationId application_1537877055510_5806 -am 1</pre><pre><strong>…<br>LogType:stdout <br>LogLastModifiedTime:Fri Oct 26 14:08:09 +0000 2018<br>LogLength:226<br>LogContents:<br>Input RDD has 4 partitions<br>Output RDD has 4 partitions<br>Host h034 received data: [ 1 2 3 4 5 ]<br>Host h016 received data: [ 6 7 8 9 10 ]<br>Host h035 received data: [ 11 12 13 14 15 ]<br>Host h039 received data: [ 16 17 18 19 20 ]<br>…</strong></pre><p>Возможно, это покажется немного неожиданным, почему мы получили четыре частичных результата вместо одного, но все логично — именно столько разделов в RDD. Произошедшее можно описать так:</p><ol><li>Создается dataRDD, состоящий из 20 записей, разбитых на 4 раздела</li><li>Записи конвертируются к типа String</li><li>Для каждого из разделов создается свой экземпляр внешнего процесса</li><li>Все записи исходного раздела перенаправляются на стандартный вход внешнего процесса, при этом они разделены символом новой строки.</li><li>Внешний процесс обрабатывает данные и пишет в стандартный выход</li><li>Результаты считываются из стандартного выхода и пишутся выходной раздел</li><li>Получаем pipeRDD, состоящий из четырех разделов по одной записи в каждом с подтверждение того, что разделы были обработаны на разных хостах</li></ol><p>Таким образом, по завершению вызова RDD будет состоять из такого же количества разделов. Суммируя, можно сказать, что исходные разделы были заменены строками из стандартного выхода с процесса. Графически это можно изобразить таким образом.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*cSD7NJ-9VNIoHqIon45pZg.jpeg" /><figcaption>Рис. 1</figcaption></figure><h4>Что еще можно сделать с помощью pipe</h4><p>Приведем еще один пример. Допустим у нас есть архивный файл, содержащий метеоданные для Яготинского района. Сам файл можно посмотреть в <a href="https://github.com/SashkoTar/spark-pipe">репозитории на Github</a>. Возьмем несколько первых строк из него:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5525d9cbf3be18043d8aa234fc708aca/href">https://medium.com/media/5525d9cbf3be18043d8aa234fc708aca/href</a></iframe><p>Пускай из этих данных нам требуется получить такую информацию: дату и время (Local time in Yagotyn), температуру(T), атмосферное давление(Po) и влажность (U) для тех наблюдений, когда видимость(VV) была меньше одного километра. Вероятнее всего, это был туман. Для того, чтобы получить нужные данные надо проделать последовательность операций над строками файла</p><ol><li>Избавиться от двойных кавычек. Необходимость этой операции проистекает из фильтрования по видимости</li><li>Разбить на поля</li><li>Оставить строки, которые начинаются с цифры, а остальные отсеять.</li><li>Оставить наблюдения, где видимость менее одного километра, т.е. VV &lt; 1.0</li><li>Выбрать из каждой строки только затребованные поля.</li></ol><p>Решение с помощью pipe может быть крайне лаконичным и достаточно экспрессивным. При этом большая часть вычислений перекладывается непосредственно на сами операционные среды экзекьютеров. Вот как бы я решил эту задачу:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/96769504d490add687f6d1663c74fd36/href">https://medium.com/media/96769504d490add687f6d1663c74fd36/href</a></iframe><p>Сначала читаем файл из файловой системы, это очевидно. Далее все следуют в точности с ранее определенной последовательностью для каждой строки.</p><ol><li>Удаляем строки с помощью утилиты sed</li><li>Перенаправляем вывод в awk и разделяем на поля</li><li>Та же утилита отбрасывает строки, начинающиеся не с цифры (/^[0–9]/)</li><li>Имея к этому моменту разбитую на поля строку, оставляем те, где поле 22 меньше единицы.</li><li>Выбираем затребованные в условии поля, помня что поле 1 содержит сразу дату и время.</li></ol><p>Вполне возможно, что у кого-то такой код может вызвать нарекания, связанные с его читаемостью. Наверное, мне и самому не хотелось бы встретить что-то подобное в репозиторие и я предпочел видеть явно, что делает код. Но ведь спарк часто используется в интерактивном режиме, особенно дата-саентистами. Код не сохраняют так как в этом нет необходимости поскольку он выполняется единожды. В таких случаях пользователь может думать только про свое удобство и подобное решение имеет право на жизнь.</p><p>Отдельно хочу заметить то, чего пример выше не коснулся — контроля разделов. Так получилось, что в приведенном примере все строки могли быть обработаны независимо друг от друга, потому не было необходимости в контроле разделов. Но так бывает не всегда. Важно помнить об этом. Особенно при агрегировании данных с помощью внешних процессов.</p><h4>Как это работает</h4><p>Вполне возможно, что у кого-то возникнет желание понять, как все устроено. Ниже я привел диаграмму последовательности, описывающей то, что спрятано за сценой. Стоит отменить, что она несколько условна ибо реализация имеет гораздо больше всяких деталей. В этом можно убедиться, посмотрев исходный код самого Spark. Для того, чтобы не запутать читателя и самому не запутаться я выбрал самые ключевые моменты, которые и определяют нужную функциональность.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*6ZQtAAa5K2SVe9I_V8BOYw.jpeg" /><figcaption>Рис. 2</figcaption></figure><p>Почему диаграмма начинается с какого-то PipedRDD и его метода compute вместо ожидаемого pipe? Дело в том, что метод pipe не вызывает никаких действий, а всего лишь возвращает нам своего наследника — PipedRDD (transformation) и уже потом к нему перенаправляется вызов на метод compute после вызова действия (action)</p><p>Что происходит дальше?</p><ol><li>Создается экземпляр класс java.lang.ProcessBuilder</li><li>ProccessBuilder стартует внешний процесс. Именно тот, который мы передали в метод pipe</li><li>Запускается поток Thread1, который начинает читать ошибки (если они есть) из стандартного вывода ошибок (stderr) внешнего процесса</li><li>Запускается поток Thread2, который начинает писать строки из данного раздела в стандартный вход(stdin) внешнего процесса</li><li>После этого метод compute читает строки из стандартного вывода (stdout) внешнего процесса</li><li>Возвращается итератор, состоящий из строк, полученных из внешнего процесс</li></ol><p>Например, шаг 3 на уровне кода выглядит так:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf117b7dc70355c9b46f0a2dd1b87497/href">https://medium.com/media/cf117b7dc70355c9b46f0a2dd1b87497/href</a></iframe><h4>Заключение</h4><p>Я надеюсь, что эта статья дала необходимые знания, для того, чтобы начать работать с pipe и перестать их боятся. Если подходить взвешенно, то для этой технологии можно найти массу уместных применений. Один такой случай я и показал в статье. В будущем я планирую написать отдельную статью о известных и успешных использованиях pipe. И, конечно же, вы можете найти коды примеров на моем <a href="https://github.com/SashkoTar/spark-pipe">Github</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56242eae780e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>