views:

163

answers:

2

Right now my autocomplete data lives on my server, which uses LIKE queries to find matches. Specifically, I'm taking the value of the "q" parameter, splitting it on whitespace, and looking for Songs that match every word: (using SearchLogic)

@songs = Song.sortable_name_like_all(params[:q].to_s.split)

Since I don't have many songs, I think the user experience might be better if I sent all the songs to the client at once, and then autocompleted based on that client-side data.

My server now returns a JSON array onready that looks like this:

[{"path":"/lyrics/Young-jeezy-ft-jay-z/Go-crazy-remix","song":"Young Jeezy (Ft. Jay-Z) - Go Crazy (Remix)"},{"path":"/lyrics/Young-jeezy-ft-jay-z/Put-on","song":"Young Jeezy (Ft. Jay-Z) - Put On"}]

And my autocomplete looks like this:

  $("input.quick_search").autocomplete(data, {
    formatItem: function(item) {
      return item.song;
    },
    formatResult: function(item) {
      return "Loading...";
    }
  }).result(function(event, choice, formatted) {
      if (choice) {
        window.location.href = choice.path;
      }
  }).click(function() { this.select(); });

But now the autocomplete uses an exact string match, meaning "young on" won't match "Young Jeezy (Ft. Jay-Z) - Put On".

How do I use a LIKE match here?

A: 

I think the best way would be to use regular expressions you can then take the input convert to a regular expression and test that your candidates against that expression.

A simple start would be to start with dot star .* end with .* and replace all white space in your search term with .*

Hope that is enough to start with.

David Waters
I think he would be better-served by tokenising the search string (by white-space, for instance), matching each token separately, and show the results sorted by score (number of tokens matched)
K Prime
+1  A: 

In JavaScript, you can achieve "LIKE"-style matching with indexOf. For example

var song = "Hello World Song";
if (song.indexOf("World") > -1) alert("World is in the song");

My only other comment is that your song list is likely to grow (I imagine) and you'll end up making calls to your server eventually - so why not do it now?

Sohnee