10.4: Some Spotlight tips and tricks

May 02, '05 12:56:00PM

Contributed by: Gremlins

Tiger only hintSpotLight uses a database at the backend. If the database is corrupted and you want to rebuild it (or if you just want to force a rebuild), you can do so:

In SpotLight system preferences, go to the Privacy tab and drag and drop the volume you want to re-index into the table. That will erase the index of that volume, as you've asked it to now be non-searchable. Just remove the volume from the table, and indexing will re-start and create a new database. This can also be achieved in the Terminal by using the following command:

sudo mdutil -E /path/to/volume
For example, sudo mdutil -E / will erase the boot volume database. See man mdutil for more options. Read the rest for some more advanced Terminal and Spotlight tips...

Advanced Searching:

While Apple provides an interface to do searches, it has some limitations. If you need to use more customized searches, you can do so either in the Terminal, or in a search window using Raw requests criteria (do a Finder Find, click Other, then Raw Query from the pop-up). The key commands are mdls, which allows you to list the metadata of a file, and mdfind, which actually performs searches. See the man pages for both commands to get more details. The interesting part is that mdfind actually supports logical operators (and, or, not, etc...), which can help to create advanced requests.

An additional way to find informations on how to write requests is to read the information in the finder of a Smart Folder (created by saving a search; do a Get Info on it). You will find the request sent to Spotlight, and can use that information to create your own searches.

Examples of requests:

$ mdfind -onlyin ~ "(kMDItemFSName =='*.htm*') && (kMDItemFSName !='*Favorites*')"
  /* Find all the files containing '.htm' but not 'Favorites' in your home folder */

$ mdfind -onlyin ~/Desktop/Test "kMDItemContentTypeTree = 'public.text'" 
  /* Find all Text documents in the Test folder of your Desktop folder */

$ mdfind "kMDItemFSLabel != '6'"
  /* Find files that are not labeled '6' (one of the available colors of labels) */
As you can see, you can do quite a bit with a raw-style query that you may not be able to do so easily via the GUI.

Comments (14)


Mac OS X Hints
http://hints.macworld.com/article.php?story=20050427030707455