以下是我项目中获取新闻数据列表的写法,包括数据总量、数据列表,接下来会贴出分片查询(facet)等高级查询
基本的注释都有了:
private ListPage<News> queryFromSolr(NewsQueryParameters queryParameters, Keyword keyword) { if (queryParameters == null) { throw new IllegalArgumentException("查询参数为空"); } ListPage<News> result = new ListPage<News>(); HttpSolrServer solrServer = SolrServer.getInstance().getServer(); SolrQuery sQuery = new SolrQuery(); try { String para = this.initKeywordQueryPara(keyword);//初始化para参数方法 int pageNo=queryParameters.getPageNo(); int pageSize=queryParameters.getPageSize(); sQuery.setStart((pageNo - 1) * pageSize);//设置起始页,类似于sql的分页查询 sQuery.setRows(pageSize);//设置每页大小,类似于sql的分页查询 //排序条件 sQuery.setSort("publishTime", SolrQuery.ORDER.desc); sQuery.setQuery(para);//这边的值大概是酱紫的 "* AND publishTime:[1360000 TO 13700000] AND contentStr:"关键字""; QueryResponse response = solrServer.query(sQuery,SolrRequest.METHOD.POST); SolrDocumentList list = response.getResults();//response.getResults()返回的类型是SolrDocumentList,solr文档集,所以用它来接收 Integer counts = (int) list.getNumFound();//获取总数,这个可以从solr Admin 管理页面里看出来,当我们去Query时,结果中也有一个numFound的属性 List<News> newsList = new ArrayList<News>(); for (SolrDocument solrDocument : list) { News news = null; String id = (String) solrDocument.getFieldValue("id");//这边是获取solr上有存储的字段,也就是我们在schema.xml文件里配置的field标签的stored属性,=true就会存储在solr服务器上,因为我的schema.xml只配置id的stored=true,所以这边我先通过获取id,在通过id去数据库获取具体的新闻信息 news = newsDAO.findById(id); if(news != null){ newsList.add(news); } } result.setCurrentPageSize(pageSize); result.setCurrentPageNo(pageNo); result.setTotalCount(counts); result.setDataList(newsList); return result; } catch (SolrServerException e) { log.error("查询solr失败", e); e.printStackTrace(); } finally{ solrServer.shutdown(); solrServer = null; } return result; }
public String initKeywordQueryPara(Keyword keyword){ String para = "*"; long dataTimeStart = 0; long dataTimeEnd = 0; if(keyword.getMonitoringBeginTime() != null){ dataTimeStart = keyword.getMonitoringBeginTime().getTime(); } if(keyword.getMonitoringEndTime() != null){ Date endTime = DateUtil.getNextDayCurrDay(keyword.getMonitoringEndTime(), 1); dataTimeEnd = endTime.getTime(); } para = para + " AND publishTime:[" + (dataTimeStart == 0 ? "*" : dataTimeStart) + " TO " + (dataTimeEnd == 0 ? "*" : dataTimeEnd) + "]"; String keywords = keyword.getKeywordName(); if(keywords !=null && keywords.length() > 0){ String[] targetArr = keywords.split(","); para = para + " AND ("; for (int i = 0; i < targetArr.length; i++) { if (i != 0) { para = para + " OR "; } para = para + "contentStr:"" + targetArr[i] + """; } para = para + ")"; }return para; }