Skip to content

Top k/commands #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions src/NRedisStack.Core/Auxiliary.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using StackExchange.Redis;

namespace NRedisStack.Core
{
public static class Auxiliary
{
public static List<object> MergeArgs(RedisKey key, RedisValue[] items)
{
var args = new List<object> { key };
foreach (var item in items) args.Add(item);
return args;
}
}
}
2 changes: 1 addition & 1 deletion src/NRedisStack.Core/CountMinSketch/CmsCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ public bool Merge(RedisValue destination, long numKeys, RedisValue[] source, lon
/// <param name="key">The name of the sketch</param>
/// <param name="items">One or more items for which to return the count.</param>
/// <returns>Array with a min-count of each of the items in the sketch</returns>
/// <remarks><seealso href="https://redis.io/commands/cms.merge"/></remarks>
/// <remarks><seealso href="https://redis.io/commands/cms.query"/></remarks>
public long[]? Query(RedisKey key, RedisValue[] items) //TODO: Create second version of this function using params for items input
{
if (items.Length < 1)
Expand Down
14 changes: 14 additions & 0 deletions src/NRedisStack.Core/ModulPrefixes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ public static class ModulPrefixes
static bool cmsCreated = false;
static CmsCommands cmsCommands;

static bool topKCreated = false;
static TopKCommands topKCommands;

static bool searchCreated = false;
static SearchCommands searchCommands;

Expand Down Expand Up @@ -55,6 +58,17 @@ static public CmsCommands CMS(this IDatabase db)
return cmsCommands;
}

static public TopKCommands TOPK(this IDatabase db)
{
if (!topKCreated)
{
topKCommands = new TopKCommands(db);
topKCreated = true;
}

return topKCommands;
}

static public SearchCommands FT(this IDatabase db)
{
if (!searchCreated)
Expand Down
41 changes: 39 additions & 2 deletions src/NRedisStack.Core/ResponseParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using NRedisStack.Core.Bloom.DataTypes;
using NRedisStack.Core.CuckooFilter.DataTypes;
using NRedisStack.Core.CountMinSketch.DataTypes;
using NRedisStack.Core.TopK.DataTypes;

namespace NRedisStack.Core
{
Expand All @@ -31,9 +32,9 @@ public static bool[] ToBooleanArray(RedisResult result)
return boolArr;
}

public static RedisResult[] ToArray(RedisResult result)
public static RedisResult[]? ToArray(RedisResult result)
{
return (RedisResult[])result;
return (RedisResult[]?)result;
}

public static long ToLong(RedisResult result)
Expand Down Expand Up @@ -295,6 +296,42 @@ public static IReadOnlyList<TimeSeriesRule> ToRuleArray(RedisResult result)
return new CmsInformation(width, depth, count);
}

public static TopKInformation? ToTopKInfo(RedisResult result) //TODO: Think about a different implementation, because if the output of CMS.INFO changes or even just the names of the labels then the parsing will not work
{
long k, width, depth;
double decay;

k = width = depth = -1;
decay = -1.0;

RedisResult[]? redisResults = (RedisResult[]?)result;

if (redisResults == null) return null;

for (int i = 0; i < redisResults.Length; ++i)
{
string? label = redisResults[i++].ToString();

switch (label)
{
case "k":
k = (long)redisResults[i];
break;
case "width":
width = (long)redisResults[i];
break;
case "depth":
depth = (long)redisResults[i];
break;
case "decay":
decay = (double)redisResults[i];
break;
}
}

return new TopKInformation(k, width, depth, decay);
}

public static TimeSeriesInformation ToTimeSeriesInfo(RedisResult result)
{
long totalSamples = -1, memoryUsage = -1, retentionTime = -1, chunkSize = -1, chunkCount = -1;
Expand Down
23 changes: 23 additions & 0 deletions src/NRedisStack.Core/TopK/DataTypes/TopKInformation.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
namespace NRedisStack.Core.TopK.DataTypes
{
/// <summary>
/// This class represents the response for CMS.INFO command.
/// This object has Read-only properties and cannot be generated outside a CMS.INFO response.
/// </summary>
public class TopKInformation
{
public long K { get; private set; }
public long Width { get; private set; }
public long Depth { get; private set; }
public double Decay { get; private set; }


internal TopKInformation(long k, long width, long depth, double decay)
{
K = k;
Width = width;
Depth = depth;
Decay = decay;
}
}
}
13 changes: 13 additions & 0 deletions src/NRedisStack.Core/TopK/Literals/CommandArgs.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace NRedisStack.Core.Literals
{
internal class TopKArgs
{
//public static string WEIGHTS => "WEIGHTS";
// public static string CAPACITY => "CAPACITY";
// public static string EXPANSION => "EXPANSION";
// public static string NOCREATE => "NOCREATE";
// public static string ITEMS => "ITEMS";
// public static string BUCKETSIZE => "BUCKETSIZE";
// public static string MAXITERATIONS => "MAXITERATIONS";
}
}
13 changes: 13 additions & 0 deletions src/NRedisStack.Core/TopK/Literals/Commands.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace NRedisStack.Core.Literals
{
internal class TOPK
{
public static string RESERVE => "TOPK.RESERVE";
public static string ADD => "TOPK.ADD";
public static string INCRBY => "TOPK.INCRBY";
public static string QUERY => "TOPK.QUERY";
public static string COUNT => "TOPK.COUNT";
public static string LIST => "TOPK.LIST";
public static string INFO => "TOPK.INFO";
}
}
160 changes: 160 additions & 0 deletions src/NRedisStack.Core/TopK/TopKCommands.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
using NRedisStack.Core.TopK.DataTypes;
using NRedisStack.Core.Literals;
using StackExchange.Redis;
namespace NRedisStack.Core
{

public class TopKCommands //TODO: Finish this
{
IDatabase _db;
public TopKCommands(IDatabase db)
{
_db = db;
}

/// <summary>
/// Increases the count of item by increment.
/// </summary>
/// <param name="key">The name of the sketch.</param>
/// <param name="item">Item to be added.</param>
/// <returns>Array of simple-string-reply - if an element was dropped from the TopK list, null otherwise</returns>
/// <remarks><seealso href="https://redis.io/commands/topk.add"/></remarks>
public RedisResult[]? Add(RedisKey key, RedisValue item)
{
return ResponseParser.ToArray(_db.Execute(TOPK.ADD, key, item));
}

/// <summary>
/// Increases the count of item by increment.
/// </summary>
/// <param name="key">The name of the sketch.</param>
/// <param name="items">Items to be added</param>
/// <returns>Array of simple-string-reply - if an element was dropped from the TopK list, null otherwise</returns>
/// <remarks><seealso href="https://redis.io/commands/topk.add"/></remarks>
public RedisResult[]? Add(RedisKey key, params RedisValue[] items)
{
var args = Auxiliary.MergeArgs(key, items);

return (RedisResult[]?)_db.Execute(TOPK.ADD, args);
}

/// <summary>
/// Returns count for an item.
/// </summary>
/// <param name="key">Name of sketch where item is counted</param>
/// <param name="item">Item to be counted.</param>
/// <returns>count for responding item.</returns>
/// <remarks><seealso href="https://redis.io/commands/cf.count"/></remarks>
public long Count(RedisKey key, RedisValue item)
{
return ResponseParser.ToLong(_db.Execute(TOPK.COUNT, key, item));
}

/// <summary>
/// Returns count for an items.
/// </summary>
/// <param name="key">Name of sketch where item is counted</param>
/// <param name="item">Items to be counted.</param>
/// <returns>count for responding item.</returns>
/// <remarks><seealso href="https://redis.io/commands/cf.count"/></remarks>
public long[]? Count(RedisKey key, params RedisValue[] items)
{
var args = Auxiliary.MergeArgs(key, items);
return ResponseParser.ToLongArray(_db.Execute(TOPK.COUNT, args));
}


/// <summary>
/// Increase the score of an item in the data structure by increment.
/// </summary>
/// <param name="key">Name of sketch where item is added.</param>
/// <param name="itemIncrements">Tuple of The items which counter is to be increased
/// and the Amount by which the item score is to be increased.</param>
/// <returns>Score of each item after increment.</returns>
/// <remarks><seealso href="https://redis.io/commands/topk.incrby"/></remarks>
public RedisResult[]? IncrBy(RedisKey key, params Tuple<RedisValue, long>[] itemIncrements)
{
if (itemIncrements.Length < 1)
throw new ArgumentException(nameof(itemIncrements));

List<object> args = new List<object> { key };
foreach (var pair in itemIncrements)
{
args.Add(pair.Item1);
args.Add(pair.Item2);
}
return ResponseParser.ToArray(_db.Execute(TOPK.INCRBY, args));
}

// //TODO: information about what?
/// <summary>
/// Return TopK information.
/// </summary>
/// <param name="key">Name of the key to return information about.</param>
/// <returns>TopK Information.</returns>
/// <remarks><seealso href="https://redis.io/commands/topk.info"/></remarks>
public TopKInformation? Info(RedisKey key)
{
var info = _db.Execute(TOPK.INFO, key);
return ResponseParser.ToTopKInfo(info);
}

/// <summary>
/// Return full list of items in Top K list.
/// </summary>
/// <param name="key">The name of the sketch.</param>
/// <param name="withcount">return Count of each element is returned.</param>
/// <returns>Full list of items in Top K list</returns>
/// <remarks><seealso href="https://redis.io/commands/topk.list"/></remarks>
public RedisResult[]? List(RedisKey key, bool withcount = false)
{
var result = (withcount) ? _db.Execute(TOPK.LIST, key, "WITHCOUNT")
: _db.Execute(TOPK.LIST, key);
return ResponseParser.ToArray(result);
}

/// <summary>
/// Returns the count for one or more items in a sketch.
/// </summary>
/// <param name="key">The name of the sketch</param>
/// <param name="item">Item to be queried.</param>
/// <returns><see langword="true"/> if item is in Top-K, <see langword="false"/> otherwise/></returns>
/// <remarks><seealso href="https://redis.io/commands/topk.query"/></remarks>
public bool? Query(RedisKey key, RedisValue item)
{
return _db.Execute(TOPK.QUERY, key, item).ToString() == "1";
}

/// <summary>
/// Returns the count for one or more items in a sketch.
/// </summary>
/// <param name="key">The name of the sketch</param>
/// <param name="items">Items to be queried.</param>
/// <returns>Bolean Array where <see langword="true"/> if item is in Top-K, <see langword="false"/> otherwise/></returns>
/// <remarks><seealso href="https://redis.io/commands/topk.query"/></remarks>
public bool[]? Query(RedisKey key, params RedisValue[] items)
{
if (items.Length < 1)
throw new ArgumentNullException(nameof(items));

var args = Auxiliary.MergeArgs(key, items);

return ResponseParser.ToBooleanArray(_db.Execute(TOPK.QUERY, args));
}

/// <summary>
/// Initializes a TopK with specified parameters.
/// </summary>
/// <param name="key">Key under which the sketch is to be found.</param>
/// <param name="topk">Number of top occurring items to keep.</param>
/// <param name="width">Number of counters kept in each array. (Default 8)</param>
/// <param name="depth">Number of arrays. (Default 7)</param>
/// <param name="decay">The probability of reducing a counter in an occupied bucket. (Default 0.9)</param>
/// <returns><see langword="true"/> if executed correctly, error otherwise/></returns>
/// <remarks><seealso href="https://redis.io/commands/topk.reserve"/></remarks>
public bool? Reserve(RedisKey key, long topk, long width = 7, long depth = 8, double decay = 0.9)
{
return ResponseParser.ParseOKtoBoolean(_db.Execute(TOPK.RESERVE, key, topk, width, depth, decay));
}
}
}
47 changes: 47 additions & 0 deletions tests/NRedisStack.Tests/TopK/TopKTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using Xunit;
using StackExchange.Redis;
using NRedisStack.Core.RedisStackCommands;
using Moq;

namespace NRedisStack.Tests.TopK;

public class TopKTests : AbstractNRedisStackTest, IDisposable
{
Mock<IDatabase> _mock = new Mock<IDatabase>();
private readonly string key = "TOPK_TESTS";
public TopKTests(RedisFixture redisFixture) : base(redisFixture) { }

public void Dispose()
{
redisFixture.Redis.GetDatabase().KeyDelete(key);
}

[Fact]
public void CreateTopKFilter()
{
IDatabase db = redisFixture.Redis.GetDatabase();
db.Execute("FLUSHALL");

db.TOPK().Reserve("aaa", 30, 2000, 7, 0.925);

var res = db.TOPK().Add("aaa", "bb", "cc");
Assert.True(res[0].IsNull && res[1].IsNull);

Assert.Equal(db.TOPK().Query("aaa", "bb", "gg", "cc"), new bool[] { true, false, true });

Assert.Equal(db.TOPK().Count("aaa", "bb", "gg", "cc"), new long[] { 1, 0, 1 });

var res2 = db.TOPK().List("aaa");
Assert.Equal(res2[0].ToString(), "bb");
Assert.Equal(res2[1].ToString(), "cc");

var tuple = new Tuple<RedisValue, long>("ff", 10);
var del = db.TOPK().IncrBy("aaa", tuple);
Assert.True(db.TOPK().IncrBy("aaa", tuple)[0].IsNull);

res2 = db.TOPK().List("aaa");
Assert.Equal(res2[0].ToString(), "ff");
Assert.Equal(res2[1].ToString(), "bb");
Assert.Equal(res2[2].ToString(), "cc");
}
}