Skip to main content

How To Use Map Reduce in Spring Mongo data


Suppose  I have order table and I want to find out best five selling product.

Create a method that returns best product of ValueObject Type .
ValueObject Type basically contain id and corresponding values to those ids as shown below:


public class ValueObject implements Comparable<ValueObject>{
private Object id;
private int value;
public Object getId() {
return id;
}
public void setId(Object id) {
this.id = id;
}

public int getValue() {
return value;
}

public void setValue(int value) {
this.value = value;
}

@Override
public String toString() {
return "ValueObject [id=" + id + ", value=" + value + "]";
}
@Override
public int compareTo(ValueObject o) {
if(o instanceof ValueObject){
return o.getValue()-this.getValue();
}
else{
throw new ClassCastException();
}
}

}


Now, you can call mapReduce method on MongoTemplate which return result as MapReduceResult

public Iterable<ValueObject> countBestSellingProduct() {
MapReduceResults<ValueObject> results = mongoTemplate.mapReduce("order", "map.js", ”reduce.js", ValueObject.class);
             
              return results;
       }

Syntax of mapReduce ()

mapReduce(“Collection Name”, “ mapfunction”, “reducefunction”, ValueObect.class);
* You can also pass your query to mapReduce then Sytax will be
mapReduce(query, “Collection Name”,  “mapfunction”, “reducefunction”, ValueObect.class);

map.js (This is just an example to map with id)

function ()
{
       var prt = this.$id;
       if(prt != null ){
             
       }
       emit(this.$id, 1);
}

reduce.js(Example of a reduce function)

function (key, values)
{
       var sum = 0;
       for (var i = 0; i < values.length; i++)
       {
              sum += values[i];
       }
       return sum;
}


You will get result which is Iterable ValueObject type
Now Convert it into List<ValueObject>
List<ValueObject> lst = new ArrayList<ValueObject>();

              for (ValueObject prt: result) {
                     lst.add(prt);
                     
              }
And finally, sort this list by using
Collections.sort(lst);
Now, you can top five or more best-selling products by taking out a sublist from the above list.

List<ValueObject> bestFiveSellingProduct=lst.subList(0,4)

Simple, isn' it??
Cheers !!!!!!!!!!!!!!!!!!!!!!!

Comments

  1. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. what county am i in

    ReplyDelete

Post a Comment

Thanks for your concern.