【Solr4.7.0学习笔记】系列之一:Facet分组查询

时间:2022-09-16 12:25:02
 要求:输入“年级”可以统计出A表里面的“上地实验小学一年级(4条)上地实验小学二年级(2条)”分析思路:既要查询又要分组,而分组和查询最好分开写。所以你可以申明两个域,指向同一个字段一个用来查询,一个用来统计。再加上涉及到两张表,所以需要一个表连接查询。第一步:修改配置文件schema.xml【Solr4.7.0学习笔记】系列之一:Facet分组查询【Solr4.7.0学习笔记】系列之一:Facet分组查询这个uniquekey不能重复,classid在A表里面有重复。不可以第二步:修改mysql-data-config.xml【Solr4.7.0学习笔记】系列之一:Facet分组查询 第三步:java代码// solrj对Facet的支持,实现分组统计     public List<Classify> testFacet(String name, int i){            List<Classify> list= new ArrayList<Classify>();          Classify cEntity= null;           try {           HttpSolrServer server=SolrServer.getInstance ().getServer ();                    //智能分词-----------------------                   CharTermAttribute ta= null;                      String params= "";                    try {                                      IKAnalyzer analyzer = new IKAnalyzer();                                 //使用智能分词                        analyzer.setUseSmart( true);                        TokenStream Stream = analyzer.tokenStream("className" , new StringReader(name));                                 ta=Stream.addAttribute(CharTermAttribute. class);                        Stream.reset();                                       for (;Stream.incrementToken(); ) {                                                         params += "className:"+ta+" OR ";                                           }                        Stream.end();                   } catch (IOException e1) {                                    e1.printStackTrace();                   }          SolrQuery query = new SolrQuery();          query.setQuery("className:"+name);                   String para= "";           if(params != null){               if (params.lastIndexOf("OR" ) != -1)                   params= params.substring(0,params.lastIndexOf("OR" ));              para=params;          }              query.set( "q",para);          query.setRows(0);          query.setFacet( true);//设置facet=on                       query.addFacetField(new String[] {"cname" });//设置需要facet的字段                 query.setFacetLimit(100); //限制facet返回的数量          QueryResponse response = server.query(query);                    List<FacetField> facets = response.getFacetFields();//返回的facet列表                for (FacetField facet : facets) {                   List<Count> counts = facet.getValues();               for (Count count : counts) {                   cEntity= new Classify();                              System. out.println(count.getName() + ":" + count.getCount());//他是按照term去统计的                                    cEntity.setClassname(count.getName()+"("+count.getCount()+"条" +")" );//是出现的doc数                   list.add(cEntity);              }              System. out.println();          }          } catch (SolrServerException e) {                   e.printStackTrace();          }               return list;     }