Example usage for com.mongodb MapReduceOutput results

List of usage examples for com.mongodb MapReduceOutput results

Introduction

In this page you can find the example usage for com.mongodb MapReduceOutput results.

Prototype

@SuppressWarnings("unchecked")
public Iterable<DBObject> results() 

Source Link

Document

Returns an iterable containing the results of the operation.

Usage

From source file:com.Aleksandar.Zoric.MongoMain.java

public String mapReduceFunction() {
    MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017));
    DB db = mongoClient.getDB("amarokforumdb");
    DBCollection collection = db.getCollection("comments");
    long count = db.getCollection("comments").count();

    System.out.println("Current amount of documents: " + count);

    String map = "function() { " + "var category; " + "var numOfDocuments = " + count + ";"
            + "for(i = 0; i < numOfDocuments; i++){ " + "if (numOfDocuments <= 100) {"
            + "category = 'New Comments'; }" + "else if(numOfDocuments > 100){"
            + "category = 'Old Comments'; }}" + "emit(category,1);};";

    String reduce = "function(key, values) { " + "var sum = 0; " + "values.forEach(function(doc) { "
            + "sum += 1; " + "}); " + "return {comments: sum};} ";

    MapReduceCommand cmd = new MapReduceCommand(collection, map, reduce, null,
            MapReduceCommand.OutputType.INLINE, null);

    MapReduceOutput out = collection.mapReduce(cmd);

    System.out.println("Mapreduce results");

    String result = null;/* w w w  . j a v  a2  s  . c o m*/

    for (DBObject o : out.results()) {
        result += o;

    }
    return result;
}

From source file:com.bugull.mongo.AdvancedDao.java

License:Apache License

public Iterable<DBObject> mapReduce(MapReduceCommand cmd) throws MapReduceException {
    MapReduceOutput output = coll.mapReduce(cmd);
    CommandResult cr = output.getCommandResult();
    if (!cr.ok()) {
        throw new MapReduceException(cr.getErrorMessage());
    }//from   ww  w .j ava2 s .c o  m
    return output.results();
}

From source file:com.bugull.mongo.AdvancedDao.java

License:Apache License

public Iterable<DBObject> mapReduce(String map, String reduce) throws MapReduceException {
    MapReduceOutput output = coll.mapReduce(map, reduce, null, OutputType.INLINE, null);
    CommandResult cr = output.getCommandResult();
    if (!cr.ok()) {
        throw new MapReduceException(cr.getErrorMessage());
    }/*from  w ww.  j  a  v a2  s .  c om*/
    return output.results();
}

From source file:com.bugull.mongo.AdvancedDao.java

License:Apache License

private Iterable<DBObject> mapReduce(String map, String reduce, DBObject query) throws MapReduceException {
    MapReduceOutput output = coll.mapReduce(map, reduce, null, OutputType.INLINE, query);
    CommandResult cr = output.getCommandResult();
    if (!cr.ok()) {
        throw new MapReduceException(cr.getErrorMessage());
    }/*from ww w  . j a  va  2  s .c o m*/
    return output.results();
}

From source file:com.dilmus.dilshad.scabi.deprecated.DDBOld.java

License:Open Source License

public ArrayList<String> fieldNames(DTableOld table) throws DScabiException {
    if (null == table) {
        throw new DScabiException("Table is null", "DBD.FNS.1");
    }/*from  w ww.  jav  a  2s. c o  m*/
    log.debug("fieldNamesUsingFindOne() table.count() is {}", table.count());
    if (table.count() <= 0) {
        return null;
    }
    String map = "function() { for (var key in this) { emit(key, null); } }";
    String reduce = "function(key, stuff) { return null; }";

    MapReduceCommand cmd = new MapReduceCommand(table.getCollection(), map, reduce, null,
            MapReduceCommand.OutputType.INLINE, null);
    MapReduceOutput out = table.getCollection().mapReduce(cmd);
    //if 4th param output collection name is used above, String s = out.getOutputCollection().distinct("_id").toString();
    //if 4th param output collection name is used above, System.out.println("out.getOutputCollection().distinct " + s);
    ArrayList<String> fieldNames = new ArrayList<String>();
    for (DBObject o : out.results()) {
        log.debug("fieldNames() Key, value is : {}", o.toString());
        log.debug("fieldNames() Key name is : {}", o.get("_id").toString());
        if (false == o.get("_id").toString().equals("_id"))
            fieldNames.add(o.get("_id").toString());
    }
    return fieldNames;

}

From source file:com.dilmus.dilshad.scabi.deprecated.DTableOld.java

License:Open Source License

public ArrayList<String> fieldNames() throws DScabiException {
    if (null == m_tableName) {
        throw new DScabiException("Table name is null", "DBT.FNS.1");
    }/*from w w w.  ja v  a 2s  .c o m*/
    if (null == m_table) {
        throw new DScabiException("Table is null", "DBT.FNS.2");
    }
    log.debug("fieldNames() firstTime is {}", m_firstTime);
    log.debug("fieldNames() table.count() is {}", m_table.count());
    if (m_table.count() <= 0) {
        return null;
    }
    if (m_firstTime) {
        String map = "function() { for (var key in this) { emit(key, null); } }";
        String reduce = "function(key, s) { return null; }";

        MapReduceCommand cmd = new MapReduceCommand(m_table, map, reduce, null,
                MapReduceCommand.OutputType.INLINE, null);
        MapReduceOutput out = m_table.mapReduce(cmd);
        //if 4th param output collection name is used above, String s = out.getOutputCollection().distinct("_id").toString();
        //if 4th param output collection name is used above, System.out.println("out.getOutputCollection().distinct " + s);
        m_fieldNames = new ArrayList<String>();
        for (DBObject o : out.results()) {
            log.debug("fieldNames() Key, value is : {}", o.toString());
            log.debug("fieldNames() Key name is : {}", o.get("_id").toString());
            if (false == o.get("_id").toString().equals("_id"))
                m_fieldNames.add(o.get("_id").toString());
        }
        m_firstTime = false;
        return m_fieldNames;
    }
    return m_fieldNames;
}

From source file:com.exorath.service.connector.service.MongoDatabaseProvider.java

License:Apache License

@Override
public ServerInfo getServerInfo(Filter filter, Long minLastUpdate) {
    //Fingers crossed
    BasicDBObjectBuilder builder = BasicDBObjectBuilder.start();
    if (filter.getGameId() != null)
        builder.append("gameId", filter.getGameId());
    if (filter.getMapId() != null)
        builder.append("mapId", filter.getMapId());
    if (filter.getFlavorId() != null)
        builder.append("flavorId", filter.getFlavorId());
    builder.append("expiry", new BasicDBObject("$gte", System.currentTimeMillis()));
    MapReduceCommand mapReduceCommand = new MapReduceCommand(datastore.getDB().getCollection(collectionName),
            "function(){" + "var ret = {pc:0, opc:0, sc:0, osc:0};" + "ret.pc = this.pc; ret.sc = 1;"
                    + "if(this.joinable && this.pc < this.mpc){ ret.opc = this.mpc - this.pc; ret.osc = 1;}"
                    + "emit('server', ret);}",
            "function(key, values){" + "var ret = {pc:0, opc:0, sc:0, osc:0};"
                    + "values.forEach( function(value) {" + "       ret.pc+= value.pc; ret.sc++;"
                    + "       ret.osc+= value.osc; ret.opc+= value.opc" + "   });" + "return ret;" + "}",
            null, MapReduceCommand.OutputType.INLINE, builder.get());
    MapReduceOutput results = datastore.getDB().getCollection(collectionName).mapReduce(mapReduceCommand);
    if (results.getOutputCount() == 0)
        return new ServerInfo(0, 0, 0, 0, System.currentTimeMillis());
    if (results.getOutputCount() > 1)
        throw new IllegalStateException("mapReduce returned multiple results.");
    for (DBObject res : results.results()) {
        DBObject val = (DBObject) res.get("value");
        return new ServerInfo(((Double) val.get("pc")).intValue(), ((Double) val.get("sc")).intValue(),
                ((Double) val.get("osc")).intValue(), ((Double) val.get("opc")).intValue(),
                System.currentTimeMillis());
    }//from   ww  w .j  a  v  a 2 s. c o m
    ////         MapreduceResults<ServerInfo> results = datastore.mapReduce(MapreduceType.INLINE, getFilterQuery(filter), ServerInfo.class, mapReduceCommand);
    ////        if(results.getCounts().getOutputCount() == 0) {
    ////            System.out.println("output 0 :*");
    //            return null;
    //        }
    //        System.out.println("ms: " + results.getElapsedMillis());
    //        results.forEach(info -> System.out.println(info.getOpenSlotCount()));
    return null;
}

From source file:com.hangum.tadpole.mongodb.core.test.MongoTestMapReduce.java

License:Open Source License

/**
 * @param args/*from  ww w .j  a  v a 2  s  . c om*/
 */
public static void main(String[] args) throws Exception {

    ConAndAuthentication testMongoCls = new ConAndAuthentication();
    Mongo mongo = testMongoCls.connection(ConAndAuthentication.serverurl, ConAndAuthentication.port);
    DB db = mongo.getDB("test");
    DBCollection coll = db.getCollection("person");

    MapReduceOutput out = coll.mapReduce(map, reduce, null, MapReduceCommand.OutputType.INLINE, null);
    for (DBObject obj : out.results()) {
        System.out.println("======================================================");
        System.out.println("\t[_id]\t" + obj.get("_id"));
        Map objResult = (Map) obj.get("value");
        System.out.println("\t[count]\t" + objResult.get("count"));
        System.out.println("\t[sum]\t" + objResult.get("sum"));

        System.out.println(obj);
    }
    out.getRaw();
    out.getRaw();

    mongo.close();

    try {
        Thread.sleep(1);
    } catch (Exception e) {
    }
}

From source file:com.impetus.client.mongodb.MongoDBClient.java

License:Apache License

/**
 * Execute native query./*from   w w  w .ja  va2s  .  c o m*/
 * 
 * @param jsonClause
 *            the json clause
 * @param entityMetadata
 *            the entity metadata
 * @return the list
 */
public List executeNativeQuery(String jsonClause, EntityMetadata entityMetadata) {
    List entities = new ArrayList();
    String[] tempArray = jsonClause.split("\\.");
    String tempClause = tempArray[tempArray.length - 1];

    if (tempClause.contains("findOne(") || tempClause.contains("findAndModify(")) {
        DBObject obj = (BasicDBObject) executeScript(jsonClause);
        populateEntity(entityMetadata, entities, obj);
        return entities;

    } else if (tempClause.contains("find(") || jsonClause.contains("aggregate(")) {
        jsonClause = jsonClause.concat(".toArray()");
        BasicDBList list = (BasicDBList) executeScript(jsonClause);
        for (Object obj : list) {
            populateEntity(entityMetadata, entities, (DBObject) obj);
        }
        return entities;

    } else if (tempClause.contains("count(") || tempClause.contains("dataSize(")
            || tempClause.contains("storageSize(") || tempClause.contains("totalIndexSize(")
            || tempClause.contains("totalSize(")) {
        Long count = ((Double) executeScript(jsonClause)).longValue();
        entities.add(count);
        return entities;

    } else if (tempClause.contains("distinct(")) {
        BasicDBList list = (BasicDBList) executeScript(jsonClause);
        for (Object obj : list) {
            entities.add(obj);
        }
        return entities;

    } else if (jsonClause.contains("mapReduce(")) {
        final MapReduceCommand command = parseMapReduceCommand(jsonClause);
        final MapReduceOutput output = mongoDb.getCollection(command.getInput()).mapReduce(command);

        final BasicDBList list = new BasicDBList();
        for (final DBObject item : output.results()) {
            list.add(item);
        }
        return list;
    } else {
        BasicDBList list = (BasicDBList) executeScript(jsonClause);
        for (Object obj : list) {
            entities.add(obj);
        }
        return entities;
    }
}

From source file:com.petpet.c3po.dao.mongo.MongoPersistenceLayer.java

License:Apache License

public List<BasicDBObject> mapReduceRaw(String map, String reduce, Filter filter) {
    long start = System.currentTimeMillis();
    DBObject query = this.getCachedFilter(filter);
    DBCollection elmnts = getCollection(Element.class);
    MapReduceCommand cmd = new MapReduceCommand(elmnts, map, reduce, null, INLINE, query);

    MapReduceOutput output = elmnts.mapReduce(cmd);
    Iterator<DBObject> iterator = output.results().iterator();
    List<BasicDBObject> results = new ArrayList<BasicDBObject>();
    while (iterator.hasNext()) {
        results.add((BasicDBObject) iterator.next());

    }/*from www.j a va  2  s  . c om*/
    //List<BasicDBObject> results = ArrayList<BasicDBObject> () ( output.results());getCommandResult().get( "results" );
    long end = System.currentTimeMillis();
    LOG.debug("The map-reduce job took {} seconds", (end - start) / 1000);
    return results;

}