How do I specify which key to use when searching data?

211 views Asked by At

I'm trying to ignore punctuation in a name field of my data by creating a sanitized_name field that is stripped of all non-word characters. I'm trying to make the query match the sanitized field and then display the corresponding unsanitized name (e.g. query of "title subtitle" matches {name: "title: subtitle!", sanitized_name: "title subtitle"} and displays "title: subtitle!" as suggestion). I haven't been able to get the query to match anything other than the unmodified name field, including all punctuation.

I think I've narrowed it down to Bloodhound never calling my datumTokenizer -- I've tried putting garbage in "datumTokenizer: ..." but it acts the same. This has been asked before at Why is my datumTokenizer never getting called? but I don't think it was satisfactorily answered. I have also tried emptying my cache and hard reloading on Chrome but it still isn't called.

Another quicker solution seems to be to just ignore all punctuation in the name field using Bloodhound.tokenizers.nonword, but since my datumTokenizer is never called, I haven't been able to try this.

I have also tried a template (Use different value from JSON data instead of displayKey using Typeahead) which successfully gives me the control to choose what to display in the suggestions, but I'm still internally searching by the name field. I don't know how to change what field I'm using to search.

If it matters, I'm using Typeahead.js 0.10.5, and the remote data is passed in from Searchkick running on Ruby on Rails 4.2.0 and is just an array of strings of the search hits in order.

Code:

  var games_object = new Bloodhound({
    datumTokenizer: function(d) {
      // Doesn't matter what's here
      console.log(d);
      return Bloodhound.tokenizers.obj.noasdfasdfnword("sanitized_name");
    },
    queryTokenizer: Bloodhound.tokenizers.nonword,
    // limit: 8,
    remote: {
      url: '/games/autocomplete?query=%QUERY',
      filter: function(results) {
        // console.log(results);
        return $.map(results, function(data) {
          return {
            "name": data,
            "sanitized_name": data
              .replace(/[^a-zA-Z0-9\s]/g, "")
              .replace(/\-/g, "")
              .replace(/\s+/, " ")
          };
        });
      },
    }
  });

  var games_promise = games_object.initialize();

  games_promise
    .done(function() { console.log('games searcher - success!'); })
    .fail(function() { console.log('games searcher - error!'); });

  $('#game_search').typeahead({
    highlight: true,
    minLength: 2
  }, {
    name: 'games',
    displayKey: 'name',
    source: games_object.ttAdapter(),
    templates: {
      header: "<h4 class='section-header'>Standalone games</h4>",
  });
0

There are 0 answers