Redis how to store associative array? Set or Hash or List?

后端 未结 3 1830
孤独总比滥情好
孤独总比滥情好 2021-01-30 04:24

I\'m a bit confused with all the available storing options of Redis. I want to do something simple and I don\'t want to over engineer it. I\'m working with phpredis

相关标签:
3条回答
  • 2021-01-30 05:02

    In PHP you can just do

    $redis->set($key, json_encode($value));
    

    Then

    $value = json_decode($redis->get($key));
    

    Or use whatever serialization technique you prefer. JSON encode/decode was performant enough for me not to care.

    0 讨论(0)
  • 2021-01-30 05:06

    Just for the folks looking for the PHP code, here is what I've ended up using:

    // Create a post hash
    $key = 'post:'.$post->getId();
    $this->redis->hSet($key, 'data', serialize($post->toArray()));
    
    // Add a post in the account posts SET
    $this->redis->sAdd($account->getId().':posts', $post->getId());
    
    // You can execute the above code as many time as you need 
    // to add an object in a SET
    
    // Fetch the first $limit posts for this account
    // SORT <account_id>:posts BY nosort GET <account_id>:post:*->data
    $key = $account->getId().':posts';
    $keys = $this->redis->sort($key, array(
        'by' => 'nosort',
        'limit' => array($offset, $limit),
        'get' => 'post:*->data'
    ));
    
    // All Good !
    var_dump($keys);
    

    I hope this will help some of you ;)

    0 讨论(0)
  • 2021-01-30 05:09

    You can use SET and Hash and SORT in combination

    redis 127.0.0.1:6379> HMSET TEST_12345 name "Post A" val2 "Blah Blah" val3 "Blah Blah Blah"
    OK
    redis 127.0.0.1:6379> HMSET TEST_54321 name "Post B" val2 "Blah Blah" val3 "Blah Blah Blah"
    OK
    redis 127.0.0.1:6379> HMSET TEST_998877 name "Post C" val2 "Blah Blah" val3 "Blah Blah Blah"
    OK
    redis 127.0.0.1:6379> SADD All_keys TEST_12345 TEST_54321 TEST_998877
    (integer) 3
    redis 127.0.0.1:6379> HGETALL TEST_12345
    

    To GET one HASH:

    redis 127.0.0.1:6379> HGETALL TEST_12345
    1) "name"
    2) "Post A"
    3) "val2"
    4) "Blah Blah"
    5) "val3"
    6) "Blah Blah Blah"
    

    TO GET All HASH

    redis 127.0.0.1:6379> SORT All_keys BY nosort GET *->name GET *->val2 GET *->val3
    1) "Post A"
    2) "Blah Blah"
    3) "Blah Blah Blah"
    4) "Post B"
    5) "Blah Blah"
    6) "Blah Blah Blah"
    7) "Post C"
    8) "Blah Blah"
    9) "Blah Blah Blah"
    

    If you don't want to use sort you can use Fetch All the key names from SET using SMEMBERS and then use Redis Pipeline to fetch all the keys

    0 讨论(0)
提交回复
热议问题