redis实现像关系型数据库一样按条件高效查询分页

业务场景:redis以高效读取数据著称,我们常常把mysql、oracle等关系型数据库的数据存储在redis中,按照key=>value 这种查询是高效的,但是我们的需求是按多个条件组合来查询,如查询 select *from table where money>1000 and id not in(1,2,3,4) order by id,money asc limit 10 以下是代码片段

1、mysql数据转redis数据,并构建索引

           foreach($f_list as $key=>$f)
            {
                RDBX::instance('redis')->set('data:fins:'.$f['id'],json_encode($f));


                $tmp_idx_fins_id_arr[] = $f['id'];

                RDBX::instance('redis')->sAdd('idx:fins:source_type:'.$f['source_type'],$f['id']);
                RDBX::instance('redis')->sAdd('idx:fins:bill_day:'.$f['bill_day'],$f['id']);
                $tmp_idx_fins_money[] = $f['money'];
                $tmp_idx_fins_money[] = $f['id'];


                $tmp_source_type_arr[] = $f['source_type'];
                $tmp_bill_day_arr[] = $f['bill_day'];
                $tmp_money_arr[] = $f['money'];



                RDBX::instance('redis')->set('score:fins:invest_time:'.$f['id'],$f['invest_time']);
                RDBX::instance('redis')->set('score:fins:money:'.$f['id'],$f['money']);

                RDBX::instance('redis')->sAdd('idx:fins:client_id:'.$f['client_id'],$f['id']);


                $tmp_client_id_arr[] = $f['client_id'];

                RDBX::instance('redis')->set('score:fins:id:invest_time:'.$f['id'],$f['id'].$f['invest_time']);
                RDBX::instance('redis')->set('score:fins:id:money:'.$f['id'],$f['id'].$f['money']);



            }
            call_user_func_array(array(RDBX::instance('redis'), 'zAdd'), $tmp_idx_fins_money);
            call_user_func_array(array(RDBX::instance('redis'), 'sAdd'), $tmp_idx_fins_id_arr);
            call_user_func_array(array(RDBX::instance('redis'), 'sAdd'), $tmp_source_type_arr);
            call_user_func_array(array(RDBX::instance('redis'), 'sAdd'), $tmp_bill_day_arr);
            call_user_func_array(array(RDBX::instance('redis'), 'sAdd'), $tmp_money_arr);
            call_user_func_array(array(RDBX::instance('redis'), 'sAdd'), $tmp_client_id_arr);

以上代码用到了redis数据结构有 集合、有序集合,用到了集合的合并操作

2、实现按各种组合条件查询

    RDBX::instance('redis')->sDiffStore('sdiff_ids','idx:fins','not_fids','idx:fins:client_id:'.$this->linfo['fincncin_client_id']);
    $idx_fins_source_type_set = 'idx:fins:source_type:'.$this->linfo['source_type'];
    $idx_fins_bill_day_set = 'idx:fins:bill_day:'.$this->linfo['repay_day'];
    RDBX::instance('redis')->SinterStore('sinter_multi',$idx_fins_source_type_set,$idx_fins_bill_day_set,$money_set,'sdiff_ids');
    $sort=array('BY'=>$by_double,
        'SORT'=>'ASC',
        'GET'=>'data:fins:*',
        'LIMIT'=>array(0,$num)
    );
    $list =  RDBX::instance('redis')->sort('sinter_multi',$sort);
    原文作者:gordanhappy
    原文地址: https://segmentfault.com/a/1190000014684890
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞