干貨:最受歡迎編程語言c與大數(shù)據(jù)開發(fā)實(shí)踐
IEEE Spectrum的第三次“***編程語言”中,C語言居首,有人說是大數(shù)據(jù)贏了。本文將探討c與大數(shù)據(jù)的開發(fā)實(shí)踐。大數(shù)據(jù)是使用工具和技術(shù)處理大量和復(fù)雜數(shù)據(jù)集合的術(shù)語。能夠處理大量數(shù)據(jù)的技術(shù)稱為MapReduce。
大數(shù)據(jù)何時(shí)使用MapReduce
大概有如下場景會(huì)應(yīng)用到MapReduce:
Apache Hadoop
開發(fā)MapReduce解決方案,推薦使用Hadoop,它已經(jīng)是事實(shí)上的標(biāo)準(zhǔn),同時(shí)也是開源免費(fèi)的軟件。
還有其他多個(gè)優(yōu)點(diǎn):
- 成本效益:不需要任何專門和奇特的硬件,因?yàn)檐浖谡5挠布歼\(yùn)行正常
- 容錯(cuò):如果有節(jié)點(diǎn)出現(xiàn)問題,其它節(jié)點(diǎn)可以接收它的工作,整個(gè)集群繼續(xù)處理。
本文中我們將使用PHP做為主開發(fā)語言。
Apache Hadoop的安裝配置超出了本文范圍。您可以根據(jù)自己的平臺(tái),在線輕松找到很多文章。為了保持簡單,我們只討論大數(shù)據(jù)相關(guān)的事。
映射器的任務(wù)是將輸入轉(zhuǎn)換成一系列的鍵值對。比如在字計(jì)數(shù)器的情況下,輸入是一系列的行。我們按單詞將它們分開,把它們變成鍵值對(如key:word,value:1),看起來像這樣:
- the 1
- water 1
- on 1
- on 1
- water 1
- on 1
- ... 1
reducer
mapping和reducing的整個(gè)過程看起來有點(diǎn)像這樣,請看下列之圖表:
使用PHP做單詞計(jì)數(shù)器
執(zhí)行以下命令下載這本書:
- wget http://www.gutenberg.org/cache ... 1.txt
我們的PHP代碼從mapper開始
- #!/usr/bin/php
- <?php
- // iterate through lines
- while($line = fgets(STDIN)){
- // remove leading and trailing
- $line = ltrim($line);
- $line = rtrim($line);
- // split the line in words
- $words = preg_split('/\s/', $line, -1, PREG_SPLIT_NO_EMPTY);
- // iterate through words
- foreach( $words as $key ) {
- // print word (key) to standard output
- // the output will be used in the
- // reduce (reducer.php) step
- // word (key) tab-delimited wordcount (1)
- printf("%s\t%d\n", $key, 1);
- }
- }
- ?>
你可以通過使用某些命令和管道的組合來在本地輕松測試腳本。
- head -n1000 pg2701.txt | ./mapper.php | sort | ./reducer.php
輸出將存儲(chǔ)在文件夾hello / result中,可以通過執(zhí)行以下命令查看
- hdfs dfs -cat hello/result/part-00000
下一個(gè)例子是一個(gè)更實(shí)際的例子,雖然數(shù)據(jù)集相對較小,但是相同的邏輯可以很容易地應(yīng)用于具有數(shù)百個(gè)數(shù)據(jù)點(diǎn)的集合上。 我們將嘗試計(jì)算過去五十年的黃金年平均價(jià)格。
在HDFS(Hadoop分布式文件系統(tǒng))中創(chuàng)建一個(gè)工作目錄
- hadoop dfs -mkdir goldprice
我的reducer看起來像這樣
- #!/usr/bin/php
- <?php
- // iterate through lines
- while($line = fgets(STDIN)){
- // remove leading and trailing
- $line = ltrim($line);
- $line = rtrim($line);
- // regular expression to capture year and gold value
- preg_match("/^(.*?)\-(?:.*),(.*)$/", $line, $matches);
- if ($matches) {
- // key: year, value: gold price
- printf("%s\t%.3f\n", $matches[1], $matches[2]);
- }
- }
- ?>
像單詞統(tǒng)計(jì)樣例一樣,我們也可以在本地測試
- head -n1000 data.csv | ./mapper.php | sort | ./reducer.php
查看平均值
- hdfs dfs -cat goldprice/result/part-00000
我們經(jīng)常會(huì)將結(jié)果轉(zhuǎn)換成圖表。 對于這個(gè)演示,我將使用gnuplot,你可以使用其它任何有趣的東西。
創(chuàng)建一個(gè)gnu plot配置文件(gold.plot)并復(fù)制以下內(nèi)容
- # Gnuplot script file for generating gold prices
- set terminal png
- set output "chart.jpg"
- set style data lines
- set nokey
- set grid
- set title "Gold prices"
- set xlabel "Year"
- set ylabel "Price"
- plot "gold.dat"
這會(huì)生成一個(gè)名為chart.jpg的文件。看起來像這樣:
