Saturday, December 13, 2008

Spotlight on the command line

In addition to the traditional command line search programs, locate and find, OS X provides a command line interface to the Spotlight search system (mdfind).

While I can't find it documented anywhere, my guess is that "mdfind" stands for "meta data find".

Simple spotlight search

mdfind searchterm

Search in a specific directory

mdfind -onlyin /Users/keithw searchterm

Search for specific meta data

mdfind "kMDItemAuthor == '*Donaldson*'"

List available meta data fields

mdls filename

Turn off spotlight indexing for a volume

mdutil -i off volumename

Turn on spotlight indexing for a volume

mdutil -i on volumename

Show the status of spotlight indexing for a volume

mdutil -s volumename

How spotlight does its magic

Unlike the locate program and database, spotlight recognizes and indexes file system changes almost immediately. How is that possible? The magic happens in the kernel, which sends notices of file system changes to a special character device named /dev/fsevents. Spotlight monitors this special device and learns about new files that need to be indexed. There is no published API for /dev/fsevents, as far as I can tell.