Master Data Services для управления НСИ. Что за «птица» залетела в Mac

(MDS) в MS SQL Server 2012. До недавнего времени я был знаком с этим продуктом, входящим в состав MS SQL Server 2012 (Business Intelligence and Enterprise editions), только в теории и ждал удачного случая, чтобы проверить его на практике, и вот такой случай представился.

Вводные данные

Мой клиент использует BI-решение на базе Microsoft SQL Server 2012 Business Intelligence Edition. Центром этой BI-системы является хранилище данных (Data Warehouse), которое наполняется с помощью SSIS-пакетов из транзакционных систем (OLTP). Хранилище данных, в свою очередь, служит источником для многомерной модели данных (Multidimensional Data Model). На основе многомерной модели данных аналитики заказчика формируют отчетность в Excel, используя сводные таблицы (Pivot Tables). Поскольку источников данных много, и пользователи транзакционных систем управляют справочниками хаотично, заказчик обозначил потребность в решении, которое позволяло бы создать в хранилище данных иерархии для некоторых измерений, которые были бы удобны для целей аналитического анализа. Так, например, информация об организационной структуре компании, хранящаяся в измерении «Подразделения» (таблица dbo.dimDivisions), импортируемая из OLTP-систем, удобна для оперативных отчетов, формируемых в OLTP-системах, но не подходит для целей анализа в BI-системе.

Требования бизнеса

Формальные требования бизнес-заказчика можно кратко описать следующим образом:
  • Разработать инструмент, позволяющий управлять данными о подразделениях компании для целей аналитической отчетности.
  • Использовать новые данные о подразделения в существующем BI-решений.
  • Изменения не должны повлиять на работу OLTP-систем.

Предварительная оценка и выбор решения

На основании имеющихся вводных данных и бизнес-требований заказчику было предложено следующее решение:
  • Добавить в хранилище данных дополнительное измерение для хранения данных об орг. структуре для целей аналитической отчетности.
  • Обеспечить связь между записями нового измерения и измерения «Сотрудники».
  • Изменить многомерную модель данных с учетом изменения структуры хранилища данных.
  • Выполнить настройку Master Data Services. Под настройкой понимается создание возможности ввода и редактирования данных о сотрудниках и подразделениях вручную, а так же настройка, необходимая для импорта/экспорта данных в/из MSD.
  • Обеспечить автоматический импорт данных о новых сотрудниках из хранилища данных в Master Data Services.
  • Обеспечить автоматический экспорт данных о подразделениях и принадлежности сотрудников к подразделениям сотрудниках из Master Data Services в хранилище данных.

Реализация решения

Доработка хранилища данных
Итак, поехали по-порядку. Сначала создадим в хранилище данных новое измерение «Произвольные подразделения» (dbo.dimDerivedDivisions) и свяжем его с измерением «Сотрудники» (dbo.dimEmploees). SQL-скрипт для этой задачи выглядит следующим образом:

Создадим новое измерение "Произвольные подразделения" CREATE TABLE dbo.dimDerivedDivisions (id int NOT NULL primary key identity(1, 1), parentId int NULL, sourceCode int NOT NULL, sourceParentCode int NULL, name nvarchar(100) NOT NULL DEFAULT ("N/A"), lineageDate datetime DEFAULT GETDATE(), lineageSource nvarchar(255) NOT NULL DEFAULT ("")); --Определим внешний ключ для parentId, ссылающийся на dbo.dimDerivedDivisions(id) для обеспечения иерархии родитель-потомок ALTER TABLE dbo.dimDerivedDivisions ADD CONSTRAINT fk_dbo_dimDerivedDivisions_dbo_dimDerivedDivisions FOREIGN KEY (parentId) REFERENCES dbo.dimDerivedDivisions(id); --В новое измерение добавим значение по умолчанию, на которое будут ссылаться не распределенные сотрудники SET IDENTITY_INSERT dbo.dimDerivedDivisions ON; INSERT INTO dbo.dimDerivedDivisions (id, parentId, sourceCode, sourceParentCode, name, lineageDate, lineageSource) SELECT 0, NULL, 0, NULL, "N/A", GETDATE(), "Запись введена вручную" WHERE NOT EXISTS (SELECT id FROM dbo.dimDerivedDivisions WHERE id = 0); SET IDENTITY_INSERT dbo.dimDerivedDivisions OFF; --Добавим новую колонку в измерение "Сотрудники" ALTER TABLE dbo.dimEmployees ADD derivedDivisionId int NOT NULL DEFAULT(0); --Определим внешний ключ, ссылающийся на dbo.dimDerivedDivisions(id) ALTER TABLE dbo.dimEmployees ADD CONSTRAINT fk_dbo_dimEmployees_dbo_dimDerivedDivisions FOREIGN KEY (derivedDivisionId) REFERENCES dbo.dimDerivedDivisions(id);

Доработка многомерной модели данных
Теперь добавим новое измерение в многомерную модель данных. Для этого откроем проект многомерной модели данных в SQL Server Data Tools и добавим новую таблицу dbo.dimDerivedDivisions в Data Source View. Результат выглядит следующим образом:

Чтобы не уходить далеко от темы, кратко опишу процесс доработки многомерной модели. В многомерной модели данных создаем новое измерение «Произвольные подразделения», настраиваем связь нового измерения с существующими таблицами фактов через измерение «Сотрудники», деплоим и процессим куб:

Настройка Master Data Services
Теперь все структуры данных для подготовки аналитической отчетности в разрезе нового измерения «Произвольные измерения» готовы, приступаем к самому главному - к настройке Master Data Services. Для этого в браузере переходим по ссылке, которую дал нам SQL Server Administrator, и попадаем в web-интерфейс MDS, который выглядит следующим образом:

Я не буду описывать здесь установку Master Data Services, так как это рутинная задача подробно описана на msdn.microsoft.com . Сосредоточимся лучше на реальной практике использования MDS.

Итак, первое, что нам необходимо сделать - это создать модель. Моделью в MDS называется логический контейнер, который содержит в себе сущности определенной бизнес-области. В нашем случае уместно создать модель «Сотрудники», содержащую сущности «Сотрудники» и «Подразделения». Для создания модели перейдем в web-интерфейсе Master Data Services в Administrative Tasks по ссылке System Administration. В открывшемся окне введем название модели Employees и нажмем кнопку Save model:

При установленном флажке Create entity with same name as model автоматически вместе с моделью будет создана одноименная сущность Employees. Далее создадим еще одну сущность «Подразделения» (Divisions), для этого выберем модель Employees и перейдем в меню Manage - Entities:

Нажмем на кнопку Add entity:

В открывшемся диалоге заполним параметры новой сущности и нажмем кнопку Save entity. Обратите внимание, что при создании сущности «Подразделения» был установлен флажок Enable explicit hierarchies and collections (это означает, что для сущности появится возможность создания иерархии), и ниже укажем название иерархии Divisions. Явная иерархия (Explicit Hierarchy) - это иерархия, члены которой могут быть организованы любым образом, т.е. на каждом уровне иерархии может быть любое любое количество членов и следующих уровней вложенности:

После того, как сущности созданы, необходимо настроить атрибуты сущностей. Для сущности «Сотрудники» (Employees) добавим атрибут «Подразделение» (Division). Выберем сущность Employees и нажмем кнопку Edit selected entity:

В открывшейся форме редактирования сущности нажмем на кнопку Add leaf attribute для того, чтобы добавить атрибут «Подразделение» конечного элемента сущности «Сотрудники»:

В открывшейся форме добавления атрибута, заполним наименование атрибута и установим переключатель типа атрибута в положение Domain-based. Это означает, что значения данного атрибута будут принадлежать определенной сущности, и ниже укажем какой именно, в нашем случае это сущность «Подразделения» (Divisions). В конце нажимаем кнопку Save attribute:

Ручной ввод данных в Master Data Services
Итак, модель «Сотрудники» (Employees) и сущности «Сотрудники» (Employees) и «Подразделения» (Divisions) готовы, теперь необходимо наполнить их данными. Сущность «Подразделения» (Divisions) пользователи будут заполнять вручную. Для демонстрации этого процесса перейдем на главную страницу web-интерфейса Master Data Services, в подразделе Information Worker Tasks выберем модель Employees и перейдем по ссылке Explorer:

Выберем иерархию «Подразделения» (Divisions):

Выберем тип элементов, которыми мы хотим управлять. Сначала создадим несколько групповых элементов (Consolidated Member):

Нажмем кнопку Add, введем наименование подразделения-группы «Отдел продаж» и нажмем кнопку OK:

Аналогично добавим другие подразделения и, таким образом, создадим структуру подразделений, изображенную на следующем рисунке:

Обратите внимание, жирным шрифтом выделены подразделения-группы, а нежирным - конечные элементы. На одном уровне иерархии могут быть как те, так и другие типы элементов.

Импорт данных в Master Data Services
Теперь необходимо импортировать данные о сотрудниках в Master Data Servises из существующего хранилища данных (для дальнейшего сопоставления сотрудников и подразделений, и экспорта этих данных обратно в хранилище). Для загрузки данных в MDS в SQL базе данных, обеспечивающей работу Master Data Servises, существуют специальные промежуточные таблицы (Staging Tables), в которые мы можем вставить данные SQL-запросом или создать специальный SSIS-пакет, который будет импортировать новые записи о сотрудниках из хранилища данных во временные таблицы для их дальнейшей обработки в Master Data Servises. Откроем SSMS и найдем временные таблицы в базе данных Master Data Servises. Вот они:

В качестве примера импортируем произвольные 10 записей о сотрудниках из хранилища данных в промежуточную таблицу базы данных Master Data Services. Для этого выполним следующий SQL-запрос:

INSERT INTO . (, , , , ) SELECT TOP 10 1, 0, N"Employees_Leaf_Batch00001", E.id, E.name FROM .. E;

Вернемся в web-интерфейс Master Data Services и на главной странице перейдем по ссылке Intergation Management:

В открывшемся окне видим пакет Employees_Leaf_Batch00001, который был только что создан SQL-запросом. Запустим его, нажав на кнопку Start Batches:

После отработки пакета увидим вот такую информацию о статусе, времени начала и окончания выполнения, ошибках:

Управление данными в Master Data Services
Теперь давайте перейдем в режим управления данными и посмотрим, как загрузились записи о сотрудниках из промежуточной таблицы. Для этого перейдем на главную страницу web-интерфейса Master Data Services, в подразделе Information Worker Tasks выберем модель Employees и перейдем по ссылке Explorer. В открывшемся окне видим, что новые данные о сотрудниках были добавлены в Master Data Services и находятся в состоянии Waiting to be validated:

Обратите внимание, что данные о подразделении (Division) у сотрудников не заполнены. Нам необходимо для каждого сотрудника выбрать подразделение, в котором он работает и нажать на кнопку ОК:

Экспорт данных из Master Data Services
После того как данные о подразделениях и принадлежности сотрудников к подразделениям введены, необходимо импортировать их обратно в хранилище данных. Для этого необходимо создать специальные представления (Subscription Views) в MDS. Перейдем на главную страницу web-интерфейса Master Data Services, в подразделе Administrative Tasks перейдем по ссылке Intergation Management:

В открывшемся окне перейдем в меню Create Views и нажмем кнопку Add subscription view:

Заполним параметры представления для сущности «Подразделения» (Divisions) и нажмем кнопку Save:

Аналогичным образом создадим представление для сущности «Сотрудники» (Employees):

Теперь давайте разберемся, что же это за представления и как можно их использовать. На самом деле все довольно просто, представления в MDS есть ни что иное, как привычные нам представления (Views) в SQL базе данных. Откроем SSMS, и убедимся в этом:

И последнее, что остается сделать для решения поставленной задачи - это разработать SQL-скрипт или пакет SSIS, который экспортирует информацию из представлений MDS в хранилище данных.

Выводы

На реализацию данного решения было потрачено около восьми человеко-часов, что, как мне кажется, вполне адекватное время для такой задачи. В описанном решении я не использовал все возможности Master Data Services, например, остались без внимания

– это встроенная поисковая система, которая позволяет найти почти всё, что Вы используете под своей учётной записью. Для этого индексирует все носители, подключённые к Вашему Маку. В некоторых случаях в меню постоянно отображается строка прогресса, указывающая на то, что система индексирует жёсткий диск. В этом случае в окне Activity Monitor можно найти процессы «mds» и «md-worker», которые используют большое количество ресурсов CPU.

может повторно индексировать жёсткий диск после крупных обновлений системы, восстановления из резервной копии или после критических ошибок, таких как kernel panic или зависаний, устранённых принудительной перезагрузкой. Это стандартные случаи, при которых индексация должна запускаться и, поскольку это довольно длительный процесс, может занять несколько часов. Однако, если Вы обнаружите повышенную активность процессов «mds» и «md-worker» и постоянно проводящуюся индексацию, то стоит уделить этой проблеме внимание.

Для начала попробуйте очистить индексы вручную. Есть два способа это сделать.

Список конфиденциальности Spotlight.

Выберите Spotlight в Системных настройках и откройте вкладку Конфиденциальность. Дальше перетащите все свои носители в список и сразу удалите их из него. Это вынудит систему удалить индексацию носителей и затем создать её, после удаления этих носителей из списка.

Терминал

Для существует несколько команд в Терминале , которые можно использовать для удаления и повторного проведения индексации вашей системы. Чтобы это сделать, откройте Терминал и последовательно введите три команды:

mdutil -Ea
mdutil -ai off
mdutil -ai on

Первая команда удалит индексацию всех томов в системе, вторая – отключит функцию индексации, а третья – включит её обратно. Подождите пока процесс завершится и проверьте, осталась ли проблема.

Следует учесть, что индексация диска – процесс длительный и может занять несколько часов, и определить решена ли проблема до завершения процесса нельзя.

Если описанные выше способы не дали положительного результата, то стоит проверить жёсткий диск. Ошибки файловой системы могут вызвать проблемы с доступом к данным и их обработкой, что, в свою очередь, может заставить Spotlight постоянно проводить индексацию. Проверьте, есть ли у Вас полная резервная копия Вашей системы (если нет, то обязательно создайте её), а затем используйте Дисковую утилиту для проверки и исправления дисков.

  1. Запустите Дисковую утилиту .
  2. С зажатой клавишей ⌘Command выберите все подключенные к вашему компьютеру диски.
  3. Во вкладке Первая помощь нажмите Проверить диск

Если в процессе проверки будут выявлены ошибки, нажмите Исправить диск. Если же ошибка возникла на загрузочном разделе, то исправить её стоит, загрузившись из раздела восстановления. Чтобы загрузиться из раздела восстановления, выключите компьютер, а затем включите его, зажав сочетание клавиш ⌘Command + R.

Традиционное спасибо Кристоферу Кесслеру за оригинальную .

Похожих постов не обнаружено

When your Mac is running very slowly and there is no obvious cause, the problem could be because of mdworker and mds processes in OS X. Here is the solution you need to reclaim your Mac’s speed.

This is a worked example of the sort of thing than can go wrong with your Mac and how to solve the problem. An hour ago My Mac stopped working, but now it is back to normal. Want to know how I did it? read on. (Affiliate links in this article.)

The problem was that the Mac was running slowly. It wasn’t bad, but it was a bit annoying watching the spinning beach ball where the mouse should be.

Then it almost stopped completely. The Mac was barely usable and switching from one window to another took 30 seconds. Click a menu and it would not appear until 20 seconds later. Click a button and nothing would happen for 20 or 30 seconds. It was like swimming through through treacle.

It was almost, but not quite impossible to use the Mac. It just took forever to do anything, no matter how simple. When this happens, you need to run Activity Monitor in the Applications/Utilities folder.

It took some time to quit a few apps, close a couple of windows, and get Activity Monitor open because the Mac had almost stopped responding, but eventually it opened.

Issues with mdworker and mds process

The problem could be seen on the Memory tab and mdworker was using 2.23 GB of memory, 1.72 GB of swap file was used, there was 2.33 GB of compressed memory, and the memory pressure chart was completely red.

A red memory pressure chart means there is no memory left to do anything and the Mac gets really bogged down swapping memory out to disk, compressing it, and juggling it around.

The mdworker process is used by Spotlight and _spotlight can be seen in in the User column in Activity Monitor. In addition to the 2.23 GB at the top, further down were several more mdworker processes using 37 - 45 MB. Also there are mds processes that are also related to mdworker and these were also using memory.

It was all way too much for a 4 GB MacBook Pro.

The problem may have been exacerbated by plugging in two USB disks and a USB flash memory stick. Spotlight just went crazy trying to index everything and the Mac ground to a halt.

Stop Spotlight

The solution, although not a perfect one, is to turn off Spotlight because Spotlight runs the mdworker process to index the contents of disk drives.

Go to System Preferences and open Spotlight . Select the Privacy tab. Click the plus button at the bottom and add each of your disk drives and partitions.

This tells Spotlight not to index any of the disk drives or partitions. It causes mdworker to stop what it is doing and to discard any indexing that was taking place and the index it had already created.

Check Activity Monitor

Now mdworker is no longer using the huge amount of memory it required previously. There an mds process, but that’s only 61.5 MB. The memory pressure chart has turned green indicating that there are no longer any memory problems, the swap file and compressed memory usage is a fraction of what it was.

Adding all the disks to the Privacy tab does not stop Spotlight completely because there are many different components, including web searches, dictionary definitions and so on. What you won’t see are any files or apps in the search results. When Spotlight indexing is stopped, you can’t search for files. Open Finder and if it is set to show all your files by default, it will be empty. It seems that the results come from Spotlight, which is disabled.

Now that the Spotlight file index no longer exists, you may find that removing the disks, or at least the internal boot disk, from the Privacy tab in Spotlight System Preferences causes mdworker to act normally again.

Spotlight will index the disk contents once again and rebuild a brand new index. This will impact performance of the Mac a bit, but it should never be so bad you can’t use it, as was the case with my MacBook. When Spotlight has finished indexing the disk, mdworker will quieten down and Spotlight searches will work again.

Alternatively, you could leave Spotlight disabled with all the disks on the privacy tab and use some other search tool.

Всем здравствуйте! Сегодня хочу рассказать одну неприятную историю которая произошла с моим MacBook. А дело было так, одним зимним вечером я как всегда бродил по просторам интернета и вдруг заметил что мой Мак угрожающе загудел — кулеры начали работать на всю катушку и как следствие очень сильно стал нагреваться корпус.

Bird — что это за птица

Я сразу же залез в мониторинг системы и увидел что 98 % ресурсов ЦП пожирает некий Bird (с англ. птица) теперь задача стояла в том, что бы выяснить какая программа использует этот процесс и чем вызван такой расход ресурсов моего Мак. Но для начала я предположил, что возможно проблема решается принудительным завершением Bird, это помогло буквально на 2 минуты. Следующим шагом была перезагрузка компа — тоже тщетно.

Решение проблемы было найдено на одном из буржуйских сайтов, оказывается работа «птички» связана с , чтобы в этом убедиться я зашёл в настройки > iCloud и убрал галочку с этого пункта затем еще раз перезагрузил макбук и вуаля — мониторинг системы показал 93 % свободных ресурсов.

Все здорово, если бы мне было абсолютно плевать на этот iCloud Drive, но я из числа тех кто очень быстро адаптируется ко всем новым фишкам Apple и в дальнейшем уже не может без них обходиться, а значит следующая проблема заключалась в том как теперь вновь активировать облачное хранилище но уже без всяких там «птиц». Признаться честно я так и не узнал в чем кроется причина, просто через пару часов опять поставил галочку на место и с той поры вроде бы все здорово:). Будем считать, что это плавающий отказ, а если кто-то разобрался в этом нюансе более детально то обязательно пишите в комментариях.

mds, mds_stores, mdworker — «гаденыши» Spotlight

Следующие процессы которые могут доставить неприятные хлопоты носят имя mds_stores, mdworker и mds (все они из одной шайки). На самом деле это очень даже благородные процессы которые отвечают за индексацию данных на Mac, то есть, как многие уже догадались, напрямую сотрудничают со Spotlight. Но вот иногда эта троица (либо раздельно) может неоправданно сильно нагружать комп оставляя жалкие крохи свободной оперативки и ресурсов процессора.

А какие процессы Mac доставляли хлопоты вам? А также о других настигнувших проблемах и способах их решения обязательно пишите в комментарии, думаю всем будет интересно узнать.

If your Mac is suddenly running sluggish and you launched Activity Monitor, you may notice a process named ‘mds’ cranking away at 30% and even up to 90% CPU utilization. If you see this, don’t worry, it’s not abnormal behavior and your Mac isn’t crashing, it’s just indexing it’s built in search engine.

What is MDS in Mac OS?

mds stands for “metadata server” and the mds process is part of Spotlight, the amazingly powerful and very useful search feature built directly into the foundation of Mac OS X. You access Spotlight by hitting Command+Spacebar.

An easy way to identify that mds and Spotlight is indexing is to look at the Spotlight icon in the upper right corner of your menubar, when Spotlight is indexing the magnifying glass will have a dot in the center like so:

You can then click on the Spotlight icon and you’ll see your main hard drive being indexed, with a progress bar and estimated time until completion:

Is the mds process related to mdworker?

Yes. Usually you will see the mds process in conjunction with , which is another part of Spotlight and it’s indexing engine.

How long does mds & Spotlight take to finish indexing?

How long it takes to update the Spotlight index depends on a few variables, but mostly the size of your hard drive, the amount of data being indexed, major changes to the filesystem, and the time since last indexing. Just let the indexing complete, it generally takes between 15 and 45 minutes to complete.

If Spotlight isn’t working, you can check out these which will get you situated again. If you don’t ever use the search feature or just don’t like it, you can also and all of its indexing.

Related

Related articles:

  • No related posts

33 Comments

    I did not purchase a Mac so that it would tell me when I can work. I mistakenly believed that my Mac would work for me.

    Do not tell me that I am not as smart as Apple and that everything they do is “for my own benefit.”

    I found Time Machine Editor that lets me control when Time Machine runs.

    I need something similar for Spotlight.

    • Can’t help U with Spotlight scheduler, but I did learn that, what with the seemingly global effort to strip icons & buttons & such down to absolute minimum of overhead (presumably for WiFi and TeethOfBlue) by removing animations and 3D effects, there is a new, non-animated “Backup In Progress” telltale–an itty-bitty 2ND triangle, at the 8:00 position on the clock, just below (obviously) the tiny triangle at 9:00. I had found that the animation was useful (clock hands/triangle going around, clockwise) to cue me into when backup was giving me a performance whack. The movement, of course, would catch your eye–whereas with the new, non-animated (static?) menubar icon, you only have a split 2nd to see the 2nd triangle “move”–from off to on.

      Unrelated, sort of: Can’t figure out how to reduce the # of flashes “on mouse up”–time was we could select 3, 2, 1 or none. I found that 1 flash was just fine, but two and three flashes were an annoyance.

    […] or by hitting the “-” minus button in the lower left. Removing items will trigger the mds and mdworker processes to run again, and when finished the once excluded files will be searchable […]

    […] an upgrade from 10.6, 10.7, or 10.8, this is usually because of Spotlight and the mdworker & mds process combination, which irons itself out over the course of an hour or so. If waiting it out […]

    If you are using a using any P2P programs you may want to prevent Spotlight from searching your”incoming” directory. I discovered Spotlight was trying to index the partial files and was killing my performance. Once I added the directory to the list under System Preferences > Spotlight > Privacy my utilization went back down to normal.

    It’s a bit much to segue from a computer annoyance to a sweeping prediction of where Apple is going.

    If mds is going nuts evebn after reboot I would figure it is corruption somewhere. Perhaps reset the index to start from zero: http://support.apple.com/kb/HT2409?viewlocale=en_US&locale=en_US I am very sensitive to processes wasting power on my macbook (no laptoasters, thank you) and rarely have had a problem with mds or spotlight. The UI could use work though, like a lot of Apple stuff right now.

    This is only 1 example of what MDS does. On my machine its running at 63% with a secondary mdworker running at 115% and my spotlight is not indicating anything of a rebuild.

    This is a major pain in the butt. This happens randomly almost everyday. Spotlight is a bloated piece of junk software that appears to be thrown together by a group of people being rushed. Is not clean, its not smooth, Its not even smart enough to ignore the contents of a program and lists pieces of graphic art for the UI’s and app note files that any normal day to day user would NEVER search for.

    Apple is falling apart, loosing its shine, as sloppy programmers, Ideas and programming are poorly implemented and handed out to Users.

    Thank you for writing this really nice, simple explanation of mds. It’s been running at 75% on my mac and I didn’t know if it was some process that was hanging that I should kill. I wish you could schedule it without needing to know Terminal language.

    And I agree that Spotlight is wonderful and more people should know about it, and so a little praise about it is a good thing. Too bad Bugsman didn’t agree. I’m glad we know his opinion and can change the world to fit his preferences.

    I drifted to Alfred from Spotlight, though, because it displays results with big text, in the middle of the screen. I like that!

    I just started an initial time machine backup (on a new drive) and I noticed the mds and mdworker processes hitting the CPU in a big way.

    Does this mean that spotlight is now also indexing the backed-up files ?

    […] in Mac OS X Lion can be done with the help of the Terminal. The following command unloads the Spotlight mds agent from launchd, preventing the daemon from running or indexing any drives […]

    • My sys is hanging up for up to 30-60 seconds. AND I see that a root user process called mds is running using 99.8% CPU. AND there are 12 processes of mdworker among 2 users are using NO CPU%.

      This is supposed to be file indexing, that usually takes 45 minutes has been running for over 3 DAYS!!

      EVEN tho I have restarted computer twice during that 3 days.

      AND my Spotlight icon DOES NOT have a dot in the center.

      Can I force quit this process? Anychance it’s a virus masking as mds? I ran a MacKeeper scan just now and no files found.

      Should I do a disk utility repair disk permission?

      • MacKeeper is causing your problem, uninstall MacKeeper. Do not install MacKeeper again, it does not help anything.

        Then reboot your Mac and LET IT SIT for several hours to complete the indexing.

        How do you think it’s going to index if you keep restarting it and turning it off?

  1. my mds and mdworker is completely hogging my system and it has been going on for several week. I am suspecting that this is not a correct behavior. Does anyone know how to fix this permanently?

    My mds process is not hogging to the extent that you are describing but it is using a constant 254MB of virtual memory which is the top user on a periminant basis. Does that sound right? Is is a problem?

    Great article I have never noticed spotlight icon with a dot in the middle meaning that indexing is going on. Can you schedule it to happen when you decide not when the mac decides? “

    sudo ln -s /dev/null /System/Library/Frameworks/CoreServices.framework/Frameworks/Metadata.framework/Support/mds

    (For the sake of future Internet searchers finding this page: Just Kidding! Also -f flag left off intentionally. Whew!)

    The most important question, however, is “how do you shut down that stupid mds process that is taking up 2GB of memory?” Pertinent if you’re doing computing with your mac, and that silly program is at the top of your “top -o rsize” I just saw it there, found this helpful post, and decided to experiment. I did this command: “sudo killall mds” and it went away. Nothing else seems to have crashed, so I hesitantly recommend this as a possible one-time solution, with caution of course. :)

    Wait, never mind. It started up again. Anyone know how to disable it?

    […] do MDS and MDWorker have to do with Spotlight? The MDS process and mdworker processes usually run concurrently on your Mac when Spotlight is indexing your Mac. […]

    Contrary to BugsMan, I liked the short article. Thanks OS X Daily for posting these short tips and hints! I didn’t know (or had forgotten) what the dot in the center of the magnifying glass means. Now I know.

    BugsMan, maybe you find some tips below your level — you have after all “used Macs from the day they were launched” as you write — then just ignore those helpful hints and be happy that we are others that benefit from them, and be happy you already are in the know.

    And which particular Apple employee (Marketing Dept) wrote this?

    “What is MDS in Mac OS?

    “mds stands for “metadata server” and the mds process is part of Spotlight, the amazingly powerful and very useful search feature built directly into the foundation of Mac OS X. You access Spotlight by hitting Command+Spacebar.”

    I subscribe to this RSS feed because I have used Macs from the day they were launched; not to be bombasted with “the amazingly powerful …” hyperboles.

    • I wish I was an Apple employee!

      Seriously though, I’ve had enough people ask me about “my Mac is running slow randomly” and “what the heck is mds and mdserver?” that I felt it justified writing an explanation. We have a pretty diverse readership here from complete novice to expert and we try to accommodate that. You’re more than welcome to email us some topics, suggestions, or even your own tips to [email protected]

      I find Spotlight pretty handy and I use it constantly, so I tend to talk it up a bit, it’s not meant to convey any other message or agenda.

      • spotlight is driving me crazy. I want to disable it and I can’t. No matter what key that I hit, spotlight pops up. Pleeze help me.

          • Windows also stresses the HD a lot!

            With a PC he would get 15 problems more

      • “Spotlight, the amazingly powerful and very useful search feature built directly into the foundation of Mac OS X”

        Spotlight is a dysfunctional abomination that destroys your computer, economy and eventually your life.
        It only works in one mode. DISABLED!
        The brain farts at Apple do not understand how important it is NOT to cripple the customers home and workplace with a program that runs so wildly amok that i will pose a fire risk to your home.
        If they would just run the s#”T in nice mode, then you could forgive the sad unintelligent logic for not doing anything else than stealing CPU cycles.
        But the stupid process absolutely has to own you. WTF!