从Mongo MapReduce的Spring调用中获得结果

时间:2017-11-14 15:19:35

标签: spring mongodb

在我的Java Spring代码中调用my函数之后,我尝试直接在MongoDB上获取mapReduce函数的结果:

MongoOperations mongoOperations = new MongoTemplate(new SimpleMongoDbFactory(new Mongo("xxx.xxx.xxx.xxx"), "xxx"));
    MapReduceResults<Object> results = mongoOperations.mapReduce(
            "counters",
            mapFunctionCounters,
            reduceFunctionCounters,
            new MapReduceOptions().scopeVariables(scopeVariables).outputTypeInline(),
            Object.class);

    String jsonString = "";
    ObjectMapper mapper = new ObjectMapper();
    try {
        jsonString = mapper.writeValueAsString(results);
        System.out.println("jsonString = " + jsonString);
    } catch (JsonProcessingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

控制台结果:

jsonString = {"rawResults":null,"outputCollection":null,"timing":{"mapTime":-1,"emitLoopTime":-1,"totalTime":576},"counts":{"inputCount":100287,"emitCount":7102,"outputCount":104}}

当我指定集合输出时,mapReduce运行良好,但我不知道如何直接获得结果,就像使用mongodb命令中使用的out: {inline: 1}属性一样。

有人帮我吗?

1 个答案:

答案 0 :(得分:0)

我只需要添加以下类:

@AllArgsConstructor
@Setter
@Getter
public class ValueObject {
    private int id;
    private float value;

    @Override
    public String toString() {
        return "ValueObject [id=" + id + ", value=" + value + "]";
    }
}

然后改变显示结果的方式:

MapReduceResults<ValueObject> results = mongoOperations.mapReduce(
            "counters",
            mapFunctionCounters,
            reduceFunctionCounters,
            new MapReduceOptions().scopeVariables(scopeVariables).outputTypeInline(),
            ValueObject.class
            );

    for (ValueObject valueObject : results) {
        System.out.println(valueObject.getId());
    }