Loading TOC...

MarkLogic 10 Product Documentation
ValuesSearch.reduce

ValuesSearch.reduce(
   reducer as objectOrFuncRef,
   seed as anyValue
) as ValuesSearch

Summary

Specifies a function similar to Array.prototype.reduce() to apply to each value within the slice or a configuration object for the built-in reducer. See the Usage Notes for details.

Parameters
reducer The reducer function or a configuration for the built-in mapper.
seed The initial reduction passed to the reducing function.

Usage Notes

You can pass in either a configuration object for the built-in reducer or a function reference to a custom reducer. The built-in reducer configuration object can have the following properties:

frequency
One of the string values "fragment", "item", or "none" (default). This setting controls whether or not to include the number of occurrences of each value. Fragment frequency is the number of fragments (documents) containing each value. Item frequency is the number occurrences of each value. Defaults to none.

When returning frequencies, the built-in reducer returns an object with the serialized value (or bucket name when using groupInto) as the key and the frequency as the value.

The reducer function should have the following signature:

function (prev, current, index, state)

Where the parameters have the following contents:

prev
The value returned by the previous call, or the seed value on the first call.
current
The current value.
index
The number of the current value.
state
A state object with a boolean-valued isLast> property that indicated the last call. You can set it to true to prematurely halt the reduction.

The return from the last call becomes the final reduced result.

You cannot use this method in conjunction with ValuesSearch.map.

See Also

Example


// Using the built-in reducer to return frequency data
const jsearch = require('/MarkLogic/jsearch.sjs');
jsearch.values('author')
  .reduce({frequency: 'item'})
  .result();

// Result: {"John Steinbeck":3, "Mark Twain":4, "Robert Frost":1}
   

Example


// Using a custom reducer. (In practice, you would use the aggregate
// method with the built-in "avg" aggregate function to do this calculation.)
const jsearch = require('/MarkLogic/jsearch.sjs');
jsearch.values('price')
  .where(cts.directoryQuery('/books/'))
  .reduce(function (accum, value, index, state) {
     const freq = cts.frequency(value);
     accum.count += freq;
     accum.sum += value * freq;
     return state.isLast ? (accum.sum / accum.count) : accum;
   }, {count: 0, sum: 0})
  .result();

// Result: The computed value: 16.125
   

Stack Overflow iconStack Overflow: Get the most useful answers to questions from the MarkLogic community, or ask your own question.