玩轉大數據系列之Apache Pig如何與Apache Solr集成(二)

散仙,在上篇文章中介紹了,如何使用Apache Pig與Lucene集成,還不知道的道友們,能夠先看下上篇,熟悉下具體的流程。 
在與Lucene集成過程當中,咱們發現最終還要把生成的Lucene索引,拷貝至本地磁盤,才能提供檢索服務,這樣以來,比較繁瑣,並且有如下幾個缺點: 

(一)在生成索引以及最終能提供正常的服務以前,索引通過屢次落地操做,這無疑會給磁盤和網絡IO,帶來巨大影響 

(二)Lucene的Field的配置與其UDF函數的代碼耦合性過強,並且提供的配置也比較簡單,不太容易知足,靈活多變的檢索需求和服務,若是改動索引配置,則有可能須要從新編譯源碼。 

(三)對Hadoop的分佈式存儲系統HDFS依賴過強,若是使用與Lucene集成,那麼則意味着你提供檢索的Web服務器,則必須跟hadoop的存儲節點在一個機器上,不然,沒法從HDFS上下拉索引,除非你本身寫程序,或使用scp再次從目標機傳輸,這樣無疑又增長了,系統的複雜性。 


鑑於有以上幾個缺點,因此建議你們使用Solr或ElasticSearch這樣的封裝了Lucene更高級的API框架,那麼Solr與ElasticSearch和Lucene相比,又有什麼優勢呢? 

(1)在最終的寫入數據時,咱們能夠直接最終結果寫入solr或es,同時也能夠在HDFS上保存一份,做爲災備。 

(2)使用了solr或es,這時,咱們字段的配置徹底與UDF函數代碼無關,咱們的任何字段配置的變更,都不會影響Pig的UDF函數的代碼,而在UDF函數裏,惟一要作的,就是將最終數據,提供給solr和es服務。 

(3)solr和es都提供了restful風格的http操做方式,這時候,咱們的檢索集羣徹底能夠與Hadoop集羣分離,從而讓他們各自都專一本身的服務。 



下面,散仙就具體說下如何使用Pig和Solr集成? 

(1)依舊訪問這個地址下載源碼壓縮包。 
(2)提取出本身想要的部分,在eclipse工程中,修改定製適合本身環境的的代碼(Solr版本是否兼容?hadoop版本是否兼容?,Pig版本是否兼容?)。 
(3)使用ant從新打包成jar 
(4)在pig裏,註冊相關依賴的jar包,並使用索引存儲 



注意,在github下載的壓縮裏直接提供了對SolrCloud模式的提供,而沒有提供,普通模式的函數,散仙在這裏稍做修改後,能夠支持普通模式的Solr服務,代碼以下:


SolrOutputFormat函數 

java

Java代碼 git

  1. package com.pig.support.solr;  github

  2.   

  3.   

  4.   

  5. import java.io.IOException;  web

  6. import java.util.ArrayList;  apache

  7. import java.util.List;  服務器

  8. import java.util.concurrent.Executors;  微信

  9. import java.util.concurrent.ScheduledExecutorService;  restful

  10. import java.util.concurrent.TimeUnit;  網絡

  11.   

  12. import org.apache.hadoop.io.Writable;  app

  13. import org.apache.hadoop.mapreduce.JobContext;  

  14. import org.apache.hadoop.mapreduce.OutputCommitter;  

  15. import org.apache.hadoop.mapreduce.RecordWriter;  

  16. import org.apache.hadoop.mapreduce.TaskAttemptContext;  

  17. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;  

  18. import org.apache.solr.client.solrj.SolrServer;  

  19. import org.apache.solr.client.solrj.SolrServerException;  

  20. import org.apache.solr.client.solrj.impl.CloudSolrServer;  

  21. import org.apache.solr.client.solrj.impl.HttpSolrServer;  

  22. import org.apache.solr.common.SolrInputDocument;  

  23. /** 

  24.  * @author qindongliang 

  25.  * 支持SOlr的SolrOutputFormat 

  26.  * 若是你想了解,或學習更多這方面的 

  27.  * 知識,請加入咱們的羣: 

  28.  *  

  29.  * 搜索技術交流羣(2000人):324714439  

  30.  * 大數據技術1號交流羣(2000人):376932160  (已滿) 

  31.  * 大數據技術2號交流羣(2000人):415886155  

  32.  * 微信公衆號:我是攻城師(woshigcs) 

  33.  *  

  34.  * */  

  35. public class SolrOutputFormat extends  

  36.         FileOutputFormat<Writable, SolrInputDocument> {  

  37.   

  38.     final String address;  

  39.     final String collection;  

  40.   

  41.     public SolrOutputFormat(String address, String collection) {  

  42.         this.address = address;  

  43.         this.collection = collection;  

  44.     }  

  45.   

  46.     @Override  

  47.     public RecordWriter<Writable, SolrInputDocument> getRecordWriter(  

  48.             TaskAttemptContext ctx) throws IOException, InterruptedException {  

  49.         return new SolrRecordWriter(ctx, address, collection);  

  50.     }  

  51.   

  52.       

  53.     @Override  

  54.     public synchronized OutputCommitter getOutputCommitter(  

  55.             TaskAttemptContext arg0) throws IOException {  

  56.         return new OutputCommitter(){  

  57.   

  58.             @Override  

  59.             public void abortTask(TaskAttemptContext ctx) throws IOException {  

  60.                   

  61.             }  

  62.   

  63.             @Override  

  64.             public void commitTask(TaskAttemptContext ctx) throws IOException {  

  65.                   

  66.             }  

  67.   

  68.             @Override  

  69.             public boolean needsTaskCommit(TaskAttemptContext arg0)  

  70.                     throws IOException {  

  71.                 return true;  

  72.             }  

  73.   

  74.             @Override  

  75.             public void setupJob(JobContext ctx) throws IOException {  

  76.                   

  77.             }  

  78.   

  79.             @Override  

  80.             public void setupTask(TaskAttemptContext ctx) throws IOException {  

  81.                   

  82.             }  

  83.               

  84.               

  85.         };  

  86.     }  

  87.   

  88.   

  89.     /** 

  90.      * Write out the LuceneIndex to a local temporary location.<br/> 

  91.      * On commit/close the index is copied to the hdfs output directory.<br/> 

  92.      *  

  93.      */  

  94.     static class SolrRecordWriter extends RecordWriter<Writable, SolrInputDocument> {  

  95.         /**Solr的地址*/  

  96.         SolrServer server;  

  97.         /**批處理提交的數量**/  

  98.         int batch = 5000;  

  99.           

  100.         TaskAttemptContext ctx;  

  101.           

  102.         List<SolrInputDocument> docs = new ArrayList<SolrInputDocument>(batch);  

  103.         ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();  

  104.         /** 

  105.          * Opens and forces connect to CloudSolrServer 

  106.          *  

  107.          * @param address 

  108.          */  

  109.         public SolrRecordWriter(final TaskAttemptContext ctx, String address, String collection) {  

  110.             try {  

  111.                 this.ctx = ctx;  

  112.                 server = new HttpSolrServer(address);  

  113.                   

  114.                 exec.scheduleWithFixedDelay(new Runnable(){  

  115.                     public void run(){  

  116.                         ctx.progress();  

  117.                     }  

  118.                 }, 10001000, TimeUnit.MILLISECONDS);  

  119.             } catch (Exception e) {  

  120.                 RuntimeException exc = new RuntimeException(e.toString(), e);  

  121.                 exc.setStackTrace(e.getStackTrace());  

  122.                 throw exc;  

  123.             }  

  124.         }  

  125.   

  126.           

  127.         /** 

  128.          * On close we commit 

  129.          */  

  130.         @Override  

  131.         public void close(final TaskAttemptContext ctx) throws IOException,  

  132.                 InterruptedException {  

  133.   

  134.             try {  

  135.                   

  136.                 if (docs.size() > 0) {  

  137.                     server.add(docs);  

  138.                     docs.clear();  

  139.                 }  

  140.   

  141.                 server.commit();  

  142.             } catch (SolrServerException e) {  

  143.                 RuntimeException exc = new RuntimeException(e.toString(), e);  

  144.                 exc.setStackTrace(e.getStackTrace());  

  145.                 throw exc;  

  146.             } finally {  

  147.                 server.shutdown();  

  148.                 exec.shutdownNow();  

  149.             }  

  150.               

  151.         }  

  152.   

  153.         /** 

  154.          * We add the indexed documents without commit 

  155.          */  

  156.         @Override  

  157.         public void write(Writable key, SolrInputDocument doc)  

  158.                 throws IOException, InterruptedException {  

  159.             try {  

  160.                 docs.add(doc);  

  161.                 if (docs.size() >= batch) {  

  162.                     server.add(docs);  

  163.                     docs.clear();  

  164.                 }  

  165.             } catch (SolrServerException e) {  

  166.                 RuntimeException exc = new RuntimeException(e.toString(), e);  

  167.                 exc.setStackTrace(e.getStackTrace());  

  168.                 throw exc;  

  169.             }  

  170.         }  

  171.   

  172.     }  

  173. }  





SolrStore函數 

  1. package com.pig.support.solr;  

  2.   

  3.   

  4.   

  5. import java.io.IOException;  

  6. import java.util.Properties;  

  7.   

  8. import org.apache.hadoop.fs.Path;  

  9. import org.apache.hadoop.io.Writable;  

  10. import org.apache.hadoop.mapreduce.Job;  

  11. import org.apache.hadoop.mapreduce.OutputFormat;  

  12. import org.apache.hadoop.mapreduce.RecordWriter;  

  13. import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;  

  14. import org.apache.pig.ResourceSchema;  

  15. import org.apache.pig.ResourceSchema.ResourceFieldSchema;  

  16. import org.apache.pig.ResourceStatistics;  

  17. import org.apache.pig.StoreFunc;  

  18. import org.apache.pig.StoreMetadata;  

  19. import org.apache.pig.data.Tuple;  

  20. import org.apache.pig.impl.util.UDFContext;  

  21. import org.apache.pig.impl.util.Utils;  

  22. import org.apache.solr.common.SolrInputDocument;  

  23.   

  24. /** 

  25.  *  

  26.  * Create a lucene index 

  27.  *  

  28.  */  

  29. public class SolrStore extends StoreFunc implements StoreMetadata {  

  30.   

  31.     private static final String SCHEMA_SIGNATURE = "solr.output.schema";  

  32.   

  33.     ResourceSchema schema;  

  34.     String udfSignature;  

  35.     RecordWriter<Writable, SolrInputDocument> writer;  

  36.   

  37.     String address;  

  38.     String collection;  

  39.       

  40.     public SolrStore(String address, String collection) {  

  41.         this.address = address;  

  42.         this.collection = collection;  

  43.     }  

  44.   

  45.     public void storeStatistics(ResourceStatistics stats, String location,  

  46.             Job job) throws IOException {  

  47.     }  

  48.   

  49.     public void storeSchema(ResourceSchema schema, String location, Job job)  

  50.             throws IOException {  

  51.     }  

  52.   

  53.     @Override  

  54.     public void checkSchema(ResourceSchema s) throws IOException {  

  55.         UDFContext udfc = UDFContext.getUDFContext();  

  56.         Properties p = udfc.getUDFProperties(this.getClass(),  

  57.                 new String[] { udfSignature });  

  58.         p.setProperty(SCHEMA_SIGNATURE, s.toString());  

  59.     }  

  60.   

  61.     public OutputFormat<Writable, SolrInputDocument> getOutputFormat()  

  62.             throws IOException {  

  63.         // not be used  

  64.         return new SolrOutputFormat(address, collection);  

  65.     }  

  66.   

  67.     /** 

  68.      * Not used 

  69.      */  

  70.     @Override  

  71.     public void setStoreLocation(String location, Job job) throws IOException {  

  72.         FileOutputFormat.setOutputPath(job, new Path(location));  

  73.     }  

  74.   

  75.     @Override  

  76.     public void setStoreFuncUDFContextSignature(String signature) {  

  77.         this.udfSignature = signature;  

  78.     }  

  79.   

  80.     @SuppressWarnings({ "unchecked""rawtypes" })  

  81.     @Override  

  82.     public void prepareToWrite(RecordWriter writer) throws IOException {  

  83.         this.writer = writer;  

  84.         UDFContext udc = UDFContext.getUDFContext();  

  85.         String schemaStr = udc.getUDFProperties(this.getClass(),  

  86.                 new String[] { udfSignature }).getProperty(SCHEMA_SIGNATURE);  

  87.   

  88.         if (schemaStr == null) {  

  89.             throw new RuntimeException("Could not find udf signature");  

  90.         }  

  91.   

  92.         schema = new ResourceSchema(Utils.getSchemaFromString(schemaStr));  

  93.   

  94.     }  

  95.   

  96.     /** 

  97.      * Shamelessly copied from : https://issues.apache.org/jira/secure/attachment/12484764/NUTCH-1016-2.0.patch 

  98.      * @param input 

  99.      * @return 

  100.      */  

  101.     private static String stripNonCharCodepoints(String input) {  

  102.         StringBuilder retval = new StringBuilder(input.length());  

  103.         char ch;  

  104.   

  105.         for (int i = 0; i < input.length(); i++) {  

  106.             ch = input.charAt(i);  

  107.   

  108.             // Strip all non-characters  

  109.             // http://unicode.org/cldr/utility/list-unicodeset.jsp?a=[:Noncharacter_Code_Point=True:]  

  110.             // and non-printable control characters except tabulator, new line  

  111.             // and carriage return  

  112.             if (ch % 0x10000 != 0xffff && // 0xffff - 0x10ffff range step  

  113.                                             // 0x10000  

  114.                     ch % 0x10000 != 0xfffe && // 0xfffe - 0x10fffe range  

  115.                     (ch <= 0xfdd0 || ch >= 0xfdef) && // 0xfdd0 - 0xfdef  

  116.                     (ch > 0x1F || ch == 0x9 || ch == 0xa || ch == 0xd)) {  

  117.   

  118.                 retval.append(ch);  

  119.             }  

  120.         }  

  121.   

  122.         return retval.toString();  

  123.     }  

  124.   

  125.     @Override  

  126.     public void putNext(Tuple t) throws IOException {  

  127.   

  128.         final SolrInputDocument doc = new SolrInputDocument();  

  129.   

  130.         final ResourceFieldSchema[] fields = schema.getFields();  

  131.         int docfields = 0;  

  132.   

  133.         for (int i = 0; i < fields.length; i++) {  

  134.             final Object value = t.get(i);  

  135.   

  136.             if (value != null) {  

  137.                 docfields++;  

  138.                 doc.addField(fields[i].getName().trim(), stripNonCharCodepoints(value.toString()));  

  139.             }  

  140.   

  141.         }  

  142.   

  143.         try {  

  144.             if (docfields > 0)  

  145.                 writer.write(null, doc);  

  146.         } catch (InterruptedException e) {  

  147.             Thread.currentThread().interrupt();  

  148.             return;  

  149.         }  

  150.   

  151.     }  

  152.   

  153. }  



Pig腳本以下: 

  1. --註冊依賴文件的jar包  

  2. REGISTER ./dependfiles/tools.jar;  

  3.   

  4. --註冊solr相關的jar包  

  5. REGISTER  ./solrdependfiles/pigudf.jar;   

  6. REGISTER  ./solrdependfiles/solr-core-4.10.2.jar;  

  7. REGISTER  ./solrdependfiles/solr-solrj-4.10.2.jar;  

  8. REGISTER  ./solrdependfiles/httpclient-4.3.1.jar  

  9. REGISTER  ./solrdependfiles/httpcore-4.3.jar  

  10. REGISTER  ./solrdependfiles/httpmime-4.3.1.jar  

  11. REGISTER  ./solrdependfiles/noggit-0.5.jar  

  12.   

  13.   

  14. --加載HDFS數據,並定義scheaml  

  15. a = load '/tmp/data' using PigStorage(',') as (sword:chararray,scount:int);  

  16.   

  17. --存儲到solr中,並提供solr的ip地址和端口號  

  18. store d into '/user/search/solrindextemp'  using com.pig.support.solr.SolrStore('http://localhost:8983/solr/collection1','collection1');  

  19. ~                                                                                                                                                              

  20. ~                                                                        

  21. ~                                 



配置成功以後,咱們就能夠運行程序,加載HDFS上數據,通過計算處理以後,並將最終的結果,存儲到Solr之中,截圖以下: 






成功以後,咱們就能夠很方便的在solr中進行毫秒級別的操做了,例如各類各樣的全文查詢,過濾,排序統計等等! 一樣的方式,咱們也能夠將索引存儲在ElasticSearch中,關於如何使用Pig和ElasticSearch集成,散仙也會在後面的文章中介紹,敬請期待! 

相關文章
相關標籤/搜索