Main Content

KeyValueStore

キーと値のペアを保存して mapreduce で使用

説明

関数 mapreduce は、実行中に KeyValueStore オブジェクトを自動的に作成し、それを使用して map 関数と reduce 関数によって追加されたキーと値のペアを保存します。mapreduce を使用するために KeyValueStore オブジェクトを明示的に作成する必要はありませんが、map 関数と reduce 関数でこのオブジェクトを操作するには、オブジェクト関数 addaddmulti を使用する必要があります。

作成

関数 mapreduce は実行時に KeyValueStore オブジェクトを自動的に作成します。

オブジェクト関数

addキーと値の 1 つのペアを KeyValueStore に追加
addmultiキーと値の複数のペアを KeyValueStore に追加

すべて折りたたむ

次の map 関数は、関数 add を使用してキーと値のペアを中間の KeyValueStore オブジェクト (intermKVStore) に 1 つずつ追加します。

function MeanDistMapFun(data, info, intermKVStore)
    distances = data.Distance(~isnan(data.Distance));
    sumLenKey = 'sumAndLength';
    sumLenValue = [sum(distances), length(distances)];
    add(intermKVStore, sumLenKey, sumLenValue);
end

次の map 関数は、addmulti を使用してキーと値の複数のペアを中間の KeyValueStore オブジェクト (intermKVStore) に追加します。この map 関数は intermKeys 変数から複数のキーを収集して、intermVals 変数から複数の値を収集していることに注意してください。これにより、addmulti を一度呼び出すだけで、すべてのキーと値のペアが追加されます。add をループで使用するのではなく、 addmulti を一度呼び出すのがベスト プラクティスです。

function meanArrivalDelayByDayMapper(data, ~, intermKVStore)
% Mapper function for the MeanByGroupMapReduceExample.

% Copyright 2014 The MathWorks, Inc.

% Data is an n-by-2 table: first column is the DayOfWeek and the second
% is the ArrDelay. Remove missing values first.
delays = data.ArrDelay;
day = data.DayOfWeek;
notNaN =~isnan(delays);
day = day(notNaN);
delays = delays(notNaN);

% find the unique days in this chunk
[intermKeys,~,idx] = unique(day, 'stable');

% group delays by idx and apply @grpstatsfun function to each group
intermVals = accumarray(idx,delays,size(intermKeys),@countsum);
addmulti(intermKVStore,intermKeys,intermVals);

function out = countsum(x)
n = length(x); % count
s = sum(x); % mean
out = {[n, s]};

拡張機能

スレッドベースの環境
MATLAB® の backgroundPool を使用してバックグラウンドでコードを実行するか、Parallel Computing Toolbox™ の ThreadPool を使用してコードを高速化します。

バージョン履歴

R2014b で導入

参考

トピック