solr批量操作使用

批量新增操作

   /**
     * 批量新增索引
     * @param allDocList
     * @return
     * @throws IOException
     * @throws SolrServerException
     */
    public static Boolean batchAdd(List<AllDoc> allDocList){
        if(!CollectionUtils.isEmpty(allDocList)){
            try {
                int total = allDocList.size();
                int count=0;
                for (AllDoc allDoc : allDocList) {
                    SolrQuery solrQuery = new SolrQuery();
                    solrQuery.setQuery("content_type_ik:"+allDoc.getType()+" AND content_id_ik:"+allDoc.getContentId()+" AND website_id_ik:" +  allDoc.getWebsiteId());
                    QueryResponse response = client.query(solrQuery);
                    SolrDocumentList documentList = response.getResults();
                    if(documentList == null || documentList.size() == 0) {
                        SolrInputDocument documents = new SolrInputDocument();
                        String id = UUID.randomUUID().toString();
                        documents.addField("id", id);
                        documents.addField("title_ik", allDoc.getTitle());
                        documents.addField("website_id_ik", allDoc.getWebsiteId());
                        documents.addField("content_type_ik", allDoc.getType());
                        documents.addField("content_id_ik", allDoc.getContentId());
                        client.add(documents);
                        ++count;
                    }
                }
                logger.info("添加数据到索引中,总共要添加"+total+"条记录,实际添加第"+count+"条");
                client.commit();
                logger.info("批量添加数据到索引成功");
            }catch (Exception e){
                logger.error("批量新增索引失败");
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

根据条件批量删除索引

public static boolean deleteAllByQuery(String query){
        try {
            client.deleteByQuery(query);  //删除所有,把删除的条件设置为"*:*"就可以了
            client.commit();
            logger.info("索引批量删除成功");
        } catch (Exception e) {
            logger.error("批量删除索引失败");
            e.printStackTrace();
            return false;
        }
        return true;
    }

posted on 2020-01-10 14:41  惊涛随笔  阅读(1345)  评论(0编辑  收藏  举报

导航