这里,我给出了一个DataLoader接口的实现,数据存储在MongoDB中,具体实现对应于MongoDataLoader类,代码如下所示:
- package org.shirdrn.solr.tools;
- import Java.io.Serializable;
- import java.util.Map;
- import com.mongodb.BasicDBObject;
- import com.mongodb.DBCollection;
- import com.mongodb.DBCursor;
- import com.mongodb.DBObject;
- import com.mongodb.Mongo;
- import com.mongodb.MongoException;
- /**
- * Load data being indexed from Mongo DB.
- *
- * @author shirdrn
- * @date 2011-12-07
- */
- public class MongoDataLoader implements DataLoader {
- private MongoConfig mongoConfig;
- private DBCollection collection;
- private Map<Object, Object> conditions;
- private DBCursor cursor;
- private int recordCount;
- public MongoDataLoader(MongoConfig mongoConfig, Map<Object, Object> conditions) {
- super();
- this.mongoConfig = mongoConfig;
- this.conditions = conditions;
- initialize();
- }
- private void initialize() {
- DBObject q = new BasicDBObject();
- if(conditions!=null) {
- q.putAll(conditions);
- }
- try {
- if(collection==null) {
- collection = MongoHelper.newHelper(mongoConfig).getCollection(mongoConfig.collectionName);
- }
- cursor = collection.find(q);
- recordCount = cursor.size();
- } catch (MongoException e) {
- e.printStackTrace();
- }
- }
- @SuppressWarnings("unchecked")
- @Override
- public Map<Object, Object> fetchOne() {
- Map<Object, Object> m = null;
- try {
- if(cursor.hasNext()) {
- m = cursor.next().toMap();
- m.put("id", m.get("_id").toString());
- } else {
- cursor.close();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return m;
- }
- @Override
- public int getRecordCount() {
- return recordCount;
- }
- public static class MongoConfig implements Serializable {
- private static final long serialVersionUID = -3028092758346115702L;
- private String host;
- private int port;
- private String dbname;
- private String collectionName;
- public MongoConfig(String host, int port, String dbname, String collectionName) {
- super();
- this.host = host;
- this.port = port;
- this.dbname = dbname;
- this.collectionName = collectionName;
- }
- @Override
- public boolean equals(Object obj) {
- MongoConfig other = (MongoConfig) obj;
- return host.equals(other.host) && port==other.port
- && dbname.equals(other.dbname) && collectionName.equals(other.collectionName);
- }
- }
- static class MongoHelper {
- private static Mongo mongo;
- private static MongoHelper helper;
- private MongoConfig mongoConfig;
- private MongoHelper(MongoConfig mongoConfig) {
- super();
- this.mongoConfig = mongoConfig;
- }
- public synchronized static MongoHelper newHelper(MongoConfig mongoConfig) {
- try {
- if(helper==null) {
- helper = new MongoHelper(mongoConfig);
- mongo = new Mongo(mongoConfig.host, mongoConfig.port);
- Runtime.getRuntime().addShutdownHook(new Thread() {
- @Override
- public void run() {
- if(mongo!=null) {
- mongo.close();
- }
- }
- });
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return helper;
- }
- public DBCollection getCollection(String collectionName) {
- DBCollection c = null;
- try {
- c = mongo.getDB(mongoConfig.dbname).getCollection(collectionName);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return c;
- }
- }
- }
在我们要实现一个真正提供与Solr搜索服务器进行交互服务的AbstractPostServer之前,我们先看一下,都需要提供哪些基本服务,这是在PostService接口中定义的。PostService接口中定义了管理索引最基本的功能,代码如下所示:
- package org.shirdrn.solr.tools;
- import java.io.IOException;
- import java.io.OutputStream;
- public interface PostService {
- public void commit(OutputStream output) throws IOException;
- public void optimize(OutputStream output) throws IOException;
- public void postUpdate(boolean autoOptimize) throws Exception;
- public void postDelete(boolean autoOptimize) throws Exception;
- public int getPostCount();
- }
- package org.shirdrn.solr.tools;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Map.Entry;
- import net.sf.json.JSONObject;
- /**
- * Json style post server. Actually it represents
- * a proxy server of Solr search server, and is responsible for
- * managing indices, such as indexing, deleting some document, etc.
- *
- * @author shirdrn
- * @date 2011-12-07
- */
- public class JsonPostServer extends AbstractPostServer implements PostService {
- private int postCount;
- private String responseMessage = "OK";
- public JsonPostServer(PostConfig postConfig) {
- super(postConfig, null);
- }
- public JsonPostServer(PostConfig postConfig, DataLoader dataLoader) {
- super(postConfig, dataLoader);
- }
- @Override
- public void postUpdate(boolean autoOptimize) throws Exception {
- try {
- StringBuffer data = new StringBuffer("{");
- for(int i=0; i<dataLoader.getRecordCount(); i++) {
- Map<Object, Object> record = dataLoader.fetchOne();
- JSONObject op = new JSONObject();
- JSONObject doc = new JSONObject();
- if(record!=null) {
- Iterator<Entry<Object, Object>> iter = record.entrySet().iterator();
- JSONObject jo = new JSONObject();
- while(iter.hasNext()) {
- Entry<Object, Object> entry = iter.next();
- if(postConfig.getIndexFieldSet().contains(entry.getKey())) {
- if(postConfig.getFinalFieldSet().contains(entry.getKey())) {
- jo.put(entry.getKey(), entry.getValue().toString());
- } else {
- jo.put(entry.getKey(), purgeJsonSpecifiedCharacters(entry.getValue().toString()));
- }
- }
- }
- doc.put("doc", jo);
- op.put("add", doc);
- data.append(op.toString().substring(1, op.toString().length()-1));
- increment(i+1, dataLoader.getRecordCount(), data);
- }
- }
- if(autoOptimize) {
- optimize(System.out);
- }
- } catch (IOException e) {
- responseMessage = e.getMessage();
- }
- }
- private void increment(int i, int recordCount, StringBuffer data) throws IOException {
- ++postCount;
- if(i%postConfig.getMaxCommitCount()==0 || i==recordCount) {
- data.append("}");
- post(stringToStream(data.toString()), null, System.out);
- commit(System.out);
- if(i!=recordCount) {
- data.delete(0, data.length());
- data.append("{");
- }
- } else {
- data.append(",");
- }
- }
- private String purgeJsonSpecifiedCharacters(String data) {
- StringBuffer buffer = new StringBuffer();
- for (int i=0; i<data.length(); i++){
- switch (data.charAt(i)){
- case '\"':
- case '\\':
- case '/':
- case '\b':
- case '\f':
- case '\n':
- case '\r':
- case '\t':
- buffer.append(" ");
- break;
- default:
- buffer.append(data.charAt(i));
- }
- }
- return buffer.toString().trim();
- }
- @Override
- public void postDelete(boolean autoOptimize) throws Exception {
- try {
- StringBuffer data = new StringBuffer("{");
- for(int i=0; i<dataLoader.getRecordCount(); i++) {
- Map<Object, Object> record = dataLoader.fetchOne();
- JSONObject jo = new JSONObject();
- JSONObject op = new JSONObject();
- Iterator<Entry<Object, Object>> iter = record.entrySet().iterator();
- Entry<Object, Object> entry = iter.next();
- if(postConfig.getUniqueKey().equals(entry.getKey()) || entry.getKey().equals("query")) {
- jo.put(entry.getKey(), entry.getValue());
- op.put("delete", jo);
- data.append(op.toString().substring(1, op.toString().length()-1));
- increment(i+1, dataLoader.getRecordCount(), data);
- }
- }
- if(autoOptimize) {
- optimize(System.out);
- }
- } catch (IOException e) {
- responseMessage = e.getMessage();
- }
- }
- @Override
- public void commit(OutputStream output) throws IOException {
- JSONObject commit = new JSONObject();
- commit.put("commit", new JSONObject());
- post(stringToStream(commit.toString()), null, output);
- LOG.debug("Commit done: " + commit.toString());
- }
- @Override
- public void optimize(OutputStream output) throws IOException {
- JSONObject optimizer = new JSONObject();
- JSONObject jo = new JSONObject();
- jo.put("waitFlush", false);
- jo.put("waitSearcher", false);
- optimizer.put("optimize", jo);
- post(stringToStream(optimizer.toString()), null, output);
- LOG.debug("Optimize done: " + optimizer.toString());
- }
- @Override
- public String getResponseMessage() {
- return responseMessage;
- }
- @Override
- public int getPostCount() {
- return postCount;
- }
- }
