初学Redis常规操作(PHP)

什么是Redis?
REmote DIctionary Server 缩写
 一个基于内存的网络存储系统
丰富的数据结构(sets, sorted sets,hashes, list ...)
本质是key-value,但是与memcached不同的是,value的类型得到了扩展
 
用Hashes保存字段
$user = array(
'id' => 123,
'name' => 'joyqi',
'mail' => 'magike.net@gmail.com',
'created' => 1212312312
);
$redis->hMSet(‘user:123’, $user);
print_r($redis->hGetAll(‘user:123’));
[root@localhost redis]# php db1.php     
Array
(
    [id] => 123
    [name] => goith
    [age] => 12
)
 
用Sets保存关系
 

<?php
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);


$questionid = 123;
$tagids = array(11,22,33);
foreach( $tagids as $sort=>$tagid){

$redis->zAdd('question_tag:'.$questionid,$sort,$tagid);
}
$val = $redis->zRange('question_tag:123',0,-1);
print_r($val);
print_r("\n");

[root@localhost redis]# php db2.php
Array
(
[0] => 11
[1] => 22
[2] => 33
)

有了Redis,支持实时搜
索的门槛被大大降低
 
分词加Redis集合实现索引
 

$questionTitle = ‘搜索技术’;
$questionId = 123;
$words = fenci($questionTitle); // array(‘搜索’, ‘技术’);
foreach ($words as $word) {
$redis->zAdd(‘w:’ . md5($word), 1, $questionId);
}
// 索引完成

Redis集合Union操作实现查询
 

$keywords = ‘怎样实现搜索技术’;
$words = fenci($keywords); // array(‘怎样’, ‘实现’, ‘搜索’, ‘技术’);
$indexes = array_map(function ($word) {
return ‘w:’ . md5($word);
}, $words);
$redis->zUnion(‘result’, $indexes, array_fill(0, count($indexes), 1),
‘sum’);
print_r($redis->zRevRange(‘result’, 0, -1));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值