题记
在mysql,oracle等关系型数据库中,可以通过表之间的关联操作(join, left join, and)实现字段之间的关联操作。
而在mongo非关系型数据库中没有对应的接口。
为此,我们自身实现了1个Mongo db库中的多个collection之间的类笛卡尔操作。(这种需求,多少有些不合理)
1、需求:Mongo多个Collection之间的关联操作
输入: gatherList,
组成如下:
List <Object> la = Arrays.asList (new Object [] {'A', 'B', 'C', 'D'}); //1
List <Object> lb = Arrays.asList (new Object [] {1, 2, 3, 4}); //2
List <Object> lc = Arrays.asList (new Object [] {"百度", "小米", "谷歌", "Facebook"}); //3
List <Object> ld = Arrays.asList (new Object [] {"雷军", "乔布斯", "罗永浩", "罗胖子"}); ///4
List <Object> le = Arrays.asList (new Object [] {"微博", "微信", "陌陌", "脉脉"}); //5
List <List <Object>> gatherList = new ArrayList <List <Object>> ();
gatherList.add(la);
gatherList.add(lb);
gatherList.add(lc);
gatherList.add(ld);
gatherList.add(le);
输出: CartesianIterable dkRst
CartesianIterable dkRst = CartesianIteratorTest.dk_process_obj(gatherList);
原理:合集处理——笛卡尔迭代器实现,逐个遍历元素,形成一个笛卡尔集合。
参考:http://stackoverflow.com/questions/714108/cartesian-product-of-arbitrary-sets-in-java
2、关联结果入Mongodb。
void mongoInsertObj(CartesianIterable dkRst,
List labelNameList, int iGatherListSize)
输入:1) CartesianIterable dkRst, 笛卡尔结果。
2) List labelNameList,列名称集。
3) int iGatherListSize, 笛卡尔结果的组数,即 gatherList集的大小,等同于 列名称集的大小。
输出:空。
算法实现:集合拆分——以 gatherList集的大小为一组,对应一个document入库。
源码:
public static void mongoInsertObj(CartesianIterable<Object> dkRst,
List<String> labelNameList, int iGatherListSize)
throws UnknownHostException {
try {
/**** Connect to MongoDB ****/
// Since 2.10.0, uses MongoClient
MongoClient mongo = new MongoClient("110.20.12.41", 27017);
/**** Get database ****/
// if database doesn't exists, MongoDB will create it for you
DB db = mongo.getDB("data");
/**** Get collection / table from 'testdb' ****/
DBCollection table = db.getCollection(testCollName);
for (List <Object> lo: dkRst){
int iObjSize = lo.size();
BasicDBObject document = new BasicDBObject();
for (int i = 0; i < iObjSize; i+=iGatherListSize) {
//System.out.println("NtnbRisk.labelNameList[0] = " + NtnbRisk.labelNameList[0]);
for (int j = 0; j < iGatherListSize; j++) {
// create a document to store key and value
document.put(labelNameList.get(j), lo.get(i+j)); //1
}
table.insert(document);
}
}
http://stackoverflow.com/questions/714108/cartesian-product-of-arbitrary-sets-in-java
3、结果如下
数据集合的大小为:44444=1024;
作者:铭毅天下
转载请标明出处,原文地址:
http://blog.csdn.net/laoyang360/article/details/70946468