Solr的Suggest用法代码示例

Solr4.7版本,使用Solr的Suggest功能代码样例:

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.util.NamedList;

public class SolrSuggest {

    private HttpSolrServer solr = new HttpSolrServer(
            "http://localhost:8080/solr/collection1");

    private static final String REQUEST_HANDLER = "/suggest";

    private static final String SUGGEST_DICTIONARY = "mySuggester";

    private int _count = 0;
    private int _status = 0;
    private int _QTime = 0;

    public int getCount() {
        return this._count;
    }

    public int getStatus() {
        return this._status;
    }

    public int getQTime() {
        return this._QTime;
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public List<String> getSuggest(String query) {
        SolrQuery solrQuery = new SolrQuery();
        solrQuery.setRequestHandler(REQUEST_HANDLER);
        solrQuery.set("suggest.dictionary", SUGGEST_DICTIONARY);
        solrQuery.set("suggest.q", query);

        QueryResponse response = null;
        try {
            response = solr.query(solrQuery);
        } catch (SolrServerException e) {
            e.printStackTrace();
        }

        List<String> rtn = new ArrayList<String>();
        if (response != null) {
            this._status = response.getStatus();
            this._QTime = response.getQTime();

            NamedList<Object> result = response.getResponse();
            Map map = (Map) result.get("suggest");
            NamedList nvPairs = (NamedList) map.get(SUGGEST_DICTIONARY);
            nvPairs = (NamedList) nvPairs.get(query);

            this._count = Integer.parseInt(nvPairs.get("numFound").toString());

            List<NamedList> lst = (List<NamedList>) nvPairs.get("suggestions");
            for (int i = 0; i < lst.size(); i++) {
                System.out.println(lst.get(i).get("term"));
                rtn.add(lst.get(i).get("term").toString());
            }
        }

        return rtn;
    }
}

你可能感兴趣的:(java,Solr)