메뉴 건너뛰기

Bigdata, Semantic IoT, Hadoop, NoSQL

Bigdata, Hadoop ecosystem, Semantic IoT등의 프로젝트를 진행중에 습득한 내용을 정리하는 곳입니다.
필요한 분을 위해서 공개하고 있습니다. 문의사항은 gooper@gooper.com로 메일을 보내주세요.


$match에서 집계 대상을 선정하고 $group에서 그룹핑하는 컬럼을 지정한다.

최종적으로 결과에 포함시킬 컬럼은 $project에서 지정한다(값이 1이면 최종 결과에 포함되고 0이면 포함하지 않음)


// MongoDB연결
		try {
			mongoClient = new MongoClient(new ServerAddress(db_server, Integer.parseInt(db_port)));
			db = mongoClient.getDB(db_name);
			table = db.getCollection(collection_name);
		} catch (Exception ex) {
			log.debug("MongoDB connection error : "+ex.getMessage());
			if(db != null) {
				db.cleanCursors(true);
				db = null;				
			}
			if(table != null) {table = null;}
			if(mongoClient != null ) {
				mongoClient.close();
			}
			throw ex;
		} 

// 리턴 값
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
// 집계 수행(ty=4이고 _uri가 "TicketCount/status/CONTENT_INST"포함하며 ct가 지금부터 5분전에 해당되는 data에 대해서..)
		DBObject match = new BasicDBObject();  //"$match", new BasicDBObject("ct", new BasicDBObject("$gte", "20161213T160000")));
		match.put("ty",4);
		match.put("_uri", new BasicDBObject("$regex", "TicketCount/status/CONTENT_INST"));
		//match.put("ct", new BasicDBObject("$gte", "20161213T160000"));
		long nowDate = new Date().getTime();
		long newDate = nowDate-(5*60*1000);
		
		match.put("ct", new BasicDBObject("$gte", Utils.dateFormat.format((new Date(newDate)))));

		//Forming Group parts(cr컬럼을 기준으로 grouping하고 con값을 sum하여 sum_con컬럼으로 담는다)
		DBObject group = new BasicDBObject();
		group.put("_id", "$cr");
		group.put("sum_con", new BasicDBObject("$sum", "$con"));
		//group.put("sum_con", new BasicDBObject("$sum", 1));

		//Forming Project parts(최종적으로 _id값을 cr컬럼으로 뽑아내고, _id는 뽑아내지 않으며 sum_con은 결과로서 뽑아낸다)
		DBObject project = new BasicDBObject();
		project.put("cr","$_id");
		project.put("_id",0);
		project.put("sum_con", 1);

		try {
			AggregationOutput output = db.getCollection("resource").aggregate(
						new BasicDBObject("$match", match), 
						new BasicDBObject("$group", group),
						new BasicDBObject("$project", project)
						);

			//System.out.println("output : "+output.getCommandResult().getString("result"));
			Iterator<DBObject> itr = output.results().iterator();
			
			while(itr.hasNext()) {
				DBObject dbObject =itr.next();
				//JSONObject jsonObject = JSONObject.fromObject(dbObject.toString());
				//Map<String, String> newMap = castMap(dbObject.toMap(), String.class, String.class);
				@SuppressWarnings("unchecked")
				Map<String, String> newMap = makeStringMap(dbObject.toMap());
				list.add(newMap);
	        }	
			
			return list;
		} catch (Exception e) {
			log.debug("Exception : "+e.getMessage());
			throw e;
		} finally {
			if(db != null) {
				db.cleanCursors(true);
				table = null;
				db = null;				
			}
			if(mongoClient != null ) {
				mongoClient.close();
			}
		}


번호 제목 글쓴이 날짜 조회 수
23 [DBeaver 4.3.0]import/export시 "Client home is not specified for connection" 오류발생시 조치사항 총관리자 2017.12.21 753
22 mongodb aggregation query를 Java code로 변환한 샘플 총관리자 2016.12.15 777
21 update 샘플 총관리자 2018.03.12 810
20 Current heap configuration for MemStore and BlockCache exceeds the threshold required for successful cluster operation 총관리자 2017.07.18 892
19 column family삭제시 Column family 'delete' does not exist오류 발생하는 경우 총관리자 2014.04.14 932
18 postgresql-9.4에서 FATAL: remaining connection slots are reserved for non-replication superuser connections가 나올때 조치 총관리자 2018.08.16 945
17 HBase 0.98.12(1.2.5) for hadoop2 설치-5대에 완전분산모드 (HDFS HA상테) 총관리자 2015.04.29 1047
16 Ubuntu 16.04 LTS에 MariaDB 10.1설치 및 포트변경 및 원격접속 허용 총관리자 2017.05.01 1081
15 mysql에서 외부 디비를 커넥션할 경우 접속 속도가 느려질때 총관리자 2017.06.30 1083
14 hbase shell 필드 검색 방법 총관리자 2015.05.24 1900
13 hbase에 필요한 jar들 구퍼 2013.04.01 2100
12 AIX 7.1에 MariaDB 10.2 소스 설치 총관리자 2016.09.24 2372
11 hbase shell에서 컬럼값 검색하기(SingleColumnValueFilter이용) 총관리자 2014.04.25 2448
10 HBase, BigTable, Cassandra Schema Design file 구퍼 2013.03.15 2509
9 HBase 설치하기 – Pseudo-distributed file 구퍼 2013.03.12 2647
8 org.apache.hadoop.hbase.PleaseHoldException: Master is initializing 구퍼 2013.03.15 2668
7 mysql-server 기동시 Do you already have another mysqld server running on port 오류 발생할때 확인및 조치방법 총관리자 2017.05.14 2674
6 Hbase Shell 명령 정리 구퍼 2013.04.01 3170
5 HBase 설치하기 – Fully-distributed 구퍼 2013.03.12 3548
4 HBASE Client API : 기본 기능 정리 file 구퍼 2013.04.01 3554

A personal place to organize information learned during the development of such Hadoop, Hive, Hbase, Semantic IoT, etc.
We are open to the required minutes. Please send inquiries to gooper@gooper.com.

위로