97

Suppose you have a LIST datatype in Redis. How do you delete all its entries? I've tried this already:

LTRIM key 0 0
LTRIM key -1 0

Both of those leave the first element. This will leave all the elements:

LTRIM key 0 -1

I don't see a separate command to completely empty a list.

Abdulrahman Bres
  • 2,603
  • 1
  • 20
  • 39
Paul A Jungwirth
  • 23,504
  • 14
  • 74
  • 93
  • 2
    @DavidJames: Consider it another way of spelling "foo." I'm following the convention used in Redis's own documentation: http://redis.io/commands/ – Paul A Jungwirth Aug 13 '12 at 19:59
  • Yes, in redis, all data structures are keys. That doesn't mean 'key' is useful in an example. Quite the opposite, I think. Using `mylist` would make your question clearer. For example, http://redis.io/commands/ltrim/ writes: `LTRIM mylist 1 -1`. The page you cite is a command *reference* and should not be considered a "convention" for making good examples. – David J. Aug 13 '12 at 20:41

7 Answers7

175

Delete the key, and that will clear all items. Not having the list at all is similar to not having any items in it. Redis will not throw any exceptions when you try to access a non-existent key.

DEL key

Here's some console logs.

redis> KEYS *
(empty list or set)
redis> LPUSH names John
(integer) 1
redis> LPUSH names Mary
(integer) 2
redis> LPUSH names Alice
(integer) 3
redis> LLEN names
(integer) 3
redis> LRANGE names 0 2
1) "Alice"
2) "Mary"
3) "John"
redis> DEL names
(integer) 1
redis> LLEN names
(integer) 0
redis> LRANGE names 0 2
(empty list or set)
Anurag
  • 140,337
  • 36
  • 221
  • 257
  • Is there a way to do that in one atomic operation? (both "LRANGE names 0 2" and "DEL names") – refaelos Oct 14 '13 at 10:44
  • 1
    One thing, using Del `may create extra overhead`, Time complexity: O(N) where N is the number of keys that will be removed. When a key to remove holds a value other than a string, the individual complexity for this key is O(M) where M is the number of elements in the list, set, sorted set or hash. Removing a single key that holds a string value is O(1). The [docs](http://redis.io/commands/del) – ChewOnThis_Trident May 15 '14 at 22:46
  • 3
    this method is dangerous as it also **remove the ttl** of the key – Saitama Mar 01 '16 at 15:11
22

UPDATE 06-11-2021

There Different ways to Remove all element from the List :

Step 1: Using General DEL Command for delete any key into Redis like Anurag's solution

DEL list

Step 2: Using LTRIM Command and Applying The next conditional from Documentation

if start is larger than the end of the list, or start > end, the result will be an empty list (which causes key to be removed).

SO any of next Commands will works or Mohd Abdul Mujib's solution

LTRIM list 999 0

LTRIM list 1 0

LTRIM list 4 1

But Take care about using negative numbers as The start index, as From Documentation

start and end can also be negative numbers indicating offsets from the end of the list, where -1 is the last element of the list, -2 the penultimate element and so on.

Next Command Will Remove all elements under list IF list include more than one elements BUT IF list include only one element will Not Remove any thing

LTRIM list -1 0

Explain

First Case (list include more than one elements) the index -1 as the start will translate to the last element which has 4 index(if list include 4 elements) SO the condition start > end has been applyed

Second Case (list include one elements) the index -1 as the start will translate to the last element which has 0 index SO the condition become start == end Not start > end

Here Example for Above commands:

redis 127.0.0.1:6379> RPUSH mylist four 1 3 1
(integer) 4
redis 127.0.0.1:6379> KEYS *
1) "test4"
2) "firstList"
3) "mylist"
redis 127.0.0.1:6379> LTRIM mylist 999 0
OK
redis 127.0.0.1:6379> KEYS *
1) "test4"
2) "firstList"
redis 127.0.0.1:6379> RPUSH mylist four 1 3 1
(integer) 4
redis 127.0.0.1:6379> KEYS *
1) "test4"
2) "firstList"
3) "mylist"
redis 127.0.0.1:6379> LTRIM mylist -1 0
OK
redis 127.0.0.1:6379> LRANGE mylist 0 -1
(empty list or set)
redis 127.0.0.1:6379> KEYS *
1) "test4"
2) "firstList"
redis 127.0.0.1:6379> RPUSH mylist four
(integer) 1
redis 127.0.0.1:6379> KEYS *
1) "test4"
2) "firstList"
3) "mylist"
redis 127.0.0.1:6379> LTRIM mylist -1 0
OK
redis 127.0.0.1:6379> KEYS *
1) "test4"
2) "firstList"
3) "mylist"
ahmed hamdy
  • 5,096
  • 1
  • 47
  • 58
  • Like mentioned in the comments of the accepted answer: DEL key will ALSO remove the ttl of the list – patrick Dec 25 '20 at 12:37
  • Please correct the false claim in your answer; it *is* possible to delete a list with a single value too: https://stackoverflow.com/a/51497664/4960855 – EliadL Oct 17 '21 at 19:27
  • @EliadL I updated my answer to clear my suggested solution which Still Correct (after Testing), Into given another solution he correct too, also his solution will works into all cases [list with one element or more than one elements] – ahmed hamdy Oct 18 '21 at 23:41
  • @ahmedhamdy Note that the opening sentence in your answer is still a false claim. – EliadL Oct 19 '21 at 09:29
  • @EliadL I edit my answer to be more clarify as previous answer not include false claim as The exactly command with same start and end indexes(on the opening sentence) were not remove all elements in some case like I mentioned, please try it to figure that correct, finally Thank you about yours comment – ahmed hamdy Nov 06 '21 at 15:51
6

Just use LTRIM. ...Aaaand the magic here is to use start greater than end.

LTRIM key 99 0

And...boom! there goes the whole list of elements. Just * pooof * right in front of your eyes!! No residue remaining, and absolutely no questions asked.

Note: This will cause the key to be "removed"(as in deleted) as described here

...if start is larger than the end of the list, or start > end, the result will be an empty list (which causes key to be removed).

Mohd Abdul Mujib
  • 13,071
  • 8
  • 64
  • 88
  • Is there a reason you prefer this over `DEL key` as in @Anurag's answer? It seems like they have the same effect. – Paul A Jungwirth Jul 24 '18 at 15:42
  • Frankly no, didn't get the time to look into the benchmarks, was just reading the docs when I discovered the above method, thought might as well mention it. – Mohd Abdul Mujib Jul 24 '18 at 15:55
  • 1
    Okay, thanks! Upvoted because I can imagine algorithms that use `LTRIM` repeatedly, and it's good to know what happens when the second parameter falls below the first. I can see how exploiting this behavior could make some code more elegant. – Paul A Jungwirth Jul 24 '18 at 17:13
0

This might be a late response but am sticking it here just in case someone still needs that functionality.

Short answer

ltrim mylist 0 - (n+1) where mylist is key and n is length of mylist.

Long answer

The way ltrim works is that, it takes two indices and return the elements that fall between them inclusive of the indices.

Ltrim list startIndex endIndex

Example assuming we have a redis list with key mylist containing 10 entries:

ltrim mylist 0 5 will trim the list to elements starting from index 0 through to index 5. And discard those that fall outside that range.

Fortunately redis list operations support negative indexing which proves extremely useful in some situations. Typically when you don't know the length of the list.

-1 refers to last element, - 2 penultimate element, etc. And (-n) is the first element.

Out of range indexes are not harmful. If the end index is greater than length of the list, redis treats it as equal to last index.

This is why ltrim mylist 0, -(n +1) clear the list. It does so because (-n) is equivalent to index 0. Adding 1 to it leaves no element within that range since that will be before the first element.

Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
  • Thanks for sharing your insights. As an extension to your answer, you could simply supply a value of N that is sufficiently larger than the list to guarantee that all items are deleted. For example `ltrim mylist 0 -99999`. – Dave Johnson Jan 06 '18 at 00:09
0

I tried this and it works for me. Just change myList for your list name and execute it redis-cli KEYS "myList:*" | xargs redis-cli DEL

idioto
  • 166
  • 2
  • 5
  • 1
    Although this works, `keys` is an extremely heavy operation that involves parsing every single key in your database, which is quite unnecessary in this case, or rather in most cases – Adalcar Nov 14 '18 at 10:29
0

Seems there is no atomic operation doing this. What I found out (example is in C# using StackExchange.Redis) is:

cacheDb.ListTrim(key, 0, 0); // remove all elements but the first one
cacheDb.ListLeftPop(key);    // then remove the first one

will remove all elements in two steps (where cacheDb is your database of type IDatabase which you are connected to, and key is of type RedisKey).

I think in cli syntax this will be:

LTRIM key 0 0
LPOP key

However, it seems to do the same as cacheDb.KeyDelete(key); (or in cli-syntax DEL key) - because in both cases the key isn't found any more.

Matt
  • 25,467
  • 18
  • 120
  • 187
-1

the accepted answer is wrong. suppose i have

redis 127.0.0.1:6379> KEYS * 
1) "newKey" 
2) "firstHash" 
3) "secondList" 
4) "test4" 
5) "firstList" 
6) "mylist" 

to use ahmed's example, which is actually correct. now, if i do:

DEL 'test4'

i end up with:

1) "newKey" 
2) "firstHash" 
3) "secondList" 
4) "firstList" 
5) "mylist"` 

so, i did not remove all entries from the 'test4' list, i removed test4 itself. not the same thing. not at all. i have a little app where the list keys are hashes computed from several data(well, aren't they all?), those lists sometimes are cleared, but the semantics of a empty list and a non-existent list are very different. so, no, i do not want to DEL 'myhashes', i want just to remove all entries.

beware, oh ye who wanders here.

deimosaffair
  • 333
  • 2
  • 4
  • If you look at the page cited below you'll see that in fact the semantics ARE the same! Taken [from](http://redis.io/topics/data-types#lists): `The LPUSH command inserts a new element on the head, while RPUSH inserts a new element on the tail. A new list is created when one of this operations is performed against an empty key. Similarly the key is removed from the key space if a list operation will empty the list. These are very handy semantics since all the list commands will behave exactly like they were called with an empty list if called with a non-existing key as argument.` – Dominic Jan 20 '14 at 08:46
  • from the horses mouth: "Similarly the key is removed from the key space if a list operation will empty the list." so, is { [], [], [] } === { [] } ? not for me. i guess we're in different topological spaces.... :) – deimosaffair Jan 22 '14 at 08:59
  • Well the initial question was how to delete an entire List in redis. so if you either delete the key or delete all entries and have the key automatically removed by redis gives the same result. So I'm not sure what you mean with { [], [], [] } === { [] }. – Dominic Jan 23 '14 at 09:49
  • Removing the last element from list is equal to deleting the key. This link even same for LIST as well (tested with RPOPLPUSH) https://www.bennadel.com/blog/2965-redis-doesn-t-store-empty-sets-or-hashes-and-will-delete-empty-sets-and-hashes.htm – Kanagavelu Sugumar Aug 03 '17 at 16:45