0
votes

I am writing a map/reduce script to search for a custom record and create a CSV file from its results. Firstly, in the getInputData() creating a search and returning its results. After that comes the map function where I am using JSON.parse to parse the result values.

I have an array declared globally as var data = '' in which I am pushing the values I get in map function. But when all the looping ends in map() and it enters summarize(), the data array becomes empty again.

I want that data array to be called in summarize() where I can use file.create() function to create the csv file.

I used return data; in map() but it is showing as empty when in summarize().

1

1 Answers

1
votes

You have to use context.write at the end of map to send data to the next stage.

context.write({
    key: key,
    value: value
});

Adding a simple script to show how to access values in the summarize stage:

/**
 *@NApiVersion 2.x
 *@NScriptType MapReduceScript
 */
 
define([],
function () {
    function getInputData() {
        return [{
            id: 1,
            value: 'abc'
        }, {
            id: 2,
            value: 'def'
        }];        
    }

    function map(context) {
        var value = JSON.parse(context.value);
        
        context.write({
            key: value.id,
            value: value.value
        });
    }
    
    function summarize(context) {
        var values = [];
        
        context.output.iterator().each(function (key, value) {
            log.debug({
                title: 'Output for key ' + key, 
                details: value
            });
                
            values.push(value);    
            return true;
        });
        
        log.debug({
            title: 'Summary',
            details: JSON.stringify(values)
        });
    }

    return {
        getInputData: getInputData,
        map: map,
        summarize: summarize
    }
});