5

My index objects has a city field and I'd like to retrieve these with autocomplete, but documentation seems missing about how to perform a query (only basic search documentation is available), I found a prototype IndexCore.prototype.searchForFacetValues in the autocomplete.js but I have no idea to use it.

Xia Pengda
  • 53
  • 2

1 Answers1

2

You should be able to use the following source:

var client = algoliasearch("YourApplicationID", "YourSearchOnlyAPIKey");
var index = client.initIndex("YourIndex");

autocomplete("#search-input", { hint: false }, [
  {
    source: function(query, callback) {
      index
        .searchForFacetValues({
          facetName: "countries",
          facetQuery: query
        })
        .then(function(answer) {
          callback(answer.hits);
        })
        .catch(function() {
          callback([]);
        });
    },
    displayKey: "my_attribute",
    templates: {
      suggestion: function(suggestion) {
        return suggestion._highlightResult.my_attribute.value;
      }
    }
  }
]);

This uses the searchForFacetValues method to get the results.

rayrutjes
  • 788
  • 11
  • 17
Haroen Viaene
  • 1,329
  • 18
  • 33
  • Strangely, it throws a `400 bad request` with `Cannot search in city attribute, you need to add searchable(city) to attributesForFaceting.` while I already configure it as searchable. – Xia Pengda Feb 08 '18 at 10:09
  • Are you sure you added it in that index? I think that’s the only reason that error can be thrown. Can you send an email to support@algolia.com if you can’t get it to work? – Haroen Viaene Feb 08 '18 at 10:18
  • 1
    Sorry, I missed something in the config, thanks for the answer. – Xia Pengda Feb 08 '18 at 10:20