Apache Pig - LAST_INDEX_OF() 函式



LAST_INDEX_OF() 函式接受一個字串值和一個字元作為輸入。它返回給定字元在字串中最後一次出現的索引,從字串的結尾開始反向搜尋。

語法

以下是 LAST_INDEX_OF() 函式的語法

grunt> LAST_INDEX_OF(string, 'character')

示例

假設在 HDFS 目錄 /pig_data/ 中有一個名為 emp.txt 的檔案,內容如下所示。此檔案包含員工詳細資訊,例如 ID、姓名、年齡和城市。

emp.txt

001,Robin,22,newyork
002,BOB,23,Kolkata
003,Maya,23,Tokyo 
004,Sara,25,London 
005,David,23,Bhuwaneshwar 
006,Maggy,22,Chennai
007,Robert,22,newyork 
008,Syam,23,Kolkata
009,Mary,25,Tokyo 
010,Saran,25,London 
011,Stacy,25,Bhuwaneshwar 
012,Kelly,22,Chennai

並且,我們已使用名為 emp_data 的關係將此檔案載入到 Pig 中,如下所示。

grunt> emp_data = LOAD 'hdfs://:9000/pig_data/emp.txt' USING PigStorage(',')
   as (id:int, name:chararray, age:int, city:chararray);

以下是一個 LAST_INDEX_OF() 函式的示例。在這個例子中,我們將從每個員工姓名的末尾查詢字母 'g' 的出現位置。

grunt> last_index_data = FOREACH emp_data GENERATE (id,name), LAST_INDEX_OF(name, 'g');

以上語句從每個員工姓名的末尾開始解析,並返回字母 'g' 首次出現的索引值。如果姓名中不包含字母 'g',則返回 -1

語句的結果將儲存在名為 last_index_data 的關係中。使用 Dump 運算子驗證關係 last_index_data 的內容,如下所示。

grunt> Dump last_index_data;
  
((1,Robin),-1)
((2,BOB),-1)
((3,Maya),-1)
((4,Sara),-1) 
((5,David),-1)
((6,Maggy),3)
((7,Robert),-1)
((8,Syam),-1)
((9,Mary),-1) 
((10,Saran),-1)
((11,Stacy),-1)
((12,Kelly),-1)
apache_pig_string_functions.htm
廣告
© . All rights reserved.