Reading view

There are new articles available, click to refresh the page.

How to search successfully in Spotlight: Saved Search

The ability to save Spotlight searches is perhaps its most underused feature. This article explains how Saved Search and Smart Folders work, and how you can use them to your advantage.

Save a search

Open a new Finder window and turn it into a Find window using the Find command at the foot of the File menu. Leave its search box blank, and set up one or more search bars with criteria that find some files of interest.

Then click on the Save button at the upper right, just below the search box. In the save dialog, set the saved location to an accessible folder such as ~/Documents, leave the Add To Sidebar checkbox empty, and click Save.

Close that Find window, and select your Saved Search ‘folder’ in the Finder. That will display the same files you just found in that search, as if it was a normal folder. Select any of those files, though, and you’ll see that they’re not really there, and their paths are for the original file, as if they were symbolic links, perhaps.

You can now move that Saved Search around, even copy it to another Mac, and wherever it goes it performs the same search and shows the results. Open Get Info on the Saved Search item and it’s described as a Saved Search Query, and the predicate used internally by Spotlight for that search is shown as its Query.

Edit a search

Now double-click on the Saved Search item to open it in its own window, and click on the Action tool (the circle containing an ellipsis …) and select the Show Search Criteria item in the menu. This restores your original Find window, complete with all its original settings, search bars, and their contents.

You can now change that search, and it will update to show the new results. To save your modified search, click on the Save button at the upper right, and the Saved Search will be duly updated.

Saved Search and Smart Folders

You can do exactly the same starting from the Finder’s New Smart Folder command in its File menu, as that creates a new Find window with identical features. The end results are the same, a file of type com.apple.finder.smart-folder. Only, as you’ll have gathered by now, this isn’t a real folder at all, just a property list that the Finder handles in an unconventional way.

Open the .savedSearch file using a text editor (you can make that easier by changing its extension to .plist if you wish), and you’ll see that it doesn’t even list the files ‘contained’ by this ‘folder’, all it gives is the search predicate used by Spotlight to find the items that are shown as being inside it.

That predicate, also shown as the Query in the Get Info dialog, is saved in the property list against its RawQuery key. Much of the rest of the property list is devoted to details enabling the Finder to reconstruct the Find window should you should decide to Show Search Criteria. But nowhere does it list any of the items found in the search.

This ensures that Saved Searches and Smart Folders take almost no space, just a few KB for that property list, and unless they’re open and displaying the search results, they don’t take any memory either.

They also don’t behave like regular folders. You can’t add items to them except by changing the search criteria used. You can only copy items from them, and can’t remove anything either. If you duplicate a Saved Search then you simply get another copy of the property list, not the items found by it. Their contents are also dynamic: create another item that meets their search criteria, and that will automatically be added to their contents, hence the alternative name of Smart Folder.

They’re also versatile and can have several roles:

  • to return to a search still in progress;
  • to set defaults for future Find windows, laid out ready for fresh searches;
  • as records of important searches you might wish to repeat;
  • as templates for types of search you’re likely to repeat.

They’re also the only place that I’m aware of that provides a bridge between searches made using the GUI in the Finder, and the terms and format of predicates used internally and by mdfind. This is important, as Saved Searches are themselves of no use in the command line, but their Query string can be used directly, as I’ll demonstrate in a later article.

Key points

  • Saved Search = Smart Folder;
  • they aren’t folders at all, but reconstruct and replay the search in a Find window;
  • change the search by opening the Saved Search and using Show Search Criteria in the Action menu;
  • their Query gives the search predicate used.

How to search successfully in Spotlight: GUI tools

The most common problem reported in Spotlight search is failure to find target file(s). In this series of articles, I’ll examine what can go wrong, and how you can make local searches more successful using features in macOS. I’m well aware that there are other utilities for searching, some relying on Spotlight, others working independently, but here I’ll confine myself as much as possible to what’s provided in macOS.

Successful searches using Spotlight have four essential requirements:

  • The target file(s) must have had their metadata added to Spotlight’s volume indexes.
  • Those metadata must be accessible to the tool used to perform the search.
  • The search queries used must be capable of finding the target(s).
  • Spotlight’s search must work correctly.

spotlightsteps1

Check indexes and access

The first of those can be checked using the mdimport command tool in Terminal, using the command
mdimport -t -d3 [filepath]
where [filepath] is the path of the file. You can vary the digit used in the -d3 option from 1-3, with larger numbers delivering more detail. For -d3 you’ll first be given the file type and mdimporter used, following which all the data extracted is given according to its Spotlight attributes:
Imported '/Users/hoakley/Documents/SpotTestA.rtf' of type 'public.rtf' with plugIn /System/Library/Spotlight/RichText.mdimporter.
37 attributes returned

followed by a long list.

If the file hasn’t been indexed, this article works through the steps you can take to rectify that. Note that recent experience is that using mdutil -E / to erase and force rebuild of indexes on the Data volume may not work as expected, and you should either perform this in System Settings, or using the command mdutil -E /System/Volumes/Data

Which tool?

Global Spotlight is accessed through the 🔍 magnifying glass icon in the right of the menu bar, or using the default key combination of Command-space. This includes website content, and isn’t ideal when you’re searching for local files. If you want to use this as an easy gateway to local search, enter the text you want to search for and scroll down to use the command Search in Finder, which opens a Finder Find window for the results of that search query. Alternatively, you can click on Show More in the Documents section of the search results.

Local Spotlight can also be opened by the Find command at the foot of the Finder’s File menu, and takes you straight to its search box, at the right of the toolbar in that Finder window.

This window offers a choice of two search scopes at the upper left. The first covers all the accessible contents of that Mac, and the second is the folder open in that window when it was converted to a Find window. To set the scope for a local Spotlight search, start from a normal Finder window with the target folder open, then use the Find command on that.

Searching

Typing text into the search box at the right of the toolbar then performs live or incremental search for both filenames and content at the same time, or you can select one of them in the menu.

Text entered into the search box can simply be the start of a word in the target, or can be a basic search query such as name:"target"*cdw. I will explain those in a later article about search queries.

Instead of, or in addition to, entering text in the search box, you can set further search criteria in search bars below that.

In this case, the file Name is required to contain the string entered in the text box. Add more of these search bars for additional criteria to narrow your search.

Search attributes

In search bars, the first popup sets the metadata attribute to use in the query. For example, both Name and Filename refer to the name of the file, although Name is given in its localised form. Many more options are available by selecting the Other… item at the foot of the attribute menu. You can either set those as a one-off, or add them to the menu of attributes if you’re likely to use them again. These roughly correspond to the metadata attributes as in formal Spotlight search queries used elsewhere, although their names are different.

The second popup sets the operator to be used. While they may appear self-explanatory, two merit fuller explanation as they may work differently from how you might expect:

  • matches finds the start of words found by breaking the whole string at word boundaries (see below). Thus it will find danger and danger-es in one-danger-est, but won’t find anger there.
  • contains is applied without reference to word boundaries, and simply finds the given string, regardless of what characters occur before or after that. Thus it will find anger in dangerous. It has one unusual behaviour, though: it ignores hyphens, so dangeres will be found in the string danger-est.

Word boundaries

These are crucial in search queries run from the search box in a Find window, and the matches operator used in a search bar below. Although the search box claims to use the contains operator, it actually behaves as the matches operator does in a search bar.

In many languages word roots and meaning appear at the start of words, with declensions and conjugations at the end. If you want to find words related to harvest, like harvester, harvesting and harvested, then you’re going to enter a search query using harvest rather than vest. Like other search engines designed for live or incremental search, Spotlight is fastest when searching for the start of words. It therefore divides compound words often used for filenames into component words. It does so using rules for word boundaries laid down in the International Components for Unicode.

In practice, word boundaries include a space, the underscore _, hyphen – and changes of case used in CamelCase. Spotlight treats each of the following examples as three words:
one target two
one_target_two
one-target-two
OneTargetTwo

Languages other than English may allow other word boundaries, but those are the most common.

The rules recognise that hyphens are difficult, and Spotlight makes them even trickier as it can ignore them altogether when searching for an arbitrary string without word boundaries, and will then happily find netargett in one-target-two! Spotlight also struggles with multiple hyphens mixed with underscores. For example, it may not be able to find danger in the file name a_a-b-c-e-danger_z.txt when using matches, but should work as expected when using contains instead.

Other tools in macOS

In-app search or Core Spotlight relies on search features provided by the app, for example that in Mail. Although these use Spotlight’s indexes and its query language, their function is different from Global or Local Spotlight, and implemented through a distinct Core Spotlight API.

The primary command tool for performing Spotlight search is mdfind, which uses formal query strings and predicates. I’ll tackle those in a future article.

Recommendations for successful search

  • To perform local search of files indexed by Spotlight, use a Find window in the Finder.
  • Limit search scope by folder when possible, by opening the folder in a Finder window then converting it into a Find window using the menu command.
  • For the quickest results, type the start of a distinctive word in the file name or content into the search box.
  • For the most inclusive results, leave the search box empty and construct a series of search bars to limit the list of hits.
  • Limit the type of files when possible, using the Kind metadata attribute in the first popup menu.
  • For file names with a limited number of hyphens and underscores as word boundaries, use Name matches with the start of a word included in the localised file name.
  • For file names with more word boundaries, use Name contains with a distinctive target string.

I’m very grateful to Aldous and to Thomas Tempelmann for their unstinting help in understanding word boundaries and their importance, and for solving the mystery of Cleta.

Searching for the file that won’t be found

Searching for a file with a distinctive word in its name should be straightforward, but here I show some weird problems that could catch you out. I’m very grateful to Sam for drawing my attention to this, and welcome all and any rational explanations of what’s going on.

In some accounts of ancient Greek mythology, Cleta (Κλήτα) was one of the two Charites or Graces, alongside Phaenna. Her name apparently means renowned, and is still occasionally used as a first name today. It’s not the sort of word that should give Spotlight any cause for concern, and should prove easy to find.

Demonstration

To see the problems it can cause, create a folder somewhere accessible, in ~/Documents perhaps, and create half a dozen files with the names shown below.

Now open a new Finder window, and set it to Find mode using that command at the foot of the File menu. Then type into its search box the letters cleta

Only four of the files in that folder are found, excluding the first two, despite the fact that all their names clearly contain the search term.

Now clear the search box, and in the search criterion below, set it to find Name contains cleta, which you might have thought would be the same as the previous search.

Now all six files are found successfully.

You can try other variations of the file name to see which can be found using the search box, and which remain hidden. For example,
1995z_spectacletable_01.txt
also appears susceptible to this problem, suggesting that other examples might have the form
[digits]_[chars]cleta[chars]_[digits].[extension]

Separators

There are some other oddities at work as well, that you can see in the four file names that haven’t yet played hide and seek. So far I’ve been using Spotlight to find file names that simply contain the characters cleta. Now extend that to cletapainting

While you would expect the second of those to appear, Spotlight has elided the hyphen embedded in the first, as if it wasn’t there. Although Spotlight doesn’t provide a simple way to search for discrete words in file names, that’s a feature readily accessible in several third-party search utilities, including Find Any File and HoudahSpot. If you use Spotlight much, both of those are essentials, and you may wish to add Alfred as well.

As expected, Find Any File has no problems in finding all six test files when looking for names containing cleta

Set it to find names containing the word cleta, though, and it recognises spaces, hyphens and underscore _ characters as word separators, but doesn’t oblige with CamelCase, whether or not you capitalise its initial character.

Conclusions

  • Avoid using the characters cleta in file names, as they can confuse Spotlight.
  • Leave the search box in the Finder’s Find window empty and construct your search in the lower search bars instead.
  • Spotlight can overlook hyphens in file names, but does treat them as word separators.
  • Searching for words in file names can treat spaces, hyphens and underscore _ characters as word separators, but can’t cope with CamelCase.
  • Spotlight’s rules are largely unwritten. Apple’s brief account is here, and doesn’t even mention the name Cleta.

My thanks again to Sam for providing me with the example of cleta that made this possible if apparently highly improbable.

Postscript

For those who think this all works as they expect, try the following file name:

1995z_star-post-office-cleta-hunt-portrait_01.txt

❌