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);
1
2
3
4
5
6
7
8
9
10
11
12
输出: 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);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
http://stackoverflow.com/questions/714108/cartesian-product-of-arbitrary-sets-in-java
3、结果如下
数据集合的大小为:4*4*4*4*4=1024;