List of usage examples for com.mongodb QueryBuilder and
@SuppressWarnings("unchecked") public QueryBuilder and(final DBObject... ands)
From source file:it.sayservice.platform.smartplanner.otp.OTPManager.java
License:Apache License
private List<AlertDelay> getAlertDelay(String router, String routeId, String tripId, boolean now) { QueryBuilder qb = new QueryBuilder(); qb = qb.start("transport.routeId").is(routeId).and("transport.tripId").is(tripId); if (now) {/* w w w . ja va2 s .c o m*/ long time = System.currentTimeMillis(); qb = qb.and("from").lessThanEquals(time); qb = qb.and("to").greaterThanEquals(time); } List<AlertDelay> delays = (List) storage.getObjectsByQuery( mongoRouterMapper.getMongoTemplateMap().get(router), qb.get(), Constants.ALERT_DELAYS, AlertDelay.class, "delay"); return delays; }
From source file:it.sayservice.platform.smartplanner.otp.OTPManager.java
License:Apache License
private List<AlertDelay> getAlertDelay(String router, String tripId, boolean now) { QueryBuilder qb = new QueryBuilder(); qb = qb.start("transport.tripId").is(tripId); if (now) {//ww w. j a v a 2 s .co m long time = System.currentTimeMillis(); qb = qb.and("from").lessThanEquals(time); qb = qb.and("to").greaterThanEquals(time); } List<AlertDelay> delays = (List) storage.getObjectsByQuery( mongoRouterMapper.getMongoTemplateMap().get(router), qb.get(), Constants.ALERT_DELAYS, AlertDelay.class, "delay"); return delays; }
From source file:it.sayservice.platform.smartplanner.otp.OTPManager.java
License:Apache License
private List<TripSchedule> getSchedule(String router, String agencyId, String routeId, int day, String date, String collectionName, boolean symbolic) { QueryBuilder qb = QueryBuilder.start(); if (symbolic) { qb.and("symbolicRouteIds").is(routeId); } else {/*w w w. j a v a 2 s .co m*/ qb = qb.and("routeId").is(routeId); } qb = qb.and("agencyId").is(agencyId); qb = qb.and("days").is(day); qb = qb.and("daysRemoved").notEquals(date); qb = qb.and("fromDate").lessThanEquals(date); qb = qb.and("toDate").greaterThanEquals(date); List<TripSchedule> schedules = (List) storage.getObjectsByQuery( mongoRouterMapper.getMongoTemplateMap().get(router), qb.get(), collectionName, TripSchedule.class, "routeId"); qb = QueryBuilder.start(); if (symbolic) { qb.and("symbolicRouteIds").is(routeId); } else { qb = qb.and("routeId").is(routeId); } qb = qb.and("agencyId").is(agencyId); qb = qb.and("daysAdded").is(date); qb = qb.and("fromDate").lessThanEquals(date); qb = qb.and("toDate").greaterThanEquals(date); List<TripSchedule> addedSchedules = (List) storage.getObjectsByQuery( mongoRouterMapper.getMongoTemplateMap().get(router), qb.get(), collectionName, TripSchedule.class, "routeId"); for (TripSchedule toCheck : addedSchedules) { if (!schedules.contains(toCheck)) { schedules.add(toCheck); } } qb = QueryBuilder.start(); if (symbolic) { qb.and("symbolicRouteIds").is(routeId); qb = qb.and("agencyId").is(agencyId); qb = qb.and("daysAdded").is(date); qb = qb.and("fromDate").lessThanEquals(date); qb = qb.and("toDate").greaterThanEquals(date); QueryBuilder fb = QueryBuilder.start(); fb = fb.and("times").is("1"); fb = fb.and("order").is("1"); List<TripSchedule> toRemove = Lists.newArrayList(); for (TripSchedule ts : schedules) { qb = QueryBuilder.start(); qb = qb.and("agencyId").is(agencyId); qb = qb.and("tripId").is(ts.getTripId()); List<AnnotatedTrip> annotatedTrips = (List) storage.getObjectsByQuery( mongoRouterMapper.getMongoTemplateMap().get(router), qb.get(), Constants.ANNOTATED_TRIPS, AnnotatedTrip.class, null, fb.get()); if (!annotatedTrips.isEmpty()) { try { List<String> times = (List) annotatedTrips.get(0).getTimes(); ts.setTimes(times.toArray(new String[times.size()])); ts.setOrder(annotatedTrips.get(0).getOrder()); } catch (Exception e) { e.printStackTrace(); } } else { System.err.println("Annotated trip not found for " + ts.getTripId()); toRemove.add(ts); } } schedules.removeAll(toRemove); } Collections.sort(schedules); return schedules; }
From source file:it.sayservice.platform.smartplanner.otp.OTPStorage.java
License:Apache License
public Object getObjectByFields(MongoTemplate template, Map<String, Object> map, String collectionName, Class destinationClass) { DBCollection collection = template.getCollection(collectionName); QueryBuilder qb = QueryBuilder.start(); for (String key : map.keySet()) { qb = qb.and(key).is(map.get(key)); }/* ww w . j a va 2s . co m*/ BasicDBObject dbObject = (BasicDBObject) collection.findOne(qb.get()); if (dbObject != null) { dbObject.remove("_id"); ObjectMapper mapper = new ObjectMapper(); Object result = mapper.convertValue(dbObject, destinationClass); return result; } else { return null; } }
From source file:it.sayservice.platform.smartplanner.otp.OTPStorage.java
License:Apache License
public List<Object> getObjectsByFields(MongoTemplate template, Map<String, Object> map, String collectionName, Class destinationClass, String orderBy) { DBCollection collection = template.getCollection(collectionName); List<Object> result = new ArrayList<Object>(); QueryBuilder qb = QueryBuilder.start(); for (String key : map.keySet()) { qb = qb.and(key).is(map.get(key)); }//w w w . j av a 2 s. c o m DBCursor cursor = collection.find(qb.get()); if (orderBy != null) { BasicDBObject sb = new BasicDBObject(); sb.put(orderBy, 1); cursor = cursor.sort(sb); } while (cursor.hasNext()) { BasicDBObject dbObject = (BasicDBObject) cursor.next(); dbObject.remove("_id"); ObjectMapper mapper = new ObjectMapper(); mapper.configure(Feature.FAIL_ON_UNKNOWN_PROPERTIES, false); Object res = mapper.convertValue(dbObject, destinationClass); result.add(res); } return result; }
From source file:kina.examples.java.ReadingCellFromMongoDB.java
License:Apache License
public static void doMain(String[] args) { String job = "java:readingCellFromMongoDB"; String host = "127.0.0.1:27017"; String database = "test"; String inputCollection = "input"; // Creating the Kina Context where args are Spark Master and Job Name ContextProperties p = new ContextProperties(args); MongoKinaContext kinaContext = new MongoKinaContext(p.getCluster(), job, p.getSparkHome(), p.getJars()); QueryBuilder query = QueryBuilder.start(); query.and("number").greaterThan(27).lessThan(30); BSONObject bsonSort = new BasicBSONObject(); bsonSort.put("number", 1); BSONObject bsonFields = new BasicBSONObject(); bsonFields.put("number", 1); bsonFields.put("text", 1); bsonFields.put("_id", 0); MongoKinaConfig inputConfigEntity = MongoConfigFactory.createMongoDB().host(host).database(database) .collection(inputCollection).createInputSplit(false).filterQuery(query).sort(bsonSort) .fields(bsonFields).initialize(); RDD inputRDDEntity = kinaContext.mongoRDD(inputConfigEntity); LOG.info("count : " + inputRDDEntity.count()); LOG.info("prints first cell : " + inputRDDEntity.first()); kinaContext.stop();/*from w ww . j av a 2 s. co m*/ }
From source file:net.atos.entng.statistics.services.StatisticsServiceMongoImpl.java
License:Open Source License
private void getStatistics(final List<String> schoolIds, final JsonObject params, final Handler<Either<String, JsonArray>> handler, boolean isExport) { if (schoolIds == null || schoolIds.isEmpty()) { throw new IllegalArgumentException("schoolIds is null or empty"); }//w w w .j a v a2 s. com String indicator = params.getString(PARAM_INDICATOR); Long start = (Long) params.getNumber(PARAM_START_DATE); Long end = (Long) params.getNumber(PARAM_END_DATE); boolean isActivatedAccountsIndicator = STATS_FIELD_ACTIVATED_ACCOUNTS.equals(indicator); boolean isAccessIndicator = TRACE_TYPE_SVC_ACCESS.equals(indicator); String groupedBy = isAccessIndicator ? "module/structures/profil" : "structures/profil"; final QueryBuilder criteriaQuery = QueryBuilder.start(STATS_FIELD_GROUPBY).is(groupedBy) .and(STATS_FIELD_DATE).greaterThanEquals(formatTimestamp(start)).lessThan(formatTimestamp(end)) .and(indicator).exists(true); String module = params.getString(PARAM_MODULE); boolean moduleIsEmpty = module == null || module.trim().isEmpty(); boolean isAccessAllModules = isAccessIndicator && moduleIsEmpty; if (isAccessIndicator && !moduleIsEmpty) { criteriaQuery.and(MODULE_ID).is(module); } if (schoolIds.size() > 1) { criteriaQuery.and(STRUCTURES_ID).in(schoolIds); } else { criteriaQuery.and(STRUCTURES_ID).is(schoolIds.get(0)); // When getting data for only one module, a "find" is enough (no need to aggregate data) if (!isExport && !isAccessAllModules) { JsonObject projection = new JsonObject(); projection.putNumber("_id", 0).putNumber(indicator, 1).putNumber(PROFILE_ID, 1) .putNumber(STATS_FIELD_DATE, 1); if (isActivatedAccountsIndicator) { projection.putNumber(STATS_FIELD_ACCOUNTS, 1); } mongo.find(collection, MongoQueryBuilder.build(criteriaQuery), sortByDateProfile, projection, MongoDbResult.validResultsHandler(handler)); return; } } // Aggregate data final JsonObject aggregation = new JsonObject(); JsonArray pipeline = new JsonArray(); aggregation.putString("aggregate", collection).putBoolean("allowDiskUse", true).putArray("pipeline", pipeline); pipeline.addObject(new JsonObject().putObject("$match", MongoQueryBuilder.build(criteriaQuery))); JsonObject id = new JsonObject().putString(PROFILE_ID, "$" + PROFILE_ID); if (isAccessAllModules && !isExport) { // Case : get JSON data for indicator "access to all modules" id.putString(MODULE_ID, "$" + MODULE_ID); } else { id.putString(STATS_FIELD_DATE, "$" + STATS_FIELD_DATE); } JsonObject group = new JsonObject().putObject("_id", id).putObject(indicator, new JsonObject().putString("$sum", "$" + indicator)); if (isActivatedAccountsIndicator) { group.putObject(STATS_FIELD_ACCOUNTS, new JsonObject().putString("$sum", "$" + STATS_FIELD_ACCOUNTS)); } JsonObject groupBy = new JsonObject().putObject("$group", group); pipeline.addObject(groupBy); QueryBuilder projection = QueryBuilder.start("_id").is(0).and(PROFILE_ID).is("$_id." + PROFILE_ID); if (isActivatedAccountsIndicator) { projection.and(STATS_FIELD_ACCOUNTS).is(1); } if (!isExport) { projection.and(indicator).is(1); if (isAccessAllModules) { projection.and(MODULE_ID).is("$_id." + MODULE_ID); } else { projection.and(STATS_FIELD_DATE).is("$_id." + STATS_FIELD_DATE); } // Sum stats for all structure_ids pipeline.addObject(new JsonObject().putObject("$project", MongoQueryBuilder.build(projection))); } else { // Projection : keep 'yyyy-MM' from 'yyyy-MM-dd HH:mm.ss.SSS' DBObject dateSubstring = new BasicDBObject(); BasicDBList dbl = new BasicDBList(); dbl.add("$_id." + STATS_FIELD_DATE); dbl.add(0); dbl.add(7); dateSubstring.put("$substr", dbl); projection.and(STATS_FIELD_DATE).is(dateSubstring).and("indicatorValue").is("$" + indicator); // Replace indicatorName by label "indicatorValue", so that the mustache template can be generic JsonObject sort = sortByStructureDateProfile; // Export stats for each structure_id id.putString(STRUCTURES_ID, "$" + STRUCTURES_ID); projection.and(STRUCTURES_ID).is("$_id." + STRUCTURES_ID); if (isAccessIndicator) { if (isAccessAllModules) { sort = sort.copy().putNumber(MODULE_ID, 1); } // Export stats for each module_id id.putString(MODULE_ID, "$" + MODULE_ID); projection.and(MODULE_ID).is("$_id." + MODULE_ID); } pipeline.addObject(new JsonObject().putObject("$project", MongoQueryBuilder.build(projection))); pipeline.addObject(new JsonObject().putObject("$sort", sort)); } mongo.command(aggregation.toString(), new Handler<Message<JsonObject>>() { @Override public void handle(Message<JsonObject> message) { if ("ok".equals(message.body().getString("status")) && message.body().getObject("result", new JsonObject()).getInteger("ok") == 1) { JsonArray result = message.body().getObject("result").getArray("result"); handler.handle(new Either.Right<String, JsonArray>(result)); } else { String error = message.body().toString(); handler.handle(new Either.Left<String, JsonArray>(error)); } } }); }
From source file:net.jimj.automaton.commands.NoteCommand.java
License:Open Source License
protected void findNotes(User to) { QueryBuilder builder = new QueryBuilder(); builder.or(new BasicDBObject(NOTE_TO, to.getNick().toLowerCase()), new BasicDBObject(NOTE_TO, to.getRealName())); builder.and(new BasicDBObject(NOTE_DELIVERED, false)); DBCursor noteCursor = notes.find(builder.get()); if (noteCursor == null) { return;/*ww w . j a v a 2s . co m*/ } while (noteCursor.hasNext()) { DBObject noteObj = noteCursor.next(); String from = (String) noteObj.get(NOTE_FROM); String note = (String) noteObj.get(NOTE_NOTE); long when = (long) noteObj.get(NOTE_WHEN); StringBuilder noteMessage = new StringBuilder(to.getNick()).append(" you have a note from "); noteMessage.append(from).append(" at ").append(WHEN_FMT.format(new Date(when))); addEvent(new ReplyEvent(to, noteMessage.toString())); addEvent(new ReplyEvent(to, note)); notes.update(new BasicDBObject("_id", noteObj.get("_id")), new BasicDBObject("$set", new BasicDBObject(NOTE_DELIVERED, true))); } }
From source file:org.alfresco.bm.event.mongo.MongoResultService.java
License:Open Source License
@Override public List<EventRecord> getResults(long startTime, long endTime, boolean chartOnly, int skip, int limit) { QueryBuilder queryBuilder = QueryBuilder.start().and(EventRecord.FIELD_START_TIME) .greaterThanEquals(new Date(startTime)).and(EventRecord.FIELD_START_TIME) .lessThan(new Date(endTime)); if (chartOnly) { queryBuilder.and(EventRecord.FIELD_CHART).is(true); }/* w w w . j a v a 2s . co m*/ DBObject queryObj = queryBuilder.get(); DBObject sortObj = BasicDBObjectBuilder.start().add(EventRecord.FIELD_START_TIME, Integer.valueOf(1)).get(); DBCursor cursor = collection.find(queryObj); cursor.sort(sortObj); cursor.skip(skip); cursor.limit(limit); // Get all the results and convert them int size = cursor.size(); List<EventRecord> results = new ArrayList<EventRecord>(size); try { while (cursor.hasNext()) { DBObject obj = cursor.next(); EventRecord eventRecord = convertToEventRecord(obj); results.add(eventRecord); } } finally { cursor.close(); } // Done if (logger.isDebugEnabled()) { logger.debug( "\n" + "Found results: \n" + " Query: " + queryObj + "\n" + " Skip: " + skip + "\n" + " Limit: " + limit + "\n" + " Results: " + size); } return results; }
From source file:org.alfresco.bm.event.mongo.MongoResultService.java
License:Open Source License
@Override public List<EventDetails> getEventDetails(EventResultFilter filter, String filterEventName, int skip, int limit) { QueryBuilder queryBuilder = QueryBuilder.start(); // apply filter switch (filter) { case Failed://from w ww . ja v a 2s . c om queryBuilder.and(EventRecord.FIELD_SUCCESS).is(false); break; case Success: queryBuilder.and(EventRecord.FIELD_SUCCESS).is(true); break; default: break; } //apply event name filter if (null != filterEventName && !filterEventName.isEmpty()) { queryBuilder.and(EventRecord.FIELD_EVENT_NAME).is(filterEventName); } DBObject queryObj = queryBuilder.get(); // sort descending to get the newest values first DBObject sortObj = BasicDBObjectBuilder.start().add(EventRecord.FIELD_START_TIME, Integer.valueOf(-1)) .get(); DBCursor cursor = collection.find(queryObj); cursor.sort(sortObj); cursor.skip(skip); cursor.limit(limit); // Get all the results and convert them int size = cursor.size(); List<EventDetails> results = new ArrayList<EventDetails>(size); try { while (cursor.hasNext()) { DBObject obj = cursor.next(); EventDetails eventDetails = convertToEventDetails(obj); results.add(eventDetails); } } finally { cursor.close(); } return results; }