(This post doesn't go into detail on the OpenSearch spec., check out the OpenSearch website and the guide by Mozilla if you're interested).
So recently I decided to implement OpenSearch on the Surge website. Now, Surge has two separate search pages for artists and individual tracks.
"Ideally", I muttered to myself, "I should like to implement both of these... using one search field"
Because really, I'd much rather have one search engine that does everything than a handful for individual but similar functions.
So the project really had two main parts to it:
- The simple part, searching the website
- And the slightly more complicated auto-complete function
The Simple Part
This was nice, just a case of mashing our two existing search pages into one. Display a list of matching artists, if any, and a list of matching tracks, if any. If a single artist or single track is matched the user is just taken straight to the relevant page.
It also interprets "[phrase] - [phrase]" as being "[artist] - [track]" or vice-versa. Which I thought was pretty cool but also comes in useful for the auto-suggest part.
Auto Suggest
The auto suggest function in OpenSearch works by querying a script which then returns suggestions in JSON format.
Primarily I was going to use MySQL's UNION function to combine a track search and an artist search into one list, but thinking about it a bit more I realised I needed the artist result first. Because ideally the suggestions should work in two modes.
- Matching on an artist or track
- Listing tracks from a matched artist
The second mode only kicks in if an exact match has been found for the artist or if only one artist
So the artist query searches the artist table and matches with "artist_name LIKE '%$keyword%'". Then count the rows and compare the artist name and keyword to decide which mode to put it in.
The track query, similarly, searches the track table and matches with "track_name LIKE '%$keyword%'". But if we're in mode 2. it also matches tracks whose artist id matches the one found from the artist search.
The next step is just mashing it all down into JSON code and printing it.
Job done.
