org.pageseeder.flint.solr.query.AutoSuggest Maven / Gradle / Ivy
package org.pageseeder.flint.solr.query;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import org.apache.solr.client.solrj.SolrRequest.METHOD;
import org.apache.solr.client.solrj.SolrResponse;
import org.apache.solr.client.solrj.request.GenericSolrRequest;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.pageseeder.flint.Index;
import org.pageseeder.flint.solr.index.SolrIndexIO;
public class AutoSuggest {
private final SolrIndexIO _indexio;
private final String _name;
private Collection _dictionaries = new ArrayList<>();
private long lastBuilt = -1;
public AutoSuggest(Index index, String name) {
this(index, name, null);
}
public AutoSuggest(Index index, String name, Collection dictionaries) {
this._indexio = (SolrIndexIO) index.getIndexIO();
this._name = name;
if (dictionaries == null) this._dictionaries.add(name);
else this._dictionaries.addAll(dictionaries);
}
public String getName() {
return this._name;
}
public boolean isCurrent() {
return this.lastBuilt > 0 && this._indexio.getLastTimeUsed() < this.lastBuilt;
}
public List suggest(String text) {
return suggest(text, 10);
}
public List suggest(String text, int nb) {
return suggest(text, null, nb);
}
public List suggest(String text, String with, int nb) {
List suggestions = new ArrayList<>();
// build params
NamedList params = new NamedList<>();
params.add("suggest", "true");
for (String dic : this._dictionaries)
params.add("suggest.dictionary", dic);
params.add("suggest.q", text);
params.add("suggest.count", String.valueOf(nb));
params.add("suggest.build", String.valueOf(!isCurrent()));
if (with != null) {
params.add("suggest.cfq", with);
}
// build request
GenericSolrRequest suggest = new GenericSolrRequest(METHOD.GET, "/suggest", SolrParams.toSolrParams(params));
SolrResponse response = this._indexio.process(suggest);
if (response != null && response.getResponse() != null) {
this.lastBuilt = System.currentTimeMillis();
Object suggested = response.getResponse().get("suggest");
if (suggested != null && suggested instanceof Map) {
Map suggesters = (Map) suggested;
for (String name : suggesters.keySet()) {
Collection> list = (Collection>) ((NamedList