当前位置:网站首页>MongDb的查询方式

MongDb的查询方式

2022-08-09 06:27:00 道阻且长-行则将至-行而不辍-未来可期

MongDb的使用方式,主要是业务逻辑如何使用的MongDb的方式


@Service
public class RsUserTagServiceImpl implements RsUserTagService {

    private final static int CATEGORY_RCMD_TYPE = 0;
    private final static String CATEGORY_RCMD_NAME = "推荐";

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RsRuleDao rsRuleDao;

    @Autowired
    private RsCategoryDao rsCategoryDao;

    @Autowired
    private RsCategoryInfoDao rsCategoryInfoDao;

    @Override
    public List<RsCategoryInfoVo> queryCategoryInfo() {
        List<RsCategoryInfoVo> list = new ArrayList<>();
        RsCategoryInfoVo categoryInfo = new RsCategoryInfoVo();
        categoryInfo.setCategoryType(CATEGORY_RCMD_TYPE);
        categoryInfo.setCategoryName(CATEGORY_RCMD_NAME);
        list.add(categoryInfo);
        List<RsCategoryInfo> rsCategoryInfos = rsCategoryInfoDao.selectCategoryInfoList();
        if(!CollectionUtils.isEmpty(rsCategoryInfos)){
            rsCategoryInfos.forEach(rsCategoryInfo -> {
                if(CATEGORY_RCMD_TYPE != rsCategoryInfo.getCategoryType().intValue()){
                    RsCategoryInfoVo rsCategoryInfoVo = new RsCategoryInfoVo();
                    rsCategoryInfoVo.setCategoryType(rsCategoryInfo.getCategoryType());
                    rsCategoryInfoVo.setCategoryName(rsCategoryInfo.getCategoryName());
                    list.add(rsCategoryInfoVo);
                }
            });
        }
        return list;
    }

    @Override
    public PageVo<RsUserVo> queryUserTag(int pageNum, int pageSize, String userId) {
        PageVo<RsUserVo> page = new PageVo<>(pageNum, pageSize);
        if(StringUtils.isBlank(userId)){
            Aggregation aggregation = Aggregation.newAggregation(Aggregation.group(new String[] { "c_innerUid" }));
            List<Map> result = this.mongoTemplate.aggregate(aggregation, "rs_user_tags", Map.class).getMappedResults();
            if (CollectionUtils.isEmpty(result)) {
                page.setTotal(0);
                page.setRecords(new ArrayList<>());
                return page;
            }
            page.setTotal(result.size());
            long skip = Long.parseLong (String.valueOf((pageNum - 1) * pageSize));
            aggregation = Aggregation.newAggregation(new AggregationOperation[] {
                    Aggregation.group(new String[] { "c_innerUid" }).first("c_innerUid").as("c_innerUid"),
                    Aggregation.sort(Sort.Direction.ASC, new String[] { "c_innerUid" }), Aggregation.skip(skip), Aggregation.limit(pageSize) });
            result = this.mongoTemplate.aggregate(aggregation, "rs_user_tags", Map.class).getMappedResults();
            if (CollectionUtils.isEmpty(result)) {
                return null;
            }
            List<RsUserVo> records = new ArrayList<>(result.size());
            for (Map m : result) {
                RsUserVo user = new RsUserVo();
                user.setUserId(m.get("c_innerUid").toString());
                // 根据用户id查询标签
                user.setTags(getTagsByUserId(user.getUserId()));
                records.add(user);
            }
            page.setRecords(records);
        }else{
            Set<String> set = getTagsByUserId(userId);
            List<RsUserVo> records = new ArrayList<>();
            if(null == set){
                page.setTotal(0);
            }else{
                page.setTotal(1);
                RsUserVo user = new RsUserVo();
                user.setUserId(userId);
                user.setTags(set);
                records.add(user);
            }
            page.setRecords(records);
        }
        return page;
    }

    @Override
    public List<RsTagVo> queryTagByUserId(int pageNum, int pageSize, String userId, String tagSource) {
//        Scan scan = new Scan();
//        String startRow = MD5Utils.getMd5(userId) + "\001" + " ";
//        String endRow = MD5Utils.getMd5(userId) + "\001" + "?";
//        scan.setStartRow(Bytes.toBytes(startRow));
//        scan.setStopRow(Bytes.toBytes(endRow));
//        scan.setCaching(1000);
//        List<RsUserRuleIndex> rsUserRuleIndexList = this.hbaseTemplate.find(newsRepo + ":rcmd_user_rule_uid_index", scan, new RsUserRuleIndexMapper());
//        if(CollectionUtils.isEmpty(rsUserRuleIndexList)){
//            return Lists.newArrayList();
//        }
//        List<Get> getList = new ArrayList<>();
//        rsUserRuleIndexList.forEach(userRule -> {
//            getList.add(new Get(Bytes.toBytes(userRule.getIndex())));
//        });
//        List<RsUserRule> rsUserRuleList = this.hbaseTemplate.getByGetList(newsRepo + ":rcmd_user_rule", getList, new RsUserRuleMapper());
//        if(CollectionUtils.isEmpty(rsUserRuleList)){
//            return Lists.newArrayList();
//        }
//        Map<Integer,RsRuleVo> ruleMap = this.getRuleMap();
//        Map<Integer,String[]> categoryMap = this.getRuleCategoryMap();
//        Map<String, Long> newsCountMap = this.groupByUserIdAndTagId(userId);
//        List<RsTagVo> records = new ArrayList<>(rsUserRuleList.size());
//        rsUserRuleList.forEach(rsUserRule -> {
//            RsRuleVo rule = ruleMap.get(rsUserRule.getRuleType());
//            if(null != rule){
//                RsTagVo tag = new RsTagVo();
//                tag.setTagId(rsUserRule.getRuleName());
//                String[] tags = rsUserRule.getRulePath().split("\\u0001");
//                tag.setTagName(tags[tags.length-1]);
//                tag.setRule(rule);
//                tag.setRulePath(rsUserRule.getRulePath());
//                tag.setRulePathArr(tags);
//                tag.setRuleType(rsUserRule.getRuleType());
//                tag.setTagWeight(rsUserRule.getWeight());
//                tag.setOwnColumn(categoryMap.get(rsUserRule.getRuleType()));
//                tag.setNewsCount(null == newsCountMap.get(tag.getTagId()) ? 0L : newsCountMap.get(tag.getTagId()));
//                records.add(tag);
//            }
//        });
//        //根据标签权重降序排列
//        return records.stream().sorted(Comparator.comparing(RsTagVo::getRuleType))
//                .collect(Collectors.toList());
        return Collections.emptyList();
    }

    @Override
    public PageVo<RsNewsVo> queryNewsByTagId(int pageNum, int pageSize, String tagId, String userId, Integer recommend) {
        Query query = new Query();
        // 设置起始数
        query.skip((pageNum - 1) * pageSize);
        // 设置查询条数
        query.limit(pageSize);
        Criteria criteria = new Criteria();
        Pattern pattern = Pattern.compile("^.*" + tagId + ".*$", Pattern.CASE_INSENSITIVE);
        criteria.and("c_reason").regex(pattern);
        if(StringUtils.isNotBlank(userId)){
            criteria.and("c_innerUid").is(userId);
        }
        if(null != recommend){
            criteria.and("i_isRecommended").is(recommend);
        }
        query.addCriteria(criteria);
        query.with(new Sort(Sort.Direction.DESC, "d_weight"));
        List<RsUserNews> rsUserNews = this.mongoTemplate.find(query, RsUserNews.class, "rs_user_news");
        long total = mongoTemplate.count(query, RsUserTag.class, "rs_user_news");
        PageVo<RsNewsVo> page = new PageVo<>(pageNum, pageSize);
        page.setTotal(total);
        page.setRecords(getRsNewsList(rsUserNews));
        return page;
    }

    @Override
    public PageVo<RsNewsVo> queryNewsByUserId(int pageNum, int pageSize, String userId, String newsId, Integer newsCategory, Integer recommend) {
        Query query = new Query();
        // 设置起始数
        query.skip((pageNum - 1) * pageSize);
        // 设置查询条数
        query.limit(pageSize);
        Criteria criteria = Criteria.where("c_innerUid").is(userId);
        if(StringUtils.isNotBlank(newsId)){
            criteria.and("c_newsId").is(newsId);
        }
        if(null != newsCategory){
            criteria.and("i_category").is(newsCategory);
        }
        if(null != recommend){
            criteria.and("i_isRecommended").is(recommend);
        }
        query.addCriteria(criteria);
        query.with(new Sort(Sort.Direction.DESC, "d_weight"));
        List<RsUserNews> rsUserNews = this.mongoTemplate.find(query, RsUserNews.class, "rs_user_news");
        long total = this.mongoTemplate.count(query, RsUserTag.class, "rs_user_news");
        PageVo<RsNewsVo> page = new PageVo<>(pageNum, pageSize);
        page.setTotal(total);
        page.setRecords(getRsNewsList(rsUserNews));
        return page;
    }

    // 根据用户id查询标签
    private Set<String> getTagsByUserId(String userId) {
        // 根据用户id查询所有标签从mongo
        Query query = new Query();
        Criteria criteria = new Criteria();
        criteria.and("c_innerUid").is(userId);
        query.addCriteria(criteria);
        query.with(new Sort(Sort.Direction.DESC, "d_weight"));
        List<RsUserTag> rsUserTags = this.mongoTemplate.find(query, RsUserTag.class, "rs_user_tags");
        if (CollectionUtils.isEmpty(rsUserTags)) {
            return null;
        }
        Set<String> set = new HashSet<>();
        rsUserTags.forEach(userTag -> {
            if (StringUtils.isNotBlank(userTag.getTagName())){
                set.add(userTag.getTagName());
            }
        });
        return set;
    }

    private List<RsNewsVo> getRsNewsList(List<RsUserNews> rsUserNews){
//        Map<Integer, String> categoryNameMap = getCategoryNameMap();
//        List<RsNewsVo> records = new ArrayList<>();
//        List<Get> getList = new ArrayList<>();
//        if (!CollectionUtils.isEmpty(rsUserNews)) {
//            rsUserNews.forEach(userNews -> {
//                getList.add(new Get(Bytes.toBytes(StringUtils.reverse(userNews.getNewsId()))));
//            });
//            List<RsNewsRepository> rsNewsRepositoryList = this.hbaseTemplate.getByGetList(newsRepo + ":rcmd_news_repository", getList, new RsNewsMapper());
//            Map<String, RsNewsRepository> newsRepositoryMap = new HashMap<>();
//            if(!CollectionUtils.isEmpty(rsNewsRepositoryList)){
//                rsNewsRepositoryList.forEach(rsNewsRepository -> {
//                    newsRepositoryMap.put(rsNewsRepository.getNewsId(), rsNewsRepository);
//                });
//            }
//            rsUserNews.forEach(userNews -> {
//                records.add(getRsNewsVo(userNews, categoryNameMap, newsRepositoryMap));
//            });
//        }
//        return records;
        return Collections.emptyList();
    }
//
//    /*
//     * *
//     *
//     * @Description 根据RsUserNews创建RsNewsVo
//     *
//     * @Author 
//     *
//     * @Date 2019/6/6
//     *
//     * @Param [userNews]
//     *
//     * @return com.gildata.threebody.tbm.api.vo.RsNewsVo
//     **/
//    private RsNewsVo getRsNewsVo(RsUserNews userNews, Map<Integer,String> categoryNameMap, Map<String, RsNewsRepository> newsRepositoryMap) {
//        RsNewsVo news = new RsNewsVo();
//        news.setNewsId(userNews.getNewsId());
//        news.setNewsWeight(userNews.getWeight());
//        news.setEnterRcmdTime(userNews.getSaveTime());
//        news.setPubTime(userNews.getPubTime());
//        news.setTagWeight(userNews.getTagWeight());
//        news.setOwnColumn(categoryNameMap.get(userNews.getCategory()));
//        news.setCategory(userNews.getCategory());
//        news.setRecommend(userNews.getIsRecommended());
        RsNewsRepository rsNewsRepository = newsRepositoryMap.get(userNews.getNewsId());
        if (null != rsNewsRepository) {
            news.setNewsTitle(rsNewsRepository.getTitle());
            news.setGrabTime(rsNewsRepository.getRecordTime());
            news.setUrl(rsNewsRepository.getUrl());
            List<RsNewsRepository.Tag> tags = rsNewsRepository.getTags();
            if (!CollectionUtils.isEmpty(tags)) {
                Set<Map<String,Object>> tagMapSet = new HashSet<>();
                tags.forEach(tag -> {
                    if (StringUtils.isNotBlank(tag.getTagValue())) {
                        Map<String,Object> tagMap = new HashMap<>();
                        tagMap.put("tagName", tag.getTagValue());
                        tagMap.put("tagWeight", tag.getTagWeight());
                        tagMapSet.add(tagMap);
                    }
                });
                news.setTags(tagMapSet);
            }
        }
//        return news;
//    }

    private Map<Integer,RsRuleVo> getRuleMap(){
        Map<Integer,RsRuleVo> ruleMap = new HashMap<>();
        List<RsRule> rules = rsRuleDao.selectRuleList();
        if(!CollectionUtils.isEmpty(rules)){
            rules.forEach(rule -> {
                RsRuleVo rsRuleVo = new RsRuleVo();
                rsRuleVo.setRuleType(rule.getRuleType());
                rsRuleVo.setRuleName(rule.getRuleName());
                ruleMap.put(rule.getRuleType(), rsRuleVo);
            });
        }
        return ruleMap;
    }

    private Map<Integer,String[]> getRuleCategoryMap(){
        Map<Integer,String[]> categoryMap = new HashMap<>();
        List<RsRuleCategory> rsRuleCategories = rsCategoryDao.selectCategoryNamesGroupByRuleType();
        if(!CollectionUtils.isEmpty(rsRuleCategories)){
            rsRuleCategories.forEach(rsRuleCategory -> {
                categoryMap.put(rsRuleCategory.getRuleId(), rsRuleCategory.getCategories().split(","));
            });
        }
        return categoryMap;
    }

    private Map<Integer,String> getCategoryNameMap(){
        Map<Integer,String> map = new HashMap<>();
        List<RsCategoryInfo> rsCategoryInfos = rsCategoryInfoDao.selectCategoryInfoList();
        if(!CollectionUtils.isEmpty(rsCategoryInfos)){
            rsCategoryInfos.forEach(rsCategoryInfo -> {
                map.put(rsCategoryInfo.getCategoryType(), rsCategoryInfo.getCategoryName());
            });
        }
        return map;
    }

    /* *
     * @Description 根据用户id和tagId统计资讯数量
     * @Author 
     * @Date   2019/6/14 
     * @Param  [userId]
     * @return java.util.Map<java.lang.String,java.util.Map<java.lang.String,java.lang.Long>>
     **/
    private Map<String,Long> groupByUserIdAndTagId(String userId){
        Criteria criteria = Criteria.where("c_innerUid").is(userId);
        GroupBy groupBy = new GroupBy("c_innerUid", "c_tagId");
        groupBy.initialDocument("{ count: 0 }").reduceFunction("function (doc,pre){pre.count +=1 ;}");
        GroupByResults<RsUserTagNewsCount> result = this.mongoTemplate.group(criteria, "rs_user_news", groupBy, RsUserTagNewsCount.class);
        Map<String,Long> map = new HashMap<>();
        result.forEach(groupByResult -> {
            map.put(groupByResult.getC_tagId(), groupByResult.getCount());
        });
        return map;
    }

原网站

版权声明
本文为[道阻且长-行则将至-行而不辍-未来可期]所创,转载请带上原文链接,感谢
https://blog.csdn.net/m0_59252007/article/details/126230438