admin管理员组

文章数量:1122832

I have following code which is counting total number of records in the redis database.

public int Count()
{
    var server = _conn.GetServer(_conn.GetEndPoints().First());
    int count = 0;
    var cursor = 0L;
    do
    {
        var keys = server.Keys(cursor: cursor, pattern: GetPattern(), pageSize: batchSize);
        count += keys.Count();
    } while (cursor != 0);

    return count;
}

as per Redis documentation server.Keys is using SCAN to iterate through all the keys, and SCAN returns the cursor value. but with this code I am not getting the cursor value. any idea how can I update the value of cursor?

I have following code which is counting total number of records in the redis database.

public int Count()
{
    var server = _conn.GetServer(_conn.GetEndPoints().First());
    int count = 0;
    var cursor = 0L;
    do
    {
        var keys = server.Keys(cursor: cursor, pattern: GetPattern(), pageSize: batchSize);
        count += keys.Count();
    } while (cursor != 0);

    return count;
}

as per Redis documentation server.Keys is using SCAN to iterate through all the keys, and SCAN returns the cursor value. but with this code I am not getting the cursor value. any idea how can I update the value of cursor?

Share Improve this question asked yesterday ANEESANEES 3003 silver badges16 bronze badges 1
  • can you try calling the server.Keys in your do..while loop with a ref cursor, instead ? eg. var keys = server.Keys(cursor: ref cursor, pattern: GetPattern(), .... the reason to call using ref is such that the method can update the value. Otherwise i believe your code will end up in an infinite loop. – mna Commented yesterday
Add a comment  | 

1 Answer 1

Reset to default 0

The issue you're encountering is because the server.Keys method in StackExchange.Redis does not directly expose the cursor value. Instead, you need to use the IScanningCursor interface to handle the cursor manually.

You can try like this:

public int Count()
{
    var server = _conn.GetServer(_conn.GetEndPoints().First());
    int count = 0;
    var cursor = 0L;
    do
    {
        var result = server.Keys(cursor: cursor, pattern: GetPattern(), pageSize: batchSize);
        cursor = result.Cursor; // Update the cursor value
        count += result.Count();
    } while (cursor != 0);

    return count;
}

In this code, result is an IScanningCursor object that contains the cursor value. By updating the cursor variable with result.Cursor, you ensure that the loop continues correctly until all keys are scanned.

本文标签: How to update cursor value in Redis SCANcStack Overflow