use of com.bluenimble.platform.db.query.OrderByField in project serverless by bluenimble.
the class MongoDatabaseImpl method _query.
private Object _query(String type, Query.Construct construct, final Query query) throws DatabaseException {
if (query == null) {
return null;
}
boolean queryHasEntity = true;
String entity = query.entity();
if (Lang.isNullOrEmpty(entity)) {
queryHasEntity = false;
entity = type;
}
entity = checkNotNull(entity);
tracer.log(Tracer.Level.Debug, "Query Entity {0}", entity);
String cacheKey = construct.name() + query.name();
BasicDBObject mQuery = null;
Map<String, Object> bindings = query.bindings();
boolean cacheable = queryHasEntity && query.caching().cache(Target.meta) && !Lang.isNullOrEmpty(query.name());
if (cacheable) {
mQuery = (BasicDBObject) QueriesCache.get(cacheKey);
tracer.log(Tracer.Level.Debug, "Query meta loaded from cache {0}", mQuery);
}
if (mQuery == null) {
CompiledQuery cQuery = compile(entity, construct, query);
mQuery = (BasicDBObject) cQuery.query();
bindings = cQuery.bindings();
if (cacheable && mQuery != null) {
QueriesCache.put(cacheKey, mQuery);
tracer.log(Tracer.Level.Debug, "Query meta stored in cache {0}", mQuery);
}
}
mQuery = cacheable ? applyBindings(mQuery, bindings) : mQuery;
tracer.log(Tracer.Level.Debug, " Query {0}", mQuery);
tracer.log(Tracer.Level.Debug, " Bindings {0}", bindings);
if (Query.Construct.select.equals(construct)) {
FindIterable<Document> cursor = db.getCollection(entity).find(mQuery);
// start / skip
if (query.start() > 0) {
cursor.skip(query.start());
}
// count / limit
if (query.count() > 0) {
cursor.limit(query.count());
}
// orderBy
OrderBy orderBy = query.orderBy();
if (orderBy != null && orderBy.count() > 0) {
List<Bson> sorts = new ArrayList<Bson>();
Iterator<String> oFields = orderBy.fields();
while (oFields.hasNext()) {
String field = oFields.next();
OrderByField of = orderBy.get(field);
Bson sort = null;
if (of.direction().equals(Direction.asc)) {
sort = Sorts.ascending(field);
} else {
sort = Sorts.descending(field);
}
sorts.add(sort);
}
cursor.sort(Sorts.orderBy(sorts));
}
Select select = query.select();
if (select != null && select.count() > 0) {
String[] pFields = new String[select.count()];
for (int i = 0; i < select.count(); i++) {
System.out.println(select.get(i));
pFields[i] = select.get(i);
}
cursor.projection(Projections.include(pFields));
}
return cursor;
} else if (Query.Construct.delete.equals(construct)) {
return db.getCollection(entity).deleteMany(mQuery);
}
return null;
}
Aggregations