1. 程式人生 > >Solr-SolrJ 分頁查詢

Solr-SolrJ 分頁查詢

  1.  SolrUtil
    SolrUtil 增加分頁查詢的方法
       public static QueryResponse query(String keywords,int startOfPage, int numberOfPage) throws SolrServerException, IOException {
            SolrQuery query = new SolrQuery();
            query.setStart(startOfPage);
            query.setRows(numberOfPage);
            
            query.setQuery(keywords);
            QueryResponse rsp = client.query(query);
            return rsp;
        }
    public class SolrUtil {
        public static SolrClient client;
        private static String url;
        static {
            url = "http://localhost:8983/solr/how2java";
            client = new HttpSolrClient.Builder(url).build();
        }
     
        public static <T> boolean batchSaveOrUpdate(List<T> entities) throws SolrServerException, IOException {
     
            DocumentObjectBinder binder = new DocumentObjectBinder();
            int total = entities.size();
            int count=0;
            for (T t : entities) {
                SolrInputDocument doc = binder.toSolrInputDocument(t);
                client.add(doc);
                System.out.printf("新增資料到索引中,總共要新增 %d 條記錄,當前新增第%d條 %n",total,++count);
            }
            client.commit();
            return true;
        }
     
        public static QueryResponse query(String keywords,int startOfPage, int numberOfPage) throws SolrServerException, IOException {
            SolrQuery query = new SolrQuery();
            query.setStart(startOfPage);
            query.setRows(numberOfPage);
             
            query.setQuery(keywords);
            QueryResponse rsp = client.query(query);
            return rsp;
        }
     
    }
  2. TestSolr4j
    拿到分頁查詢的結果,遍歷出來
    public class TestSolr4j {
     
        public static void main(String[] args) throws SolrServerException, IOException {
            //查詢
            QueryResponse queryResponse = SolrUtil.query("name:手機",0,10);
            SolrDocumentList documents= queryResponse.getResults();
            System.out.println("累計找到的條數:"+documents.getNumFound());
            if(!documents.isEmpty()){
                 
                Collection<String> fieldNames = documents.get(0).getFieldNames();
                for (String fieldName : fieldNames) {
                    System.out.print(fieldName+"\t");
                }
                System.out.println();
            }
             
            for (SolrDocument solrDocument : documents) {
                 
                Collection<String> fieldNames= solrDocument.getFieldNames();
                 
                for (String fieldName : fieldNames) {
                    System.out.print(solrDocument.get(fieldName)+"\t");
                     
                }  
                System.out.println();
                 
            }
        }
     
    }