MapReduce шаблоны праектавання - кароткае ўвядзенне

featured_img

шаблоны праектавання MapReduce

Агляд: Дызайн мадэлі ў цяперашні час агульны тэрмін, які выкарыстоўваецца практычна ва ўсіх абласцях распрацоўкі праграмнага забеспячэння. Шаблоны не што іншае, як некаторыя правераныя і выпрабаваныя метады праектавання выкарыстоўваюцца для вырашэння бізнес-задач. MapReduce з'яўляецца новы дамен тэхналогіі, а таксама мае свае ўласныя шаблоны праектавання для вырашэння праблем вылічэнняў дадзеных.

In this article, Я буду казаць аб розных шаблонаў праектавання, якія выкарыстоўваюцца ў рамках MapReduce.

Увядзенне: Карта Reduce выкарыстоўваецца для апрацоўкі дадзеных, якая захоўваецца на некалькіх кампутарах. Яна забяспечвае выразныя і адметныя мяжы паміж тым, што мы можам і што мы не можам. Гэта робіць шэраг варыянтаў, нам трэба разгледзець, меншы. At the same time, мы можам высветліць, як вырашыць праблему з абмежаваннямі. Дызайн мадэлі былі пратэставаныя на працягу многіх праблем час ад часу і паказалі правільны ўзровень абстракцыі.

шаблоны праектавання MapReduce займаюць тую ж ролю ў меншым прасторы праблем і іх рашэнняў. Яны забяспечваюць агульныя рамкі для вырашэння нашых вылічэнняў дадзеных праблем, звязаных з, без канцэнтрацыі на праблемнай вобласці. MapReduce дызайн мадэлі таксама забяспечваюць агульную мову для груп, якія працуюць разам на MapReduce прыкладанняў.

MapReduce Design Pattern: Зараз давайце абмяркуем розныя падыходы да праектавання па адным у наступным раздзеле.

разліку:

Пастаноўка праблемы - Будзем лічыць, што мы маем пачак дакументаў, дзе кожны дакумент змяшчае набор тэрмінаў. Цяпер у нас ёсць патрабаванне, каб вылічыць колькасць уваходжанняў кожнага тэрміна ў дакуменце.

рашэнне - У наступным фрагменце кода мы маем Mapper, які проста запісвае '1' для кожнага тэрміна ён сутыкаецца. Рэдуктар тут праходзіць па ўсім спісе такіх людзей, сумуе іх і выдае вынік.

Listing 1: Computing Code – 1

[Code]

class Mapper

method Map(docid id, doc d)

for all term t in doc d do

Emit(term t, count 1)

class Reducer

method Reduce(term t, counts [c1, c2,…])

cnt = 0

for all count c in [c1, c2,…] do

cnt = cnt + З

Emit(term t, count cnt)

[/Code]

Though Simple, but the above code has an obvious disadvantage that a high amount of dummy counters are emitted by the Mapper. Now we can reduce this by summing the counters for each document.

Listing 2: Computing Code – 2

[Code]

class Mapper

method Map(docid id, doc d)

HArray = new AssociativeArray

for all term t in doc d do

HArray{t} = HArray{t} + 1

for all term t in HArray do

Emit(term t, count HArray{t})

[/Code]

Now, для таго, каб акумуляваць лічыльнікаў для ўсіх дакументаў, дазваляе, маюць Камбайнеры -

Listing 3: Computing Code – 3

[Code]

class Mapper

method Map(docid id, doc d)

на ўвесь тэрмін цёр ў дакумент d зрабіць

Emit(тэрмін цёр, count 1)

клас камбінатар

метад збожжаўборачны(тэрмін цёр, [c1, c2,…])

сума = 0

для ўсіх падліку CNT ў [c1, c2,…] do

сума = сума + CNT

Emit(term t, разлічваць суму)

class Reducer

method Reduce(term t, counts [c1, c2,…])

totalCnt = 0

для ўсіх падліку CNT ў [c1, c2,…] do

totalCnt = totalCnt + CNT

Emit(term t, разлічваць totalCnt)

[/Code]

Collating:

Пастаноўка праблемы -

У нас ёсць набор элементаў і некаторыя функцыі некаторых пунктаў. Зараз патрабуецца, каб захаваць усе элементы, якія маюць такое ж значэнне функцыі або выконваць некаторыя іншыя вылічэнне, якое патрабуе, каб усе такія элементы павінны быць апрацаваны ў групе.

рашэнне -

У нас ёсць рашэнне, дзе картографа вылічае зададзеную функцыю для кожнага элемента і вяртае значэнне функцыі ў якасці ключа і элемента ў якасці значэння. Ролю рэдуктара для здабывання ўсіх згрупаваных элементаў і апрацаваць іх ці захаваць іх.

Filtering (Grep), Парсінга і праверка:

Пастаноўка праблемы -

Разгледзім у нас ёсць мноства запісаў, і патрабаванне, каб сабраць усе запісы, якія задавальняюць некаторага умове або ператварыць гэтыя запісы ў некаторых іншых фарматаў прадстаўлення. The second part of the problem includes tasks such as – text parsing and extraction of the values.

рашэнне -

Solution to this problem is quite straight forward – we have a mapper which takes one record at a time and returns the items which meet the criteria.

Distributed Task Execution:

Пастаноўка праблемы -

Let us consider we have a large computational problem which can be divided into multiple parts and results from all of these parts needs to be combined in order to obtain the final result.

рашэнне -

Solution to this problem is to split the specifications into a set of specification which are stored as input data for the mappers. Each of these mappers takes one specification at a time as input data and processes them and produces the results. The job of the reducer is to combine all of these results and produces the final result.

Iterative Message Passing:

Пастаноўка праблемы -

Let us consider we have a network of entities and there exists some relationship amongst them. We are required to calculate the state of each entity based on the property of other entity in the neighborhood. This state can be used to represent a distance to other nodes which is an indication that there is a neighbor having certain properties and characteristics.

рашэнне -

We have a network which stores a set of nodes and each node contains the information of a list of adjacent node IDs. Conceptually, the MapReduce jobs are performed in iterative way and at each iteration the node sends messages to its neighbors. And then each neighbor updates its state on the basis of the message that is received. These iterations are terminated by some condition e.g. fixed maximal number of iterations. From the technical point of view, the Mapper returns the messages for each node using the ID of the adjacent node as a key. У выніку, all of these messages are grouped by the incoming node and hence the reducer is able to recalculate the state and rewrites the node with the new state.

Listing 4: Iterative messaging passing

[Code]

class Mapper

method Map(id nId, object NObj)

Emit(id nId, object NObj)

для ўсіх ID Сярэдзіны ў NObj.OutgoingRelations зрабіць

Emit(ID сярэдзіны, паведамленне GetMessage(NObj))

class Reducer

method Reduce(ідэнтыфікатар м, [s1, s2,…])

M = NULL

паведамленняў = []

для ўсіх S ў [s1, s2,…] do

калі IsObject(s) затым

M = s

яшчэ // s гэтае паведамленне

messages.add(s)

M.State = calculateState(паведамлення)

Emit(ідэнтыфікатар м, пункт M)

[/Code]

Пошук у шырыню (гэта прыклад):

Пастаноўка праблемы -

Разгледзім мы маем графік, і патрабуецца, каб вылічыць адлегласць ад аднаго вузла зыходнага да ўсіх іншых вузлах, прысутных у графе. Гэта таксама называецца лік пералётаў.

рашэнне -

Рашэнне можа быць, першы ў вузел-крыніца выпускае 0 да ўсіх сваіх суседзяў. Then the neighbors propagate this counter after incrementing it by 1 for each hop.

Distinctive Values:

Пастаноўка праблемы -

Let us consider we have a set of records that contain fields M and N. The requirement is to count the total number of unique values of field M for each subset of the same Group N.

рашэнне -

The solution to this problem can be addressed in two stages. In the first stage, the mapper produces dummy counters for each pair of M and N. Then the reducer counts the total number of occurrences for each pair. The objective of this phase is to maintain uniqueness of M values. In the second phase, pairs are grouped by N and the total numbers of items are calculated for each group.

Summary: In this article we have discussed different design approaches which are commonly used to solve data computation issues. MapReduce design patterns are continuously evolving, so we will see more design approaches in near future. Let us summarize our discussion in following bullets –

  • Map reduce is used to process data which resides on a host of computers.
  • Дызайн мадэлі выкарыстоўваюцца для вырашэння праблем.
  • Некаторыя часта выкарыстоўваюцца шаблоны праектавання MapReduce пералічаны ў раздзеле -
    • Разлік - падлік галасоў і падвядзенне
    • Collating
    • Фільтраванне парсінга і праверка
    • Размеркаваная выкананне задачы
    • Ітэрацыйныя перадача паведамленняў
    • Пошук у шырыню
    • адметная Пошук

 

 

 

============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share