Redis inserting out of order, or sorting oddly?

2020-04-11 04:52发布

问题:

I have some code written like this:

foreach ($models as $model) {
    Redis::hset('model_App\ServiceModel', $model[$primaryKey], json_encode($model->toArray()));
}

The models are ordered alphabetically by name field prior to the foreach (alpha, green, zed)

The data, once added to redis, looks something like this:

row  | key  | value
1     490   {"service_id":490, "name":"zed"}
2     489   {"service_id":489, "name":"alpha"}
3     491   {"service_id":491, "name": "green"}

Does anyone know why my ordering is being ignored / overwritten? Am I missing something about how redis works? Is 'row' like an auto incrementing id in a MySQL DB, and if so - how is it getting 'zed' before 'alpha'?

This is the first time I am 'seriously' using it, and I appreciate all the advice I can get.

回答1:

Redis' Hashes are unordered - that is the expected behavior. If sorting is needed, either look into using Sorted Sets, the SORT command, or (preferably) sorting the data in the client.



标签: redis