使用derby導入mongodb數據

先說下需求,公司使用oracle的Biee分析數據,Biee自己只支持關係數據庫的分析,沒法直接讀取mongodb的數據。網上搜索到https://blogs.oracle.com/dataintegration/entry/odi_mongodb_and_a_java java

裏面基本都介紹了,就是利用derby的table functions這個功能。這裏有個很是關鍵的jar,做用是取mongodbd的數據而後組裝成java sql的ResultSet,oracle網站裏面已經沒有了,我找了很久,給出連接:http://www.tuicool.com/articles/NvIFjasql

主要開發過程是先到derby裏面建一個tableFunctions: mongodb

create function employeeTable()
returns table(id int,
name varchar(255),
age int) language java parameter style DERBY_JDBC_RESULT_SET
no sql
external name 'xx.xx.EmployeeTable.read';
而後就是java代碼了,讀取mongodb的數據:

...
// 使用collection的find方法查找document
DBCursor cursor = collection.find();
ResultSet set = MongodbTableFunction.load(cursor);
...
public class MongodbTableFunction extends EnumeratorTableFunction {

	public MongodbTableFunction() throws SQLException {
		super(new String[] { "title", "author" });
	}

	public static ResultSet load(DBCursor cursor) throws SQLException {
		MongodbTableFunction mtf = new MongodbTableFunction();
		mtf.setEnumeration(cursor);

		return mtf;
	}

	public String[] makeRow(Object obj) throws SQLException {
		int col = 0;
		String[] row = new String[getColumnCount()];
		BSONObject bson = (BSONObject)JSON.parse(obj.toString());
		
		row[col++] = (String) bson.get("title");
		row[col++] = (String) bson.get("author");

		return row;
	}
}
EnumeratorTableFunction 就是某大神的封裝的類。而後打成jar包。另外注意的一點是須要把咱們寫的jar路徑放到classpath裏面去,若是使用ij,能夠直接編輯ij的腳本在它的LOCALCLASSPATH裏面加上jar的路徑,這樣ij裏面執行table functions就沒有問題了。
相關文章
相關標籤/搜索