在 HDInsight 中的 Apache Hadoop 上搭配 Apache Hive 和 Apache Pig 使用 C# 使用者定義函式

瞭解如何在 HDInsight 上搭配 Apache HiveApache Pig 使用 C# 使用者定義函式 (UDF)。

重要

本檔中的步驟適用於以Linux為基礎的 HDInsight 叢集。 Linux 是 HDInsight 3.4 版或更新版本上唯一使用的作業系統。 如需詳細資訊,請參閱 HDInsight 元件版本控制

Hive 和 Pig 都可以將數據傳遞至外部應用程式進行處理。 此程序稱為 串流。 使用 .NET 應用程式時,數據會傳遞至 STDIN 上的應用程式,而應用程式會在 STDOUT 上傳回結果。 若要從 STDIN 和 STDOUT 讀取和寫入,您可以使用和從主控台應用程式讀取 Console.ReadLine()Console.WriteLine() 寫入。

必要條件

HDInsight 上的 .NET

以 Linux 為基礎的 HDInsight 叢集會使用 Mono (https://mono-project.com) 執行 .NET 應用程式。 4.2.1 版的 Mono 隨附於 3.6 版的 HDInsight。

如需Mono與.NET Framework 版本相容性的詳細資訊,請參閱 Mono相容性

如需 HDInsight 版本隨附之 .NET Framework 和 Mono 版本的詳細資訊,請參閱 HDInsight 元件版本

建立 C# 專案

下列各節說明如何在 Visual Studio 中為 Apache Hive UDF 和 Apache Pig UDF 建立 C# 專案。

Apache Hive UDF

若要建立 Apache Hive UDF 的 C# 專案:

  1. 啟動 Visual Studio。

  2. 選取 [建立新專案]

  3. 在 [ 建立新專案 ] 視窗中,選擇 控制台應用程式 (.NET Framework) 範本 (C# 版本)。 然後選取下一步

  4. 在 [設定新專案] 視窗中,輸入 HiveCSharp 的專案名稱,然後流覽至或建立 [位置] 以儲存新專案。 然後選取建立

  5. 在 Visual Studio IDE 中,以下列程式代碼取代 Program.cs 的內容

    using System;
    using System.Security.Cryptography;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace HiveCSharp
    {
        class Program
        {
            static void Main(string[] args)
            {
                string line;
                // Read stdin in a loop
                while ((line = Console.ReadLine()) != null)
                {
                    // Parse the string, trimming line feeds
                    // and splitting fields at tabs
                    line = line.TrimEnd('\n');
                    string[] field = line.Split('\t');
                    string phoneLabel = field[1] + ' ' + field[2];
                    // Emit new data to stdout, delimited by tabs
                    Console.WriteLine("{0}\t{1}\t{2}", field[0], phoneLabel, GetMD5Hash(phoneLabel));
                }
            }
            /// <summary>
            /// Returns an MD5 hash for the given string
            /// </summary>
            /// <param name="input">string value</param>
            /// <returns>an MD5 hash</returns>
            static string GetMD5Hash(string input)
            {
                // Step 1, calculate MD5 hash from input
                MD5 md5 = System.Security.Cryptography.MD5.Create();
                byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
                byte[] hash = md5.ComputeHash(inputBytes);
    
                // Step 2, convert byte array to hex string
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < hash.Length; i++)
                {
                    sb.Append(hash[i].ToString("x2"));
                }
                return sb.ToString();
            }
        }
    }
    
  6. 從功能表欄,選取 [建>置建置方案 ] 以建置專案。

  7. 關閉解決方案。

Apache Pig UDF

若要建立 Apache Hive UDF 的 C# 專案:

  1. 開啟 Visual Studio。

  2. 在 [開始] 視窗中,選取 [建立新專案]

  3. 在 [ 建立新專案 ] 視窗中,選擇 控制台應用程式 (.NET Framework) 範本 (C# 版本)。 然後選取下一步

  4. 在 [設定新專案] 視窗中,輸入 PigUDF 的專案名稱,然後移至或建立 [位置] 以儲存新專案。 然後選取建立

  5. 在 Visual Studio IDE 中,以下列程式代碼取代 Program.cs 的內容

    using System;
    
    namespace PigUDF
    {
        class Program
        {
            static void Main(string[] args)
            {
                string line;
                // Read stdin in a loop
                while ((line = Console.ReadLine()) != null)
                {
                    // Fix formatting on lines that begin with an exception
                    if(line.StartsWith("java.lang.Exception"))
                    {
                        // Trim the error info off the beginning and add a note to the end of the line
                        line = line.Remove(0, 21) + " - java.lang.Exception";
                    }
                    // Split the fields apart at tab characters
                    string[] field = line.Split('\t');
                    // Put fields back together for writing
                    Console.WriteLine(String.Join("\t",field));
                }
            }
        }
    }
    

    此程式代碼會剖析從 Pig 傳送的行,並重新格式化開頭 java.lang.Exception為的行。

  6. 從功能表列,選擇 [建>置建置方案 ] 以建置專案。

  7. 讓方案保持開啟狀態。

上傳至儲存體

接下來,將Hive和 Pig UDF 應用程式上傳至 HDInsight 叢集上的記憶體。

  1. 在 Visual Studio 中,流覽至 [檢視>伺服器總管]。

  2. [伺服器總管] 中,以滑鼠右鍵按兩下 [Azure],選取 [連線 至 Microsoft Azure 訂用帳戶],然後完成登入程式。

  3. 展開您想要部署此應用程式的 HDInsight 叢集。 列出文字為 [預設 儲存體 帳戶] 的專案。

    Default storage account, HDInsight cluster, Server Explorer.

    • 如果可以展開這個專案,您就會使用 Azure 儲存體 帳戶作為叢集的預設記憶體。 若要檢視叢集預設記憶體上的檔案,請展開專案,然後按兩下 [預設容器]。

    • 如果無法展開此專案,您會使用 Azure Data Lake 儲存體 作為叢集的預設記憶體。 若要檢視叢集預設記憶體上的檔案,請按兩下 [預設 儲存體 帳戶] 專案。

  4. 若要上傳.exe檔案,請使用下列其中一種方法:

    • 如果您使用 Azure 儲存體 帳戶,請選取 [上傳 Blob] 圖示。

      HDInsight upload icon for new project.

      在 [上傳新檔案] 對話方塊的 [檔名] 底下,選取 [瀏覽]。 在 [上傳 Blob] 對話框中,移至 HiveCSharp 專案的 bin\debug 資料夾,然後選擇HiveCSharp.exe檔案。 最後,選取 [開啟],然後選取 [確定] 以完成上傳。

    • 如果您使用 Azure Data Lake 儲存體,請以滑鼠右鍵按兩下檔案清單中的空白區域,然後選取 [上傳]。 最後,選擇 HiveCSharp.exe 檔案,然後選取 [ 開啟]。

    HiveCSharp.exe上傳完成後,請針對PigUDF.exe檔案重複上傳程式

執行 Apache Hive 查詢

現在您可以執行使用 Hive UDF 應用程式的 Hive 查詢。

  1. 在 Visual Studio 中,流覽至 [檢視>伺服器總管]。

  2. 展開 [Azure],然後展開 [HDInsight]。

  3. 以滑鼠右鍵按下您部署 HiveCSharp 應用程式的叢集,然後選取 [ 寫入 Hive 查詢]。

  4. 針對 Hive 查詢使用下列文字:

    -- Uncomment the following if you are using Azure Storage
    -- add file wasbs:///HiveCSharp.exe;
    -- Uncomment the following if you are using Azure Data Lake Storage Gen1
    -- add file adl:///HiveCSharp.exe;
    -- Uncomment the following if you are using Azure Data Lake Storage Gen2
    -- add file abfs:///HiveCSharp.exe;
    
    SELECT TRANSFORM (clientid, devicemake, devicemodel)
    USING 'HiveCSharp.exe' AS
    (clientid string, phoneLabel string, phoneHash string)
    FROM hivesampletable
    ORDER BY clientid LIMIT 50;
    

    重要

    取消 add file 批注語句,以符合叢集所使用的預設記憶體類型。

    此查詢會clientidhivesampletable選取 、 devicemakedevicemodel 字段,然後將欄位傳遞至HiveCSharp.exe應用程式。 查詢預期應用程式會傳回三個字段,這些欄位會儲存為 clientidphoneLabelphoneHash。 查詢也預期會在預設記憶體容器的根目錄中尋找 HiveCSharp.exe

  5. 將預設 的 Interactive 切換為 Batch,然後選取 [提交 ] 將作業提交至 HDInsight 叢集。 [ Hive 作業摘要 ] 視窗隨即開啟。

  6. 選取 [重新整理] 以重新整理摘要,直到 [作業狀態] 變更為 [已完成]。 若要檢視作業輸出,請選取 [作業輸出]。

執行 Apache Pig 作業

您也可以執行使用 Pig UDF 應用程式的 Pig 作業。

  1. 使用 SSH 連線到 HDInsight 叢集。 (例如,執行 命令 ssh sshuser@<clustername>-ssh.azurehdinsight.net。)如需詳細資訊,請參閱 搭配HDInsight 使用SSH。

  2. 使用下列命令啟動 Pig 命令列:

    pig
    

    隨即 grunt> 顯示提示。

  3. 輸入下列命令以執行使用 .NET Framework 應用程式的 Pig 作業:

    DEFINE streamer `PigUDF.exe` CACHE('/PigUDF.exe');
    LOGS = LOAD '/example/data/sample.log' as (LINE:chararray);
    LOG = FILTER LOGS by LINE is not null;
    DETAILS = STREAM LOG through streamer as (col1, col2, col3, col4, col5);
    DUMP DETAILS;
    

    DEFINE語句會為 PigUDF.exe 應用程式建立的streamer別名,並從CACHE叢集的預設記憶體載入它。 稍後, streamer 會與運算符搭配 STREAM 使用,以處理 中包含的 LOG 單行,並以一系列數據行傳回數據。

    注意

    用於串流的應用程式名稱,在別名時必須以 ` (backtick) 字元括住,以及 ' 搭配 使用 時由 (單引號) 字元括 SHIP住。

  4. 輸入最後一行之後,作業應該會啟動。 它會傳回類似下列文字的輸出:

    (2019-07-15 16:43:25 SampleClass5 [WARN] problem finding id 1358451042 - java.lang.Exception)
    (2019-07-15 16:43:25 SampleClass5 [DEBUG] detail for id 1976092771)
    (2019-07-15 16:43:25 SampleClass5 [TRACE] verbose detail for id 1317358561)
    (2019-07-15 16:43:25 SampleClass5 [TRACE] verbose detail for id 1737534798)
    (2019-07-15 16:43:25 SampleClass7 [DEBUG] detail for id 1475865947)
    
  5. 使用 exit 結束 pig。

下一步

在本檔中,您已瞭解如何從 HDInsight 上的 Hive 和 Pig 使用 .NET Framework 應用程式。 如果您想要瞭解如何搭配Hive和 Pig 使用 Python,請參閱 在 HDInsight 中使用 Python 與 Apache Hive 和 Apache Pig。

如需使用Hive的其他方式,以及瞭解如何使用 MapReduce,請參閱下列文章: