Spellcheck result can be gathered using SolrTemplage.execute
.
final String query = "foo"; //any value to be used in solr query
SpellcheckedPage<ExampleSolrBean> page = solrTemplate.execute(new SolrCallback<SpellcheckedPage<ExampleSolrBean>>() {
@Override
public SpellcheckedPage<ExampleSolrBean> doInSolr(SolrServer solrServer) throws SolrServerException, IOException {
SolrQuery q = new SolrQuery("name:"+query);
ModifiableSolrParams params = new ModifiableSolrParams() {
{
add("spellcheck.build", "true");
add("spellcheck.q", query);
add("spellcheck", "true");
}
};
q.add(CommonParams.QT, "/spell");
q.add(params);
QueryResponse response = solrServer.query(q);
//init page with search result
SpellcheckedPage<ExampleSolrBean> page = new SpellcheckedPage<ExampleSolrBean>(solrTemplate.getConverter().read(response.getResults(), ExampleSolrBean.class));
//add spellcheck result
SpellCheckResponse scr = response.getSpellCheckResponse();
for (Suggestion suggestion : scr.getSuggestions()) {
page.addSuggestions(suggestion.getToken(), suggestion.getAlternatives());
}
return page;
}
});
class SpellcheckedPage<T> extends SolrResultPage<T> {
public SpellcheckedPage(List<T> content) {
super(content);
}
private Map<String, List<String>> suggestions = new LinkedHashMap<String, List<String>>();
public void addSuggestions(String term, List<String> suggestions) {
this.suggestions.put(term, suggestions);
}
public Collection<String> getSuggestions(String term) {
return this.suggestions.get(term);
}
public Collection<String> getSuggestions() {
List<String> allSuggestions = new ArrayList<String>();
for (List<String> suggestions : this.suggestions.values()) {
allSuggestions.addAll(suggestions);
}
return allSuggestions;
}
}