메뉴 건너뛰기

Cloudera, BigData, Semantic IoT, Hadoop, NoSQL

Cloudera CDH/CDP 및 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();
			}
		}


번호 제목 날짜 조회 수
341 php auction 프로그램 2017.05.14 236
340 mysql-server 기동시 Do you already have another mysqld server running on port 오류 발생할때 확인및 조치방법 2017.05.14 2854
339 webid에서 google처럼 검색할 수 있도록 하는 프로그램 2017.05.16 133
338 fuseki용 config-examples.ttl 예시 내용 2017.05.17 746
337 Ubuntu 16.04 LTS에서 사이트에 무료인증서를 이용하여 SSL적용 file 2017.05.23 456
336 Ubuntu 16.04LTS 설치후 초기에 주어야 하는 작업(php, apache, mariadb설치및 OS보안설정등) file 2017.05.23 5636
335 Ubuntu 16.04 LTS에서 sendmail설치및 설정(수신,발신 가능)및 메일서버 만들기 2017.05.23 1711
334 [u-Auctions]목록이 1개만 나오는 문제 2017.05.29 138
333 Eclipse 에서 bitbucket.org 연동 하기 file 2017.06.08 447
332 sendmail전송시 421 4.3.0 collect: Cannot write ./dfv5BA2EBS010579 (bfcommit, uid=0, gid=114): No such file or directory 발생시 조치사항 2017.06.11 756
331 sendmail + dovecot(pop3) + saslauthd 설치 2017.06.11 396
330 [dovecot]dovecot restart할때 root@gsda4:/usr/lib/dovecot# service dovecot restart 오류 발생시 조치사항 2017.06.12 822
329 시맨틱 관련 논문 모음 사이트 2017.06.13 161
328 숭실대 교수님등 강의영상(바이오데이터마이닝, 빅데이터분산컴퓨팅, 컴퓨터 그래픽스, 데이터베이스응용및 프로그램밍, 데이터베이스, 의생명영상처리, 웹그로그래밍, 데이터마이닝, 컴퓨터구조) file 2017.06.13 318
327 [Dovecot] -ERR [SYS/PERM] Permission denied 2017.06.13 368
326 .git폴더를 삭제하고 다시 git에 추가하고 서버에 반영하는 방법 2017.06.19 4551
325 원격 리포지토리에서 최초 clone시 Permission denied (publickey). 오류발생시 조치사항 2017.06.20 961
324 lagom을 이용한 샘플 경매 프로그램 실행방법 2017.06.20 450
323 Ubuntu에서 sbt및 scala설치하기 2017.06.20 236
322 VPS에서는 root로 실행해도 swap파일을 만들지 못하게 만들어 두었지만 swap파일을 생성하는 방법 2017.06.20 322
위로