user2881338
user2881338

Reputation: 591

Redis: specific sorting results

I have data in my table of users ("nickname" field):

User Name
username2
username1
UserName
username4
username3

I want to sort it like this:

username1
username2
username3
username4
UserName
User Name

First to have text and numeric order, and then only text. How can I do this? Thanks for any help!

Upvotes: 0

Views: 102

Answers (2)

Niloct
Niloct

Reputation: 9995

Well, there are a few things you must clear up about the solution:

1) The kind of data structure you will use

Before dealing with SORT, you must store the data in some Redis structure. You have plenty of options for this case. Redis native data structures are: hashes, lists, sets, sorted sets and simple key/value.

You could use lists for this, like:

lpush mylist "User Name" username2 username1 UserName username4 username3

Notice that you have to enclose spaces in values with double quotes.

You could also use sets, the main difference between sets and lists is that sets only store distinct values (see the example below, in which a duplicated value is stored once):

127.0.0.1:6379> sadd sample_set avalue avalue
(integer) 1
127.0.0.1:6379> smembers sample_set
1) "avalue"

So with sets, you would go like:

sadd myset "User Name" username2 username1 UserName username4 username3

2) SORT lexicographically

You will use SORT, now when you want to sort lexicographically you must use the ALPHA modifier:

127.0.0.1:6379> sort mylist alpha
1) "User Name"
2) "UserName"
3) "username1"
4) "username2"
5) "username3"
6) "username4"

The sorted order for myset elements is identical.

127.0.0.1:6379> sort myset alpha
1) "User Name"
2) "UserName"
3) "username1"
4) "username2"
5) "username3"
6) "username4"

So you may have noticed that the order you stated you wanted is not quite equal to the common lexicographic order: space, numbers, uppercase letters, lowercase letters which follows the www.asciitable.com order.

Upvotes: 0

FazoM
FazoM

Reputation: 4956

According to documentation: http://redis.io/commands/SORT

Try:

SORT nickname

Upvotes: 1

Related Questions