手机版
你好,游客 登录 注册
背景:
阅读新闻

开发更新Solr索引的工具

[日期:2012-05-05] 来源:Linux社区  作者:shirdrn [字体:大 中 小]

这里,我给出了一个DataLoader接口的实现,数据存储在MongoDB中,具体实现对应于MongoDataLoader类,代码如下所示:

  1. package org.shirdrn.solr.tools;  
  2.   
  3. import Java.io.Serializable;  
  4. import java.util.Map;  
  5.   
  6. import com.mongodb.BasicDBObject;  
  7. import com.mongodb.DBCollection;  
  8. import com.mongodb.DBCursor;  
  9. import com.mongodb.DBObject;  
  10. import com.mongodb.Mongo;  
  11. import com.mongodb.MongoException;  
  12.   
  13. /** 
  14.  * Load data being indexed from Mongo DB. 
  15.  *  
  16.  * @author shirdrn 
  17.  * @date   2011-12-07 
  18.  */  
  19. public class MongoDataLoader implements DataLoader {  
  20.       
  21.     private MongoConfig mongoConfig;  
  22.     private DBCollection collection;  
  23.     private Map<Object, Object> conditions;  
  24.     private DBCursor cursor;  
  25.     private int recordCount;  
  26.   
  27.     public MongoDataLoader(MongoConfig mongoConfig, Map<Object, Object> conditions) {  
  28.         super();  
  29.         this.mongoConfig = mongoConfig;  
  30.         this.conditions = conditions;  
  31.         initialize();  
  32.     }  
  33.   
  34.     private void initialize() {  
  35.         DBObject q = new BasicDBObject();  
  36.         if(conditions!=null) {  
  37.             q.putAll(conditions);  
  38.         }  
  39.         try {  
  40.             if(collection==null) {  
  41.                 collection = MongoHelper.newHelper(mongoConfig).getCollection(mongoConfig.collectionName);  
  42.             }  
  43.             cursor = collection.find(q);  
  44.             recordCount = cursor.size();  
  45.         } catch (MongoException e) {  
  46.             e.printStackTrace();  
  47.         }  
  48.     }  
  49.   
  50.     @SuppressWarnings("unchecked")  
  51.     @Override  
  52.     public Map<Object, Object> fetchOne() {  
  53.         Map<Object, Object> m = null;  
  54.         try {  
  55.             if(cursor.hasNext()) {  
  56.                 m = cursor.next().toMap();  
  57.                 m.put("id", m.get("_id").toString());  
  58.             } else {  
  59.                 cursor.close();  
  60.             }  
  61.         } catch (Exception e) {  
  62.             e.printStackTrace();  
  63.         }  
  64.         return m;  
  65.     }  
  66.   
  67.     @Override  
  68.     public int getRecordCount() {  
  69.         return recordCount;  
  70.     }  
  71.       
  72.     public static class MongoConfig implements Serializable {  
  73.         private static final long serialVersionUID = -3028092758346115702L;  
  74.         private String host;  
  75.         private int port;  
  76.         private String dbname;  
  77.         private String collectionName;  
  78.         public MongoConfig(String host, int port, String dbname, String collectionName) {  
  79.             super();  
  80.             this.host = host;  
  81.             this.port = port;  
  82.             this.dbname = dbname;  
  83.             this.collectionName = collectionName;  
  84.         }  
  85.         @Override  
  86.         public boolean equals(Object obj) {  
  87.             MongoConfig other = (MongoConfig) obj;  
  88.             return host.equals(other.host) && port==other.port  
  89.                 && dbname.equals(other.dbname) && collectionName.equals(other.collectionName);  
  90.         }  
  91.     }  
  92.       
  93.     static class MongoHelper {  
  94.         private static Mongo mongo;  
  95.         private static MongoHelper helper;  
  96.         private MongoConfig mongoConfig;  
  97.         private MongoHelper(MongoConfig mongoConfig) {  
  98.             super();  
  99.             this.mongoConfig = mongoConfig;  
  100.         }  
  101.         public synchronized static MongoHelper newHelper(MongoConfig mongoConfig) {  
  102.             try {  
  103.                 if(helper==null) {  
  104.                     helper = new MongoHelper(mongoConfig);  
  105.                     mongo = new Mongo(mongoConfig.host, mongoConfig.port);  
  106.                     Runtime.getRuntime().addShutdownHook(new Thread() {  
  107.                         @Override  
  108.                         public void run() {  
  109.                             if(mongo!=null) {  
  110.                                 mongo.close();  
  111.                             }  
  112.                         }  
  113.                     });  
  114.                 }  
  115.             } catch (Exception e) {  
  116.                 e.printStackTrace();  
  117.             }  
  118.             return helper;  
  119.         }             
  120.         public DBCollection getCollection(String collectionName) {  
  121.             DBCollection c = null;  
  122.             try {  
  123.                 c = mongo.getDB(mongoConfig.dbname).getCollection(collectionName);  
  124.             } catch (Exception e) {  
  125.                 e.printStackTrace();  
  126.             }  
  127.             return c;  
  128.         }     
  129.     }  
  130. }  
上面为了方便,定义了MongoConfig类封装了与MongoDB相关的一些数据,而MongoHelper类实现了与MongoDB数据库进行交互的一些操作。实际上,在打开一个DBCollection实例以后,便可以根据查询条件获取到查询结果集的一个游标(DBCursor),通过游标就可以迭代整个结果集的记录,亦即需要进行索引的数据。
在我们要实现一个真正提供与Solr搜索服务器进行交互服务的AbstractPostServer之前,我们先看一下,都需要提供哪些基本服务,这是在PostService接口中定义的。PostService接口中定义了管理索引最基本的功能,代码如下所示:
  1. package org.shirdrn.solr.tools;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.OutputStream;  
  5.   
  6.   
  7. public interface PostService {  
  8.     public void commit(OutputStream output) throws IOException;  
  9.     public void optimize(OutputStream output) throws IOException;  
  10.     public void postUpdate(boolean autoOptimize) throws Exception;  
  11.     public void postDelete(boolean autoOptimize) throws Exception;  
  12.     public int getPostCount();  
  13. }  
实现一个基于JSON数据格式的AbstractPostServer,需要继承自AbstractPostServer抽象类,同时实现接口PostService,对应的JsonPostServer实现类的代码如下所示:
  1. package org.shirdrn.solr.tools;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.OutputStream;  
  5. import java.util.Iterator;  
  6. import java.util.Map;  
  7. import java.util.Map.Entry;  
  8.   
  9. import net.sf.json.JSONObject;  
  10.   
  11. /** 
  12.  * Json style post server. Actually it represents 
  13.  * a proxy server of Solr search server, and is responsible for 
  14.  * managing indices, such as indexing, deleting some document, etc. 
  15.  *  
  16.  * @author shirdrn 
  17.  * @date   2011-12-07 
  18.  */  
  19. public class JsonPostServer extends AbstractPostServer implements PostService {  
  20.   
  21.     private int postCount;  
  22.     private String responseMessage = "OK";  
  23.       
  24.     public JsonPostServer(PostConfig postConfig) {  
  25.         super(postConfig, null);  
  26.     }  
  27.       
  28.     public JsonPostServer(PostConfig postConfig, DataLoader dataLoader) {  
  29.         super(postConfig, dataLoader);  
  30.     }  
  31.   
  32.     @Override  
  33.     public void postUpdate(boolean autoOptimize) throws Exception {  
  34.         try {  
  35.             StringBuffer data = new StringBuffer("{");  
  36.             for(int i=0; i<dataLoader.getRecordCount(); i++) {  
  37.                 Map<Object, Object> record = dataLoader.fetchOne();  
  38.                 JSONObject op = new JSONObject();  
  39.                 JSONObject doc = new JSONObject();  
  40.                 if(record!=null) {  
  41.                     Iterator<Entry<Object, Object>> iter = record.entrySet().iterator();  
  42.                     JSONObject jo = new JSONObject();  
  43.                     while(iter.hasNext()) {  
  44.                         Entry<Object, Object> entry = iter.next();  
  45.                         if(postConfig.getIndexFieldSet().contains(entry.getKey())) {  
  46.                             if(postConfig.getFinalFieldSet().contains(entry.getKey())) {  
  47.                                 jo.put(entry.getKey(), entry.getValue().toString());  
  48.                             } else {  
  49.                                 jo.put(entry.getKey(), purgeJsonSpecifiedCharacters(entry.getValue().toString()));  
  50.                             }  
  51.                         }  
  52.                     }  
  53.                     doc.put("doc", jo);  
  54.                     op.put("add", doc);  
  55.                     data.append(op.toString().substring(1, op.toString().length()-1));  
  56.                     increment(i+1, dataLoader.getRecordCount(), data);  
  57.                 }  
  58.             }  
  59.             if(autoOptimize) {  
  60.                 optimize(System.out);  
  61.             }  
  62.         } catch (IOException e) {  
  63.             responseMessage = e.getMessage();  
  64.         }  
  65.     }  
  66.       
  67.     private void increment(int i, int recordCount, StringBuffer data) throws IOException {  
  68.         ++postCount;  
  69.         if(i%postConfig.getMaxCommitCount()==0 || i==recordCount) {  
  70.             data.append("}");  
  71.             post(stringToStream(data.toString()), null, System.out);  
  72.             commit(System.out);  
  73.             if(i!=recordCount) {  
  74.                 data.delete(0, data.length());  
  75.                 data.append("{");  
  76.             }  
  77.         } else {  
  78.             data.append(",");  
  79.         }  
  80.     }  
  81.       
  82.     private String purgeJsonSpecifiedCharacters(String data) {  
  83.         StringBuffer buffer = new StringBuffer();  
  84.         for (int i=0; i<data.length(); i++){  
  85.             switch (data.charAt(i)){  
  86.             case '\"':  
  87.             case '\\':  
  88.             case '/':  
  89.             case '\b':  
  90.             case '\f':  
  91.             case '\n':  
  92.             case '\r':  
  93.             case '\t':  
  94.                 buffer.append(" ");  
  95.                 break;  
  96.             default:  
  97.                 buffer.append(data.charAt(i));  
  98.             }  
  99.         }  
  100.         return buffer.toString().trim();  
  101.     }  
  102.       
  103.     @Override  
  104.     public void postDelete(boolean autoOptimize) throws Exception {  
  105.         try {  
  106.             StringBuffer data = new StringBuffer("{");  
  107.             for(int i=0; i<dataLoader.getRecordCount(); i++) {  
  108.                 Map<Object, Object> record = dataLoader.fetchOne();  
  109.                 JSONObject jo = new JSONObject();  
  110.                 JSONObject op = new JSONObject();  
  111.                 Iterator<Entry<Object, Object>> iter = record.entrySet().iterator();  
  112.                 Entry<Object, Object> entry = iter.next();  
  113.                 if(postConfig.getUniqueKey().equals(entry.getKey()) || entry.getKey().equals("query")) {  
  114.                     jo.put(entry.getKey(), entry.getValue());  
  115.                     op.put("delete", jo);  
  116.                     data.append(op.toString().substring(1, op.toString().length()-1));  
  117.                     increment(i+1, dataLoader.getRecordCount(), data);  
  118.                 }  
  119.             }  
  120.             if(autoOptimize) {  
  121.                 optimize(System.out);  
  122.             }  
  123.         } catch (IOException e) {  
  124.             responseMessage = e.getMessage();  
  125.         }  
  126.     }  
  127.   
  128.     @Override  
  129.     public void commit(OutputStream output) throws IOException {  
  130.         JSONObject commit = new JSONObject();  
  131.         commit.put("commit", new JSONObject());  
  132.         post(stringToStream(commit.toString()), null, output);  
  133.         LOG.debug("Commit done: " + commit.toString());  
  134.     }  
  135.       
  136.     @Override  
  137.     public void optimize(OutputStream output) throws IOException {  
  138.         JSONObject optimizer = new JSONObject();  
  139.         JSONObject jo = new JSONObject();  
  140.         jo.put("waitFlush", false);  
  141.         jo.put("waitSearcher", false);  
  142.         optimizer.put("optimize", jo);  
  143.         post(stringToStream(optimizer.toString()), null, output);  
  144.         LOG.debug("Optimize done: " + optimizer.toString());  
  145.     }  
  146.   
  147.     @Override  
  148.     public String getResponseMessage() {  
  149.         return responseMessage;  
  150.     }  
  151.   
  152.     @Override  
  153.     public int getPostCount() {  
  154.         return postCount;         
  155.     }  
  156.   
  157. }  
linux
相关资讯       Solr 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款