Search code examples
ruby-on-railssolrsunspotsunspot-railssunspot-solr

Rails - How to use solr SuggestComponent with sunspot


I am using sunspot_rails gem for using Solr search library with Rails. I am trying to show suggestions for users when they enter search terms in my application like this

enter image description here

But I can't get the SuggestComponent working with sunspot. I referred this guide for suggest component and added the following to solrconfig.xml

  <searchComponent name="suggest" class="solr.SuggestComponent">
    <lst name="suggester">
      <str name="name">mySuggester</str>
      <str name="lookupImpl">AnalyzingInfixLookupFactory</str>
      <str name="dictionaryImpl">DocumentDictionaryFactory</str>
      <str name="field">name</str>
      <str name="weightField">price</str>
      <str name="contextField">cat</str>
      <str name="suggestAnalyzerFieldType">string</str>
      <str name="buildOnStartup">false</str>
    </lst>
  </searchComponent>

  <requestHandler name="/suggest" class="solr.SearchHandler" startup="lazy">
    <lst name="defaults">
      <str name="suggest">true</str>
      <str name="suggest.count">10</str>
    </lst>
    <arr name="components">
      <str>suggest</str>
    </arr>
  </requestHandler>

When I try the context filtering suggest query

http://localhost:8982/solr/development/suggest?suggest=true&suggest.build=true&suggest.dictionary=mySuggester&wt=json&suggest.q=c&suggest.cfq=memory

I am getting an empty response

{
   "responseHeader":{
      "status":0,
      "QTime":43
   },
   "command":"build",
   "suggest":{
      "mySuggester":{
         "c":{
            "numFound":0,
            "suggestions":[

            ]
         }
      }
   }
}

Any idea what am I doing wrong? Can anyone help me how to use SuggestComponent with sunspot gem? Thanks in advance


Solution

  • You don't need to use solr's suggest component. you just need to ensure that your solr gives back results for partial keyword search which can be done by adding the edge Ngram or Ngram filter factories(loads of tutorials for that), while you do it ensure you use bundle exec susnspot:solr:start since that will use the configuration saved in your codebase. Then you can use Twitter typeahead to implement auto complete.