From cfeb817ba2ccd28e0e8de8f7f7a992bb8bdef8de Mon Sep 17 00:00:00 2001 From: shacharPash <93581407+shacharPash@users.noreply.github.com> Date: Wed, 27 Sep 2023 13:06:45 +0300 Subject: [PATCH] Clean warnings (#184) * delete mock * coverage * fix test * indent * change to var - check * cluster test * add opthin to connect cluster with dotnet test * use key in topk tests * get env vars inside RedisFixture * skip if redis * add skip where needed * Execute broadcast * delete cluster tests * RedisFixture fix * add to contributing * run cluster on CI * wip * fix / * -d * delete restore * return restore * add -RC3 * add RC3 to docker-compose * try define both .net 6 and 7 * Skip if cluster where needed * add names * skip configOnTimeout if cluster * try to fix win tests * tests names +fix win version * fix versions * versions * win verer * wording * dotnet format * Clean Warnings * dataType not nullable * cleaning * TS warnings * all warnings? * more fixes * string format error * warnings * more * format * clean all warnings? * fix more warnings * clean almost all warnings * hope its all --------- Co-authored-by: Chayim --- Examples/AdvancedJsonExamples.md | 89 +++++- Examples/AdvancedQueryOperations.md | 94 ++++-- Examples/AsyncExample.md | 2 +- Examples/BasicJsonExamples.md | 165 ++++++++-- Examples/BasicQueryOperations.md | 113 +++++-- Examples/ConvertSearchResultToJson.md | 15 +- Examples/HsetAndSearch.md | 22 +- Examples/PipelineExample.md | 12 +- Examples/PipelineWithAsync.md | 6 + .../CuckooFilter/ICuckooCommands.cs | 2 +- .../CuckooFilter/ICuckooCommandsAsync.cs | 2 +- .../CuckooFilter/Literals/CommandArgs.cs | 12 +- src/NRedisStack/Gears/GearsCommandBuilder.cs | 2 +- src/NRedisStack/Gears/GearsCommands.cs | 4 +- src/NRedisStack/Gears/GearsCommandsAsync.cs | 4 +- src/NRedisStack/Graph/DataTypes/Edge.cs | 4 +- src/NRedisStack/Graph/DataTypes/Node.cs | 2 +- src/NRedisStack/Graph/DataTypes/Path.cs | 4 +- src/NRedisStack/Graph/GraphCache.cs | 11 +- src/NRedisStack/Graph/GraphCacheList.cs | 9 +- src/NRedisStack/Graph/GraphCommands.cs | 1 + src/NRedisStack/Graph/GraphCommandsAsync.cs | 1 + src/NRedisStack/Graph/Header.cs | 14 +- src/NRedisStack/Graph/Record.cs | 4 +- src/NRedisStack/Graph/RedisGraphUtilities.cs | 6 +- src/NRedisStack/Graph/ResultSet.cs | 85 +++--- src/NRedisStack/Graph/Statistics.cs | 40 +-- .../Json/DataTypes/KeyValuePath.cs | 2 +- src/NRedisStack/Json/JsonCommandBuilder.cs | 6 +- src/NRedisStack/Json/JsonCommands.cs | 4 +- src/NRedisStack/Json/JsonCommandsAsync.cs | 8 +- src/NRedisStack/ModulePrefixes.cs | 1 + src/NRedisStack/Pipeline.cs | 2 + src/NRedisStack/ResponseParser.cs | 81 ++--- src/NRedisStack/Search/AggregationRequest.cs | 4 +- src/NRedisStack/Search/AggregationResult.cs | 8 +- .../Search/DataTypes/InfoResult.cs | 34 +-- src/NRedisStack/Search/Document.cs | 22 +- src/NRedisStack/Search/FTCreateParams.cs | 14 +- src/NRedisStack/Search/FTSpellCheckParams.cs | 12 +- src/NRedisStack/Search/FieldName.cs | 4 +- src/NRedisStack/Search/Group.cs | 2 +- src/NRedisStack/Search/Limit.cs | 16 +- src/NRedisStack/Search/Query.cs | 30 +- src/NRedisStack/Search/Reducer.cs | 4 +- src/NRedisStack/Search/Row.cs | 2 +- .../Search/SearchCommandBuilder.cs | 10 +- src/NRedisStack/Search/SearchCommands.cs | 8 +- src/NRedisStack/Search/SearchCommandsAsync.cs | 6 +- src/NRedisStack/Search/SearchResult.cs | 16 +- src/NRedisStack/Tdigest/TdigestCommands.cs | 2 +- .../DataTypes/TimeSeriesInformation.cs | 24 +- .../TimeSeries/DataTypes/TimeSeriesTuple.cs | 2 +- .../TimeSeries/DataTypes/TimeStamp.cs | 2 +- .../TimeSeries/ITimeSeriesCommands.cs | 4 +- .../TimeSeries/ITimeSeriesCommandsAsync.cs | 4 +- src/NRedisStack/TimeSeries/TimeSeriesAux.cs | 6 +- .../TimeSeries/TimeSeriesCommands.cs | 7 +- .../TimeSeries/TimeSeriesCommandsAsync.cs | 5 +- .../TimeSeries/TimeSeriesCommandsBuilder.cs | 4 +- src/NRedisStack/TopK/TopKCommandBuilder.cs | 2 +- src/NRedisStack/TopK/TopKCommands.cs | 2 +- src/NRedisStack/TopK/TopKCommandsAsync.cs | 2 +- src/NRedisStack/Transactions.cs | 6 +- tests/Doc/HashExample.cs | 2 +- tests/Doc/SearchQuickstartExample.cs | 2 +- tests/Doc/SetGetExample.cs | 2 +- .../CuckooFilter/CuckooTests.cs | 20 +- .../Examples/ExampleTests.cs | 26 +- tests/NRedisStack.Tests/Gears/GearsTests.cs | 2 +- tests/NRedisStack.Tests/Graph/GraphTests.cs | 288 ++++++++++-------- .../Graph/Utils/PathBuilderTest.cs | 2 +- tests/NRedisStack.Tests/Json/JsonTests.cs | 23 +- tests/NRedisStack.Tests/Person.cs | 2 +- tests/NRedisStack.Tests/PipelineTests.cs | 72 ++--- tests/NRedisStack.Tests/RedisFixture.cs | 1 + tests/NRedisStack.Tests/Search/SearchTests.cs | 181 ++++++----- .../TimeSeries/TestAPI/TestAdd.cs | 10 +- .../TimeSeries/TestAPI/TestAddAsync.cs | 9 +- .../TimeSeries/TestAPI/TestAlter.cs | 8 +- .../TimeSeries/TestAPI/TestAlterAsync.cs | 7 +- .../TimeSeries/TestAPI/TestCreate.cs | 5 + .../TimeSeries/TestAPI/TestCreateAsync.cs | 3 + .../TimeSeries/TestAPI/TestDecrBy.cs | 13 +- .../TimeSeries/TestAPI/TestDecrByAsync.cs | 12 +- .../TimeSeries/TestAPI/TestDel.cs | 1 + .../TimeSeries/TestAPI/TestGet.cs | 3 +- .../TimeSeries/TestAPI/TestIncrBy.cs | 13 +- .../TimeSeries/TestAPI/TestIncrByAsync.cs | 12 +- .../TimeSeries/TestAPI/TestMADD.cs | 3 +- .../TimeSeries/TestAPI/TestMAddAsync.cs | 3 +- .../TimeSeries/TestAPI/TestRange.cs | 1 + .../TimeSeries/TestAPI/TestRules.cs | 1 + .../TimeSeries/TestAPI/TestRulesAsync.cs | 1 + .../TestTimeSeriesInformation.cs | 14 +- .../TimeSeries/TimeSeriesTests.cs | 2 +- tests/NRedisStack.Tests/TopK/TopKTests.cs | 40 +-- tests/NRedisStack.Tests/TransactionsTests.cs | 47 +-- 98 files changed, 1196 insertions(+), 728 deletions(-) diff --git a/Examples/AdvancedJsonExamples.md b/Examples/AdvancedJsonExamples.md index aa597d74..e9f33e5d 100644 --- a/Examples/AdvancedJsonExamples.md +++ b/Examples/AdvancedJsonExamples.md @@ -1,24 +1,30 @@ # Advanced JSON + Redis JSON array filtering examples + ## Contents -1. [Business Value Statement](#value) -2. [Data Set](#dataset) -3. [Data Loading](#dataload) -4. [Array Filtering Examples](#arrayfiltering) - 1. [All Properties of Array](#allprops) - 2. [All Properties of a Field](#allfield) - 3. [Relational - Equality](#equality) - 4. [Relational - Less Than](#lessthan) - 5. [Relational - Greater Than or Equal](#greaterthan) - 6. [Logical AND](#logicaland) - 7. [Logical OR](#logicalor) - 8. [Regex - Contains Exact](#regex_exact) - 9. [Regex - Contains, Case Insensitive](#regex_contains) - 10. [Regex - Begins With](#regex_begins) + +1. [Business Value Statement](#value) +2. [Data Set](#dataset) +3. [Data Loading](#dataload) +4. [Array Filtering Examples](#arrayfiltering) + 1. [All Properties of Array](#allprops) + 2. [All Properties of a Field](#allfield) + 3. [Relational - Equality](#equality) + 4. [Relational - Less Than](#lessthan) + 5. [Relational - Greater Than or Equal](#greaterthan) + 6. [Logical AND](#logicaland) + 7. [Logical OR](#logicalor) + 8. [Regex - Contains Exact](#regex_exact) + 9. [Regex - Contains, Case Insensitive](#regex_contains) + 10. [Regex - Begins With](#regex_begins) ## Business Value Statement + The ability to query within a JSON object unlocks further value to the underlying data. Redis supports JSONPath array filtering natively. + ## Data Set + ```JSON { "city": "Boston", @@ -48,7 +54,9 @@ The ability to query within a JSON object unlocks further value to the underlyin ] } ``` + ## Data Loading + ```c# JsonCommands json = db.JSON(); json.Set("warehouse:1", "$", new { @@ -79,13 +87,19 @@ json.Set("warehouse:1", "$", new { } }); ``` + ## Array Filtering Examples + ### Syntax + [JSON.GET](https://redis.io/commands/json.get/) ### All Properties of Array + Fetch all properties of an array. + #### Command + ```c# Console.WriteLine(json.Get(key: "warehouse:1", path: "$.inventory[*]", @@ -93,7 +107,9 @@ Console.WriteLine(json.Get(key: "warehouse:1", newLine: "\n" )); ``` + #### Result + ```json [ { @@ -131,8 +147,11 @@ Console.WriteLine(json.Get(key: "warehouse:1", ``` ### All Properties of a Field + Fetch all values of a field within an array. + #### Command + ```c# Console.WriteLine(json.Get(key: "warehouse:1", path: "$.inventory[*].price", @@ -140,7 +159,9 @@ Console.WriteLine(json.Get(key: "warehouse:1", newLine: "\n" )); ``` + #### Result + ```json [ 34.95, @@ -150,8 +171,11 @@ Console.WriteLine(json.Get(key: "warehouse:1", ``` ### Relational - Equality + Fetch all items within an array where a text field matches a given value. + #### Command + ```c# Console.WriteLine(json.Get(key: "warehouse:1", path: "$.inventory[?(@.description==\"Turtle Check Men Navy Blue Shirt\")]", @@ -159,7 +183,9 @@ Console.WriteLine(json.Get(key: "warehouse:1", newLine: "\n" )); ``` + #### Result + ```json [ { @@ -176,8 +202,11 @@ Console.WriteLine(json.Get(key: "warehouse:1", ``` ### Relational - Less Than + Fetch all items within an array where a numeric field is less than a given value. + #### Command + ```c# Console.WriteLine(json.Get(key: "warehouse:1", path: "$.inventory[?(@.price<100)]", @@ -185,7 +214,9 @@ Console.WriteLine(json.Get(key: "warehouse:1", newLine: "\n" )); ``` + #### Result + ```json [ { @@ -211,8 +242,11 @@ Console.WriteLine(json.Get(key: "warehouse:1", ``` ### Relational - Greater Than or Equal + Fetch all items within an array where a numeric field is greater than or equal to a given value. + #### Command + ```c# Console.WriteLine(json.Get(key: "warehouse:1", path: "$.inventory[?(@.id>=20000)]", @@ -220,7 +254,9 @@ Console.WriteLine(json.Get(key: "warehouse:1", newLine: "\n" )); ``` + #### Result + ```json [ { @@ -248,8 +284,11 @@ Console.WriteLine(json.Get(key: "warehouse:1", ``` ### Logical AND + Fetch all items within an array that meet two relational operations. + #### Command + ```c# Console.WriteLine(json.Get(key: "warehouse:1", path: "$.inventory[?(@.gender==\"Men\"&&@.price>20)]", @@ -257,7 +296,9 @@ Console.WriteLine(json.Get(key: "warehouse:1", newLine: "\n" )); ``` + #### Result + ```json [ { @@ -274,8 +315,11 @@ Console.WriteLine(json.Get(key: "warehouse:1", ``` ### Logical OR + Fetch all items within an array that meet at least one relational operation. In this case, return only the ids of those items. + #### Command + ```c# Console.WriteLine(json.Get(key: "warehouse:1", path: "$.inventory[?(@.price<100||@.gender==\"Women\")].id", @@ -283,7 +327,9 @@ Console.WriteLine(json.Get(key: "warehouse:1", newLine: "\n" )); ``` + #### Result + ```json [ 15970, @@ -293,8 +339,11 @@ Console.WriteLine(json.Get(key: "warehouse:1", ``` ### Regex - Contains Exact + Fetch all items within an array that match a given regex pattern. + #### Command + ```c# Console.WriteLine(json.Get(key: "warehouse:1", path: "$.inventory[?(@.description =~ \"Blue\")]", @@ -302,7 +351,9 @@ Console.WriteLine(json.Get(key: "warehouse:1", newLine: "\n" )); ``` + #### Result + ```json [ { @@ -328,8 +379,11 @@ Console.WriteLine(json.Get(key: "warehouse:1", ``` ### Regex - Contains, Case Insensitive + Fetch all items within an array where a field contains a term, case insensitive. + #### Command + ```c# Console.WriteLine(json.Get(key: "warehouse:1", path: "$.inventory[?(@.description =~ \"(?i)watch\")]", @@ -337,7 +391,9 @@ Console.WriteLine(json.Get(key: "warehouse:1", newLine: "\n" )); ``` + #### Result + ```json [ { @@ -356,8 +412,11 @@ Console.WriteLine(json.Get(key: "warehouse:1", ``` ### Regex - Begins With + Fetch all items within an array where a field begins with a given expression. + #### Command + ```c# Console.WriteLine(json.Get(key: "warehouse:1", path: "$.inventory[?(@.description =~ \"^T\")]", @@ -365,7 +424,9 @@ Console.WriteLine(json.Get(key: "warehouse:1", newLine: "\n" )); ``` + #### Result + ```json [ { diff --git a/Examples/AdvancedQueryOperations.md b/Examples/AdvancedQueryOperations.md index 4573e60c..74cad845 100644 --- a/Examples/AdvancedQueryOperations.md +++ b/Examples/AdvancedQueryOperations.md @@ -1,33 +1,38 @@ # Advanced Querying Aggregation and other more complex RediSearch queries + ## Contents -1. [Business Value Statement](#value) -2. [Modules Needed](#modules) -3. [Vector Similarity Search](#vss) - 1. [Data Load](#vss_dataload) - 2. [Index Creation](#vss_index) - 3. [Search](#vss_search) - 4. [Hybrid Query Search](#vss_hybrid_query_search) -4. [Advanced Search Queries](#adv_search) - 1. [Data Set](#advs_dataset) - 2. [Data Load](#advs_dataload) - 3. [Index Creation](#advs_index) - 4. [Search w/JSON Filtering - Example 1](#advs_ex1) - 5. [Search w/JSON Filtering - Example 2](#advs_ex2) -5. [Aggregation](#aggr) - 1. [Data Set](#aggr_dataset) - 2. [Data Load](#aggr_dataload) - 3. [Index Creation](#aggr_index) - 4. [Aggregation - Count](#aggr_count) - 5. [Aggregation - Sum](#aggr_sum) + +1. [Business Value Statement](#value) +2. [Modules Needed](#modules) +3. [Vector Similarity Search](#vss) + 1. [Data Load](#vss_dataload) + 2. [Index Creation](#vss_index) + 3. [Search](#vss_search) + 4. [Hybrid Query Search](#vss_hybrid_query_search) +4. [Advanced Search Queries](#adv_search) + 1. [Data Set](#advs_dataset) + 2. [Data Load](#advs_dataload) + 3. [Index Creation](#advs_index) + 4. [Search w/JSON Filtering - Example 1](#advs_ex1) + 5. [Search w/JSON Filtering - Example 2](#advs_ex2) +5. [Aggregation](#aggr) + 1. [Data Set](#aggr_dataset) + 2. [Data Load](#aggr_dataload) + 3. [Index Creation](#aggr_index) + 4. [Aggregation - Count](#aggr_count) + 5. [Aggregation - Sum](#aggr_sum) ## Business Value Statement + Redis provides the following additional advanced search capabilities to derive further value of Redis-held data: + * Vector Similarity Search - Store and search by ML-generated encodings of text and images * Search + JSON Filtering - Combine the power of search with JSONPath filtering of search results * Aggregation - Create processing pipelines of search results to extract analytic insights. ## Modules Needed + ```c# using StackExchange.Redis; using NRedisStack; @@ -36,11 +41,15 @@ using NRedisStack.Search; using NRedisStack.Search.Literals.Enums; using NRedisStack.Search.Aggregation; ``` + ## Vector Similarity Search (VSS) + ### Syntax + [VSS](https://redis.io/docs/stack/search/reference/vectors/) ### Data Load + ```c# db.HashSet("vec:1", new HashEntry[] { @@ -63,8 +72,11 @@ db.HashSet("vec:4", new HashEntry[] new("tag", "A") }); ``` + ### Index Creation + #### Command + ```c# SearchCommands ft = db.FT(); try {ft.DropIndex("vss_idx");} catch {}; @@ -80,13 +92,17 @@ Console.WriteLine(ft.Create("vss_idx", new FTCreateParams().On(IndexDataType.HAS } ))); ``` + #### Result + ```bash True ``` ### Search + #### Command + ```c# float[] vec = new[] { 2f, 3f, 3f, 3f}; var res = ft.Search("vss_idx", @@ -102,14 +118,18 @@ foreach (var doc in res.Documents) { } } ``` + #### Result + ```bash id: vec:2, score: 2 id: vec:3, score: 2 ``` ### Hybrid query Search + #### Search only documents with tag A + ```c# float[] vec = new[] { 2f, 3f, 3f, 3f}; var res = ft.Search("vss_idx", @@ -125,15 +145,21 @@ foreach (var doc in res.Documents) { } } ``` + #### Result + ```bash id: vec:2, score: 3 id: vec:4, score: 7 ``` + vec:3 is not returned because it has tag B ## Advanced Search Queries + + ### Data Set + ```json { "city": "Boston", @@ -192,6 +218,7 @@ vec:3 is not returned because it has tag B ``` ### Data Load + ```c# JsonCommands json = db.JSON(); json.Set("warehouse:1", "$", new { @@ -251,7 +278,9 @@ json.Set("warehouse:2", "$", new { ``` ### Index Creation + #### Command + ```c# SearchCommands ft = db.FT(); try {ft.DropIndex("wh_idx");} catch {}; @@ -260,14 +289,19 @@ Console.WriteLine(ft.Create("wh_idx", new FTCreateParams() .Prefix("warehouse:"), new Schema().AddTextField(new FieldName("$.city", "city")))); ``` + #### Result + ```bash True ``` ### Search w/JSON Filtering - Example 1 + Find all inventory ids from all the Boston warehouse that have a price > $50. + #### Command + ```c# foreach (var doc in ft.Search("wh_idx", new Query("@city:Boston") @@ -278,14 +312,19 @@ foreach (var doc in ft.Search("wh_idx", Console.WriteLine(doc); } ``` + #### Result + ```json [59263] ``` ### Search w/JSON Filtering - Example 2 + Find all inventory items in Dallas that are for Women or Girls + #### Command + ```c# foreach (var doc in ft.Search("wh_idx", new Query("@city:(Dallas)") @@ -296,7 +335,9 @@ foreach (var doc in ft.Search("wh_idx", Console.WriteLine(doc); } ``` + #### Result + ```json [{"id":51919,"gender":"Women","season":["Summer"],"description":"Nyk Black Horado Handbag","price":52.49},{"id":37561,"gender":"Girls","season":["Spring","Summer"],"description":"Madagascar3 Infant Pink Snapsuit Romper","price":23.95}] ``` @@ -353,7 +394,9 @@ json.Set("book:4", "$", new { ``` ### Index Creation + #### Command + ```c# Console.WriteLine(ft.Create("book_idx", new FTCreateParams() .On(IndexDataType.JSON) @@ -362,14 +405,19 @@ Console.WriteLine(ft.Create("book_idx", new FTCreateParams() .AddNumericField(new FieldName("$.year", "year")) .AddNumericField(new FieldName("$.price", "price")))); ``` + #### Result + ```bash True ``` ### Aggregation - Count + Find the total number of books per year + #### Command + ```c# var request = new AggregationRequest("*").GroupBy("@year", Reducers.Count().As("count")); var result = ft.Aggregate("book_idx", request); @@ -379,7 +427,9 @@ for (var i=0; i + Sum of inventory dollar value by year #### Command + ```c# request = new AggregationRequest("*").GroupBy("@year", Reducers.Sum("@price").As("sum")); result = ft.Aggregate("book_idx", request); @@ -398,9 +450,11 @@ for (var i=0; i + Document stores are a NoSQL database type that provide flexible schemas and access patterns familiar to developers. Redis natively provides document store functionality with its JSON data type. Hence, Redis complements existing document store databases such as MongoDB or provides standalone JSON document storage. ## Create + ### Syntax + [JSON.SET](https://redis.io/commands/json.set/) ### Key-value pair + Insert a simple KVP as a JSON object. + #### Command + ```c# JsonCommands json = db.JSON(); Console.WriteLine(json.Set("ex1:1", "$", "\"val\"")); ``` + #### Result + ```bash True ``` - ### Single string property + Insert a single-property JSON object. + #### Command + ```c# Console.WriteLine(json.Set("ex1:2", "$", new {field1 = "val1" })); ``` + #### Result + ```bash True ``` ### Multiple Properties + Insert a JSON object with multiple properties. + #### Command + ```c# Console.WriteLine(json.Set("ex1:3", "$", new { field1 = "val1", field2 = "val2" })); ``` + #### Result + ```bash True ``` ### Multiple Properties + Data Types + Insert a JSON object with multiple properties of different data types. + #### Command + ```c# Console.WriteLine(json.Set("ex1:4", "$", new { field1 = "val1", @@ -83,27 +106,37 @@ Console.WriteLine(json.Set("ex1:4", "$", new { field4 = (string?) null })); ``` + #### Result + ```bash True ``` ### JSON Arrays + Insert a JSON object that contains an array. + #### Command + ```c# Console.WriteLine(json.Set("ex1:5", "$", new { arr1 = new [] {"val1", "val2", "val3"} })); ``` + #### Result + ```bash True ``` ### JSON Objects + Insert a JSON object that contains a nested object. + #### Command + ```c# Console.WriteLine(json.Set("ex1:6", "$", new { obj1 = new { @@ -112,14 +145,19 @@ Console.WriteLine(json.Set("ex1:6", "$", new { } })); ``` + #### Result + ```bash True ``` ### Mix + Insert a JSON object with a mixture of property data types. + #### Command + ```c# Console.WriteLine(json.Set("ex1:7", "$", new { str1 = "val1", @@ -131,18 +169,25 @@ Console.WriteLine(json.Set("ex1:7", "$", new { } })); ``` + #### Result + ```bash True ``` ## Read + ### Syntax + [JSON.GET](https://redis.io/commands/json.get/) ### Key Fetch + Set and Fetch a simple JSON KVP. + #### Command + ```c# json.Set("ex2:1", "$", "\"val\""); Console.WriteLine(json.Get(key: "ex2:1", @@ -151,7 +196,9 @@ Console.WriteLine(json.Get(key: "ex2:1", newLine: "\n" )); ``` + #### Result + ```bash [ "val" @@ -159,8 +206,11 @@ Console.WriteLine(json.Get(key: "ex2:1", ``` ### Single Property Fetch + Set and Fetch a single property from a JSON object. + #### Command + ```c# json.Set("ex2:2", "$", new { field1 = "val1" @@ -171,7 +221,9 @@ Console.WriteLine(json.Get(key: "ex2:2", newLine: "\n" )); ``` + #### Result + ```bash [ "val1" @@ -179,8 +231,11 @@ Console.WriteLine(json.Get(key: "ex2:2", ``` ### Multi-Property Fetch + Fetch multiple properties. + #### Command + ```c# json.Set("ex2:3", "$", new { field1 = "val1", @@ -192,7 +247,9 @@ Console.WriteLine(json.Get(key: "ex2:3", newLine: "\n" )); ``` + #### Result + ```bash { "$.field1":[ @@ -205,8 +262,11 @@ Console.WriteLine(json.Get(key: "ex2:3", ``` ### Nested Property Fetch + Fetch a property nested in another JSON object. + #### Command + ```c# json.Set("ex2:4", "$", new { obj1 = new { @@ -220,7 +280,9 @@ Console.WriteLine(json.Get(key: "ex2:4", newLine: "\n" )); ``` + #### Result + ```bash [ 2 @@ -228,8 +290,11 @@ Console.WriteLine(json.Get(key: "ex2:4", ``` ### Array Fetch + Fetch properties within an array and utilize array subscripting. + #### Command + ```c# json.Set("ex2:5", "$",new { str1 = "val1", @@ -261,7 +326,9 @@ Console.WriteLine(json.Get(key: "ex2:5", newLine: "\n" )); ``` + #### Results + ```bash [ [ @@ -284,12 +351,17 @@ Console.WriteLine(json.Get(key: "ex2:5", ``` ## Update + ### Syntax + [JSON.SET](https://redis.io/commands/json.set/) ### Entire Object + Update an entire JSON object. + #### Command + ```c# json.Set("ex3:1", "$", new {field1 = "val1"}); json.Set("ex3:1", "$", new {foo = "bar"}); @@ -298,7 +370,9 @@ Console.WriteLine(json.Get(key: "ex3:1", newLine: "\n" )); ``` + #### Result + ```bash { "foo":"bar" @@ -306,8 +380,11 @@ Console.WriteLine(json.Get(key: "ex3:1", ``` ### Single Property + Update a single property within an object. + #### Command + ```c# json.Set("ex3:2", "$", new { field1 = "val1", @@ -319,7 +396,9 @@ Console.WriteLine(json.Get(key: "ex3:2", newLine: "\n" )); ``` + #### Result + ```bash { "field1":"foo", @@ -328,8 +407,11 @@ Console.WriteLine(json.Get(key: "ex3:2", ``` ### Nested Property + Update a property in an embedded JSON object. + #### Command + ```c# json.Set("ex3:3", "$", new { obj1 = new { @@ -343,7 +425,9 @@ Console.WriteLine(json.Get(key: "ex3:3", newLine: "\n" )); ``` + #### Result + ```bash { "obj1":{ @@ -354,8 +438,11 @@ Console.WriteLine(json.Get(key: "ex3:3", ``` ### Array Item + Update an item in an array via index. + #### Command + ```c# json.Set("ex3:4", "$", new { arr1 = new[] {"val1", "val2", "val3"} @@ -366,7 +453,9 @@ Console.WriteLine(json.Get(key: "ex3:4", newLine: "\n" )); ``` + #### Result + ```bash { "arr1":[ @@ -378,12 +467,17 @@ Console.WriteLine(json.Get(key: "ex3:4", ``` ## Delete + ### Syntax + [JSON.DEL](https://redis.io/commands/json.del/) ### Entire object + Delete entire object/key. + #### Command + ```c# json.Set("ex4:1", "$", new {field1 = "val1"}); json.Del("ex4:1"); @@ -392,14 +486,19 @@ Console.WriteLine(json.Get(key: "ex4:1", newLine: "\n" )); ``` + #### Result + ```bash ``` ### Single Property + Delete a single property from an object. + #### Command + ```c# json.Set("ex4:2", "$", new { field1 = "val1", @@ -411,7 +510,9 @@ Console.WriteLine(json.Get(key: "ex4:2", newLine: "\n" )); ``` + #### Result + ```bash { "field2":"val2" @@ -419,8 +520,11 @@ Console.WriteLine(json.Get(key: "ex4:2", ``` ### Nested property + Delete a property from an embedded object. + #### Command + ```c# json.Set("ex4:3", "$", new { obj1 = new { @@ -434,7 +538,9 @@ Console.WriteLine(json.Get(key: "ex4:3", newLine: "\n" )); ``` + #### Result + ```bash { "obj1":{ @@ -444,8 +550,11 @@ Console.WriteLine(json.Get(key: "ex4:3", ``` ### Array item + Delete a single item from an array. + #### Command + ```c# json.Set("ex4:4", "$", new { arr1 = new[] {"val1", "val2", "val3"} @@ -456,7 +565,9 @@ Console.WriteLine(json.Get(key: "ex4:4", newLine: "\n" )); ``` + #### Result + ```bash { "arr1":[ @@ -464,4 +575,4 @@ Console.WriteLine(json.Get(key: "ex4:4", "val3" ] } -``` \ No newline at end of file +``` diff --git a/Examples/BasicQueryOperations.md b/Examples/BasicQueryOperations.md index 11e11ac6..fb18f982 100644 --- a/Examples/BasicQueryOperations.md +++ b/Examples/BasicQueryOperations.md @@ -1,28 +1,34 @@ # Basic Query Operations + Examples of simple query operations with RediSearch + ## Contents -1. [Business Value Statement](#value) -2. [Modules Needed](#modules) -3. [Data Set](#dataset) -4. [Data Loading](#loading) -5. [Index Creation](#index_creation) -6. [Search Examples](#search_examples) - 1. [Retrieve All](#retrieve_all) - 2. [Single Term Text](#single_term) - 3. [Exact Phrase Text](#exact_phrase) - 4. [Numeric Range](#numeric_range) - 5. [Tag Array](#tag_array) - 6. [Logical AND](#logical_and) - 7. [Logical OR](#logical_or) - 8. [Negation](#negation) - 9. [Prefix](#prefix) - 10. [Suffix](#suffix) - 11. [Fuzzy](#fuzzy) - 12. [Geo](#geo) + +1. [Business Value Statement](#value) +2. [Modules Needed](#modules) +3. [Data Set](#dataset) +4. [Data Loading](#loading) +5. [Index Creation](#index_creation) +6. [Search Examples](#search_examples) + 1. [Retrieve All](#retrieve_all) + 2. [Single Term Text](#single_term) + 3. [Exact Phrase Text](#exact_phrase) + 4. [Numeric Range](#numeric_range) + 5. [Tag Array](#tag_array) + 6. [Logical AND](#logical_and) + 7. [Logical OR](#logical_or) + 8. [Negation](#negation) + 9. [Prefix](#prefix) + 10. [Suffix](#suffix) + 11. [Fuzzy](#fuzzy) + 12. [Geo](#geo) ## Business Value Statement + Search is an essential function to derive the value of data. Redis provides inherent, high-speed search capabilities for JSON and Hash Set data. + ## Modules Needed + ```c# using StackExchange.Redis; using NRedisStack; @@ -32,6 +38,7 @@ using NRedisStack.Search.Literals.Enums; ``` ## Data Set + ```JSON [ { @@ -63,7 +70,9 @@ using NRedisStack.Search.Literals.Enums; } ] ``` + ## Data Loading + ```c# JsonCommands json = db.JSON(); json.Set("product:15970", "$", new { @@ -94,11 +103,15 @@ json.Set("product:46885", "$", new { coords = "-104.991531, 39.742043" }); ``` + ## Index Creation + ### Syntax + [FT.CREATE](https://redis.io/commands/ft.create/) #### Command + ```c# SearchCommands ft = db.FT(); try {ft.DropIndex("idx1");} catch {}; @@ -114,19 +127,26 @@ ft.Create("idx1", new FTCreateParams().On(IndexDataType.JSON) ``` ## Search Examples + ### Syntax + [FT.SEARCH](https://redis.io/commands/ft.search/) ### Retrieve All + Find all documents for a given index. + #### Command + ```c# foreach (var doc in ft.Search("idx1", new Query("*")).ToJson()) { Console.WriteLine(doc); } ``` + #### Result + ```json {"id":15970,"gender":"Men","season":["Fall","Winter"],"description":"Turtle Check Men Navy Blue Shirt","price":34.95,"city":"Boston","coords":"-71.057083, 42.361145"} {"id":46885,"gender":"Boys","season":["Fall"],"description":"Ben 10 Boys Navy Blue Slippers","price":45.99,"city":"Denver","coords":"-104.991531, 39.742043"} @@ -134,8 +154,11 @@ foreach (var doc in ft.Search("idx1", new Query("*")).ToJson()) ``` ### Single Term Text + Find all documents with a given word in a text field. + #### Command + ```c# foreach (var doc in ft.Search("idx1", new Query("@description:Slippers")) .ToJson()) @@ -143,14 +166,19 @@ foreach (var doc in ft.Search("idx1", new Query("@description:Slippers")) Console.WriteLine(doc); } ``` + #### Result + ```json {"id":46885,"gender":"Boys","season":["Fall"],"description":"Ben 10 Boys Navy Blue Slippers","price":45.99,"city":"Denver","coords":"-104.991531, 39.742043"} ``` ### Exact Phrase Text + Find all documents with a given phrase in a text field. + #### Command + ```c# foreach (var doc in ft.Search("idx1", new Query("@description:(\"Blue Shirt\")")) .ToJson()) @@ -158,14 +186,19 @@ foreach (var doc in ft.Search("idx1", new Query("@description:(\"Blue Shirt\")") Console.WriteLine(doc); } ``` + #### Result + ```json {"id":15970,"gender":"Men","season":["Fall","Winter"],"description":"Turtle Check Men Navy Blue Shirt","price":34.95,"city":"Boston","coords":"-71.057083, 42.361145"} ``` ### Numeric Range + Find all documents with a numeric field in a given range. + #### Command + ```c# foreach (var doc in ft.Search("idx1", new Query("@price:[40,130]")) .ToJson()) @@ -173,15 +206,20 @@ foreach (var doc in ft.Search("idx1", new Query("@price:[40,130]")) Console.WriteLine(doc); } ``` + #### Result + ```json {"id":46885,"gender":"Boys","season":["Fall"],"description":"Ben 10 Boys Navy Blue Slippers","price":45.99,"city":"Denver","coords":"-104.991531, 39.742043"} {"id":59263,"gender":"Women","season":["Fall","Winter","Spring","Summer"],"description":"Titan Women Silver Watch","price":129.99,"city":"Dallas","coords":"-96.808891, 32.779167"} ``` ### Tag Array + Find all documents that contain a given value in an array field (tag). + #### Command + ```c# foreach (var doc in ft.Search("idx1", new Query("@season:{Spring}")) .ToJson()) @@ -189,14 +227,19 @@ foreach (var doc in ft.Search("idx1", new Query("@season:{Spring}")) Console.WriteLine(doc); } ``` + #### Result + ```json {"id":59263,"gender":"Women","season":["Fall","Winter","Spring","Summer"],"description":"Titan Women Silver Watch","price":129.99,"city":"Dallas","coords":"-96.808891, 32.779167"} ``` ### Logical AND + Find all documents contain both a numeric field in a range and a word in a text field. + #### Command + ```c# foreach (var doc in ft.Search("idx1", new Query("@price:[40, 100] @description:Blue")) .ToJson()) @@ -204,14 +247,19 @@ foreach (var doc in ft.Search("idx1", new Query("@price:[40, 100] @description:B Console.WriteLine(doc); } ``` + #### Result + ```json {"id":46885,"gender":"Boys","season":["Fall"],"description":"Ben 10 Boys Navy Blue Slippers","price":45.99,"city":"Denver","coords":"-104.991531, 39.742043"} ``` ### Logical OR + Find all documents that either match tag value or text value. + #### Command + ```c# foreach (var doc in ft.Search("idx1", new Query("(@gender:{Women})|(@city:Boston)")) .ToJson()) @@ -219,15 +267,20 @@ foreach (var doc in ft.Search("idx1", new Query("(@gender:{Women})|(@city:Boston Console.WriteLine(doc); } ``` + #### Result + ```json {"id":15970,"gender":"Men","season":["Fall","Winter"],"description":"Turtle Check Men Navy Blue Shirt","price":34.95,"city":"Boston","coords":"-71.057083, 42.361145"} {"id":59263,"gender":"Women","season":["Fall","Winter","Spring","Summer"],"description":"Titan Women Silver Watch","price":129.99,"city":"Dallas","coords":"-96.808891, 32.779167"} ``` ### Negation + Find all documents that do not contain a given word in a text field. + #### Command + ```c# foreach (var doc in ft.Search("idx1", new Query("-(@description:Shirt)")) .ToJson()) @@ -235,15 +288,20 @@ foreach (var doc in ft.Search("idx1", new Query("-(@description:Shirt)")) Console.WriteLine(doc); } ``` + #### Result + ```json {"id":46885,"gender":"Boys","season":["Fall"],"description":"Ben 10 Boys Navy Blue Slippers","price":45.99,"city":"Denver","coords":"-104.991531, 39.742043"} {"id":59263,"gender":"Women","season":["Fall","Winter","Spring","Summer"],"description":"Titan Women Silver Watch","price":129.99,"city":"Dallas","coords":"-96.808891, 32.779167"} ``` ### Prefix + Find all documents that have a word that begins with a given prefix value. + #### Command + ```c# foreach (var doc in ft.Search("idx1", new Query("@description:Nav*")) .ToJson()) @@ -251,15 +309,20 @@ foreach (var doc in ft.Search("idx1", new Query("@description:Nav*")) Console.WriteLine(doc); } ``` + #### Result + ```json {"id":15970,"gender":"Men","season":["Fall","Winter"],"description":"Turtle Check Men Navy Blue Shirt","price":34.95,"city":"Boston","coords":"-71.057083, 42.361145"} {"id":46885,"gender":"Boys","season":["Fall"],"description":"Ben 10 Boys Navy Blue Slippers","price":45.99,"city":"Denver","coords":"-104.991531, 39.742043"} ``` ### Suffix + Find all documents that contain a word that ends with a given suffix value. + #### Command + ```c# foreach (var doc in ft.Search("idx1", new Query("@description:*Watch")) .ToJson()) @@ -267,14 +330,19 @@ foreach (var doc in ft.Search("idx1", new Query("@description:*Watch")) Console.WriteLine(doc); } ``` + #### Result + ```json {"id":59263,"gender":"Women","season":["Fall","Winter","Spring","Summer"],"description":"Titan Women Silver Watch","price":129.99,"city":"Dallas","coords":"-96.808891, 32.779167"} ``` ### Fuzzy + Find all documents that contain a word that is within 1 Levenshtein distance of a given word. + #### Command + ```c# foreach (var doc in ft.Search("idx1", new Query("@description:%wavy%")) .ToJson()) @@ -282,16 +350,21 @@ foreach (var doc in ft.Search("idx1", new Query("@description:%wavy%")) Console.WriteLine(doc); } ``` + #### Result + ```json {"id":15970,"gender":"Men","season":["Fall","Winter"],"description":"Turtle Check Men Navy Blue Shirt","price":34.95,"city":"Boston","coords":"-71.057083, 42.361145"} {"id":46885,"gender":"Boys","season":["Fall"],"description":"Ben 10 Boys Navy Blue Slippers","price":45.99,"city":"Denver","coords":"-104.991531, 39.742043"} ``` ### Geo + Find all documents that have geographic coordinates within a given range of a given coordinate. Colorado Springs coords (long, lat) = -104.800644, 38.846127 + #### Command + ```c# foreach (var doc in ft.Search("idx1", new Query("@coords:[-104.800644 38.846127 100 mi]")) .ToJson()) @@ -299,7 +372,9 @@ foreach (var doc in ft.Search("idx1", new Query("@coords:[-104.800644 38.846127 Console.WriteLine(doc); } ``` + #### Result + ```json {"id":46885,"gender":"Boys","season":["Fall"],"description":"Ben 10 Boys Navy Blue Slippers","price":45.99,"city":"Denver","coords":"-104.991531, 39.742043"} -``` \ No newline at end of file +``` diff --git a/Examples/ConvertSearchResultToJson.md b/Examples/ConvertSearchResultToJson.md index 2d060e39..cfb58f85 100644 --- a/Examples/ConvertSearchResultToJson.md +++ b/Examples/ConvertSearchResultToJson.md @@ -1,31 +1,42 @@ # Converting Search Result to JSON -## This example shows how to convert Redis search results to JSON format using NRedisStack. + +## This example shows how to convert Redis search results to JSON format using NRedisStack Connect to the Redis server: + ```csharp var redis = ConnectionMultiplexer.Connect("localhost"); ``` + Get a reference to the database and for search and json commands: + ```csharp var db = redis.GetDatabase(); var ft = db.FT(); var json = db.JSON(); ``` + Create a search index with a JSON field: + ```csharp ft.Create("test", new FTCreateParams().On(IndexDataType.JSON).Prefix("doc:"), new Schema().AddTagField(new FieldName("$.name", "name"))); ``` + Insert 10 JSON documents into the index: + ```csharp for (int i = 0; i < 10; i++) { json.Set("doc:" + i, "$", "{\"name\":\"foo\"}"); } ``` + Execute a search query and convert the results to JSON: + ```csharp var res = ft.Search("test", new Query("@name:{foo}")); var docs = res.ToJson(); ``` -Now the `docs` variable contains a JSON list (IEnumerable) of the search results. \ No newline at end of file + +Now the `docs` variable contains a JSON list (IEnumerable) of the search results. diff --git a/Examples/HsetAndSearch.md b/Examples/HsetAndSearch.md index dec2f05c..54b35318 100644 --- a/Examples/HsetAndSearch.md +++ b/Examples/HsetAndSearch.md @@ -1,16 +1,22 @@ # HSET and Search + ## An example of mixing Redis open source command (HSET) with Redis Stack Redis commands (FT.CREATE & FT.SEARCH) Connect to the Redis server: + ```csharp var redis = ConnectionMultiplexer.Connect("localhost"); ``` + Get a reference to the database and for search commands: + ```csharp var db = redis.GetDatabase(); var ft = db.FT(); ``` + Use HSET to add a field-value pair to a hash: + ```csharp db.HashSet("profesor:5555", new HashEntry[] { new("first", "Albert"), new("last", "Blue"), new("age", "55") }); db.HashSet("student:1111", new HashEntry[] { new("first", "Joe"), new("last", "Dod"), new("age", "18") }); @@ -22,39 +28,53 @@ db.HashSet("teacher:6666", new HashEntry[] { new("first", "Pat"), new("last", "R ``` Create the schema indexing the text fields ```first``` and ```last```, and ```age``` as a numeric field: + ```csharp var schema = new Schema().AddTextField("first").AddTextField("last").AddNumericField("age"); ``` + Filter the index to only include hashes with an age greater than 16, and prefix of 'student:' or 'pupil:' + ```csharp var parameters = FTCreateParams.CreateParams().Filter("@age>16").Prefix("student:", "pupil:"); ``` + Create the index: + ```csharp ft.Create("example_index", parameters, schema); ``` -## Search Examples: + +## Search Examples Search all hashes in the index: + ```csharp var noFilters = ft.Search("example_index", new Query()); ``` + _noFilters_ now contains: _student:1111_, _student:5555_, _pupil:4444_, _student:3333_.

Search for hashes with a first name starting with Jo + ```csharp var startWithJo = ft.Search("example_index", new Query("@first:Jo*")); ``` + _startWithJo_ now contains: _student:1111_ (Joe), _student:5555_ (Joen).

Search for hashes with first name of Pat + ```csharp var namedPat = ft.Search("example_index", new Query("@first:Pat")); ``` + _namedPat_ now contains _pupil:4444_ (Pat). _teacher:6666_ (Pat) is not included because it does not have a prefix of 'student:' or 'pupil:'

Search for hashes with last name of Rod + ```csharp var lastNameRod = ft.Search("example_index", new Query("@last:Rod")); ``` + _lastNameRod_ is empty because there are no hashes with a last name of Rod that match the index definition. diff --git a/Examples/PipelineExample.md b/Examples/PipelineExample.md index 8b0e6ba9..66107426 100644 --- a/Examples/PipelineExample.md +++ b/Examples/PipelineExample.md @@ -1,48 +1,58 @@ # Pipeline + ## An example of pipelines Redis Stack Redis commands (JSON.SET & JSON.CLEAR & JSON.GET) Connect to the Redis server and Setup new Pipeline + ```csharp IDatabase db = redisFixture.Redis.GetDatabase(); var pipeline = new Pipeline(db); ``` - Add JSON data to pipeline + ```csharp pipeline.Json.SetAsync("person", "$", new { name = "John", age = 30, city = "New York", nicknames = new[] { "John", "Johny", "Jo" } }); ``` Increase age by 2 + ```csharp pipeline.Json.NumIncrbyAsync("person", "$.age", 2); ``` Remove the ```nicknames``` field from the JSON object + ```csharp pipeline.Json.ClearAsync("person", "$.nicknames"); ``` Delete the nicknames + ```csharp pipeline.Json.DelAsync("person", "$.nicknames"); ``` Retrieve the JSON response + ```csharp var getResponse = pipeline.Json.GetAsync("person"); ``` Execute pipeline + ```csharp pipeline.Execute(); ``` Access the result of the JSON response + ```csharp var result = getResponse.Result; ``` + now result is: + ```json { "name": "John", diff --git a/Examples/PipelineWithAsync.md b/Examples/PipelineWithAsync.md index 19e27d90..7cac09a1 100644 --- a/Examples/PipelineWithAsync.md +++ b/Examples/PipelineWithAsync.md @@ -1,17 +1,21 @@ # Pipeline With Async + ## An example of pipelines Redis Stack Redis commands (JSON.SET & JSON.CLEAR & JSON.GET) Connect to the Redis server + ```csharp var redis = ConnectionMultiplexer.Connect("localhost"); ``` Get a reference to the database + ```csharp var db = redis.GetDatabase(); ``` Setup pipeline connection + ```csharp var pipeline = new Pipeline(db); ``` @@ -62,11 +66,13 @@ pipeline.Execute(); ``` Get a reference to the database and for TimeSeries commands: + ```csharp var ts = db.TS(); ``` Get only the location label for each last sample, use SELECTED_LABELS. + ```csharp var respons = await ts.MGetAsync(new List { "temp=JLM" }, selectedLabels: new List { "location" }); ``` diff --git a/src/NRedisStack/CuckooFilter/ICuckooCommands.cs b/src/NRedisStack/CuckooFilter/ICuckooCommands.cs index 18852203..4483f1c0 100644 --- a/src/NRedisStack/CuckooFilter/ICuckooCommands.cs +++ b/src/NRedisStack/CuckooFilter/ICuckooCommands.cs @@ -124,6 +124,6 @@ bool Reserve(RedisKey key, long capacity, /// Iterator value; either 0 or the iterator from a previous invocation of this command. /// Tuple of iterator and data. /// - Tuple ScanDump(RedisKey key, long iterator); + Tuple ScanDump(RedisKey key, long iterator); } } \ No newline at end of file diff --git a/src/NRedisStack/CuckooFilter/ICuckooCommandsAsync.cs b/src/NRedisStack/CuckooFilter/ICuckooCommandsAsync.cs index acf67b69..6717c02a 100644 --- a/src/NRedisStack/CuckooFilter/ICuckooCommandsAsync.cs +++ b/src/NRedisStack/CuckooFilter/ICuckooCommandsAsync.cs @@ -124,6 +124,6 @@ Task ReserveAsync(RedisKey key, long capacity, /// Iterator value; either 0 or the iterator from a previous invocation of this command. /// Tuple of iterator and data. /// - Task> ScanDumpAsync(RedisKey key, long iterator); + Task> ScanDumpAsync(RedisKey key, long iterator); } } \ No newline at end of file diff --git a/src/NRedisStack/CuckooFilter/Literals/CommandArgs.cs b/src/NRedisStack/CuckooFilter/Literals/CommandArgs.cs index 3b6b6c16..b480700b 100644 --- a/src/NRedisStack/CuckooFilter/Literals/CommandArgs.cs +++ b/src/NRedisStack/CuckooFilter/Literals/CommandArgs.cs @@ -2,11 +2,11 @@ namespace NRedisStack.CuckooFilter.Literals { internal class CuckooArgs { - public const string CAPACITY = "CAPACITY"; - public const string EXPANSION = "EXPANSION"; - public const string NOCREATE = "NOCREATE"; - public const string ITEMS = "ITEMS"; - public const string BUCKETSIZE = "BUCKETSIZE"; - public const string MAXITERATIONS = "MAXITERATIONS"; + public const string CAPACITY = "CAPACITY"; + public const string EXPANSION = "EXPANSION"; + public const string NOCREATE = "NOCREATE"; + public const string ITEMS = "ITEMS"; + public const string BUCKETSIZE = "BUCKETSIZE"; + public const string MAXITERATIONS = "MAXITERATIONS"; } } \ No newline at end of file diff --git a/src/NRedisStack/Gears/GearsCommandBuilder.cs b/src/NRedisStack/Gears/GearsCommandBuilder.cs index 31d8c73c..5af745ba 100644 --- a/src/NRedisStack/Gears/GearsCommandBuilder.cs +++ b/src/NRedisStack/Gears/GearsCommandBuilder.cs @@ -58,7 +58,7 @@ public static SerializedCommand TFunctionList(bool withCode = false, int verbose public static SerializedCommand TFCall(string libraryName, string functionName, string[]? keys = null, string[]? args = null, bool async = false) { string command = async ? RG.TFCALLASYNC : RG.TFCALL; - var commandArgs = new List() {$"{libraryName}.{functionName}"}; + var commandArgs = new List() { $"{libraryName}.{functionName}" }; if (keys != null) { diff --git a/src/NRedisStack/Gears/GearsCommands.cs b/src/NRedisStack/Gears/GearsCommands.cs index 2eb885f0..64b7eeb8 100644 --- a/src/NRedisStack/Gears/GearsCommands.cs +++ b/src/NRedisStack/Gears/GearsCommands.cs @@ -58,7 +58,7 @@ public static Dictionary[] TFunctionList(this IDatabase db, /// public static RedisResult TFCall_(this IDatabase db, string libraryName, string functionName, string[]? keys = null, string[]? args = null) { - return db.Execute(GearsCommandBuilder.TFCall(libraryName, functionName, keys, args, async : false)); + return db.Execute(GearsCommandBuilder.TFCall(libraryName, functionName, keys, args, async: false)); } /// @@ -72,7 +72,7 @@ public static RedisResult TFCall_(this IDatabase db, string libraryName, string /// public static RedisResult TFCallAsync_(this IDatabase db, string libraryName, string functionName, string[]? keys = null, string[]? args = null) { - return db.Execute(GearsCommandBuilder.TFCall(libraryName, functionName, keys, args, async : true)); + return db.Execute(GearsCommandBuilder.TFCall(libraryName, functionName, keys, args, async: true)); } } } diff --git a/src/NRedisStack/Gears/GearsCommandsAsync.cs b/src/NRedisStack/Gears/GearsCommandsAsync.cs index 4842a3ed..09b1fafa 100644 --- a/src/NRedisStack/Gears/GearsCommandsAsync.cs +++ b/src/NRedisStack/Gears/GearsCommandsAsync.cs @@ -57,7 +57,7 @@ public static async Task[]> TFunctionListAsync(t /// public async static Task TFCall_Async(this IDatabase db, string libraryName, string functionName, string[]? keys = null, string[]? args = null) { - return await db.ExecuteAsync(GearsCommandBuilder.TFCall(libraryName, functionName, keys, args, async : false)); + return await db.ExecuteAsync(GearsCommandBuilder.TFCall(libraryName, functionName, keys, args, async: false)); } /// @@ -71,7 +71,7 @@ public async static Task TFCall_Async(this IDatabase db, string lib /// public async static Task TFCallAsync_Async(this IDatabase db, string libraryName, string functionName, string[]? keys = null, string[]? args = null) { - return await db.ExecuteAsync(GearsCommandBuilder.TFCall(libraryName, functionName, keys, args, async : true)); + return await db.ExecuteAsync(GearsCommandBuilder.TFCall(libraryName, functionName, keys, args, async: true)); } } } diff --git a/src/NRedisStack/Graph/DataTypes/Edge.cs b/src/NRedisStack/Graph/DataTypes/Edge.cs index 24e7df5b..cf005f5c 100644 --- a/src/NRedisStack/Graph/DataTypes/Edge.cs +++ b/src/NRedisStack/Graph/DataTypes/Edge.cs @@ -12,7 +12,7 @@ public class Edge : GraphEntity /// The relationship type. /// /// - public string RelationshipType { get; set; } + public string? RelationshipType { get; set; } /// /// The ID of the source node. @@ -66,7 +66,7 @@ public override int GetHashCode() int hash = 17; hash = hash * 31 + base.GetHashCode(); - hash = hash * 31 + RelationshipType.GetHashCode(); + hash = hash * 31 + RelationshipType!.GetHashCode(); hash = hash * 31 + Source.GetHashCode(); hash = hash * 31 + Destination.GetHashCode(); diff --git a/src/NRedisStack/Graph/DataTypes/Node.cs b/src/NRedisStack/Graph/DataTypes/Node.cs index dae07ef1..960ac145 100644 --- a/src/NRedisStack/Graph/DataTypes/Node.cs +++ b/src/NRedisStack/Graph/DataTypes/Node.cs @@ -53,7 +53,7 @@ public override int GetHashCode() { int hash = 17; - foreach(var label in Labels) + foreach (var label in Labels) { hash = hash * 31 + label.GetHashCode(); } diff --git a/src/NRedisStack/Graph/DataTypes/Path.cs b/src/NRedisStack/Graph/DataTypes/Path.cs index 02af0c8e..62a3552c 100644 --- a/src/NRedisStack/Graph/DataTypes/Path.cs +++ b/src/NRedisStack/Graph/DataTypes/Path.cs @@ -11,8 +11,8 @@ namespace NRedisStack.Graph.DataTypes /// public class Path { - public ReadOnlyCollection Nodes { get;} - public ReadOnlyCollection Edges { get;} + public ReadOnlyCollection Nodes { get; } + public ReadOnlyCollection Edges { get; } public Path(IList nodes, IList edges) { diff --git a/src/NRedisStack/Graph/GraphCache.cs b/src/NRedisStack/Graph/GraphCache.cs index fc9a2c39..327d019e 100644 --- a/src/NRedisStack/Graph/GraphCache.cs +++ b/src/NRedisStack/Graph/GraphCache.cs @@ -6,6 +6,7 @@ internal sealed class GraphCache public GraphCacheList PropertyNames { get; set; } public GraphCacheList RelationshipTypes { get; set; } + [Obsolete] public GraphCache(string graphName, GraphCommands redisGraph) { Labels = new GraphCacheList(graphName, "db.labels", redisGraph); @@ -13,6 +14,7 @@ public GraphCache(string graphName, GraphCommands redisGraph) RelationshipTypes = new GraphCacheList(graphName, "db.relationshipTypes", redisGraph); } + [Obsolete] public GraphCache(string graphName, GraphCommandsAsync redisGraph) { Labels = new GraphCacheList(graphName, "db.labels", redisGraph); @@ -20,11 +22,14 @@ public GraphCache(string graphName, GraphCommandsAsync redisGraph) RelationshipTypes = new GraphCacheList(graphName, "db.relationshipTypes", redisGraph); } - public string GetLabel(int index) => Labels.GetCachedData(index); + [Obsolete] + public string GetLabel(int index) => Labels.GetCachedData(index)!; - public string GetRelationshipType(int index) => RelationshipTypes.GetCachedData(index); + [Obsolete] + public string GetRelationshipType(int index) => RelationshipTypes.GetCachedData(index)!; - public string GetPropertyName(int index) => PropertyNames.GetCachedData(index); + [Obsolete] + public string GetPropertyName(int index) => PropertyNames.GetCachedData(index)!; } } \ No newline at end of file diff --git a/src/NRedisStack/Graph/GraphCacheList.cs b/src/NRedisStack/Graph/GraphCacheList.cs index 551e8476..acf62a51 100644 --- a/src/NRedisStack/Graph/GraphCacheList.cs +++ b/src/NRedisStack/Graph/GraphCacheList.cs @@ -6,7 +6,7 @@ internal sealed class GraphCacheList private readonly string _procedure; private string[] _data = Array.Empty(); - + [Obsolete] private readonly GraphCommandsAsync _redisGraph; private readonly object _locker = new object(); @@ -17,6 +17,7 @@ internal sealed class GraphCacheList /// The name of the graph to cache information for. /// The saved procedure to call to populate cache. Must be a `read` procedure. /// The graph used for the calling the . + [Obsolete] internal GraphCacheList(string graphName, string procedure, GraphCommands redisGraph) { _graphName = graphName; @@ -31,6 +32,7 @@ internal GraphCacheList(string graphName, string procedure, GraphCommands redisG /// The name of the graph to cache information for. /// The saved procedure to call to populate cache. Must be a `read` procedure. /// The graph used for the calling the . + [Obsolete] internal GraphCacheList(string graphName, string procedure, GraphCommandsAsync redisGraphAsync) { _graphName = graphName; @@ -40,7 +42,8 @@ internal GraphCacheList(string graphName, string procedure, GraphCommandsAsync r } // TODO: Change this to use Lazy? - internal string GetCachedData(int index) + [Obsolete] + internal string? GetCachedData(int index) { if (index >= _data.Length) { @@ -56,6 +59,7 @@ internal string GetCachedData(int index) return _data.ElementAtOrDefault(index); } + [Obsolete] private string[] GetProcedureInfo() { var resultSet = CallProcedure(); @@ -64,6 +68,7 @@ private string[] GetProcedureInfo() .ToArray(); } + [Obsolete] private ResultSet CallProcedure() { return _redisGraph is GraphCommands graphSync diff --git a/src/NRedisStack/Graph/GraphCommands.cs b/src/NRedisStack/Graph/GraphCommands.cs index 16894221..34740a2d 100644 --- a/src/NRedisStack/Graph/GraphCommands.cs +++ b/src/NRedisStack/Graph/GraphCommands.cs @@ -6,6 +6,7 @@ namespace NRedisStack { + [Obsolete] public class GraphCommands : GraphCommandsAsync, IGraphCommands { readonly IDatabase _db; diff --git a/src/NRedisStack/Graph/GraphCommandsAsync.cs b/src/NRedisStack/Graph/GraphCommandsAsync.cs index 8f06f338..f095392e 100644 --- a/src/NRedisStack/Graph/GraphCommandsAsync.cs +++ b/src/NRedisStack/Graph/GraphCommandsAsync.cs @@ -7,6 +7,7 @@ namespace NRedisStack { + [Obsolete] public class GraphCommandsAsync : IGraphCommandsAsync { readonly IDatabaseAsync _db; diff --git a/src/NRedisStack/Graph/Header.cs b/src/NRedisStack/Graph/Header.cs index 26f0bf5c..506a84d1 100644 --- a/src/NRedisStack/Graph/Header.cs +++ b/src/NRedisStack/Graph/Header.cs @@ -29,18 +29,21 @@ public enum ResultSetColumnTypes /// public List SchemaNames { get; } + [Obsolete] internal Header(RedisResult result) { SchemaTypes = new List(); SchemaNames = new List(); - foreach (RedisResult[] tuple in (RedisResult[])result) + foreach (RedisResult[]? tuple in (RedisResult[])result!) { - SchemaTypes.Add((ResultSetColumnTypes)(int)tuple[0]); - SchemaNames.Add((string)tuple[1]); + SchemaTypes.Add((ResultSetColumnTypes)(int)tuple![0]); + SchemaNames.Add((string)tuple[1]!); } } +#pragma warning disable CS0809 + [Obsolete] public override bool Equals(object? obj) { if (obj == null) return this == null; @@ -61,6 +64,7 @@ public override bool Equals(object? obj) && Object.Equals(SchemaNames, header.SchemaNames); } + [Obsolete] public override int GetHashCode() { unchecked @@ -72,9 +76,9 @@ public override int GetHashCode() } } - - + [Obsolete] public override string ToString() => $"Header{{schemaTypes=[{string.Join(", ", SchemaTypes)}], schemaNames=[{string.Join(", ", SchemaNames)}]}}"; } +#pragma warning restore CS0809 } \ No newline at end of file diff --git a/src/NRedisStack/Graph/Record.cs b/src/NRedisStack/Graph/Record.cs index be2346ec..e6bcebf7 100644 --- a/src/NRedisStack/Graph/Record.cs +++ b/src/NRedisStack/Graph/Record.cs @@ -37,14 +37,14 @@ internal Record(List header, List values) /// /// The index of the value that you want to get. /// The string value at the index that you specified. - public string GetString(int index) => Values[index].ToString(); + public string GetString(int index) => Values[index].ToString()!; /// /// Gets the string representation of a value by key. /// /// The key of the value that you want to get. /// The string value at the key that you specified. - public string GetString(string key) => Values[Header.IndexOf(key)].ToString(); + public string GetString(string key) => Values[Header.IndexOf(key)].ToString()!; /// /// Does the key exist in the record? diff --git a/src/NRedisStack/Graph/RedisGraphUtilities.cs b/src/NRedisStack/Graph/RedisGraphUtilities.cs index b0eae675..9678d460 100644 --- a/src/NRedisStack/Graph/RedisGraphUtilities.cs +++ b/src/NRedisStack/Graph/RedisGraphUtilities.cs @@ -60,7 +60,7 @@ public static string ValueToString(object value) foreach (var val in valueList) { - objectValueList.Add((object) val); + objectValueList.Add((object)val); } return ArrayToString(objectValueList.ToArray()); @@ -76,7 +76,7 @@ public static string ValueToString(object value) return ConvertibleToString(floatValue); } - return value.ToString(); + return value.ToString()!; } private static string ConvertibleToString(IConvertible floatValue) @@ -90,7 +90,7 @@ private static string ArrayToString(object[] array) { if (x.GetType().IsArray) { - return ArrayToString((object[]) x); + return ArrayToString((object[])x); } else { diff --git a/src/NRedisStack/Graph/ResultSet.cs b/src/NRedisStack/Graph/ResultSet.cs index 334f0a8a..9ef95af8 100644 --- a/src/NRedisStack/Graph/ResultSet.cs +++ b/src/NRedisStack/Graph/ResultSet.cs @@ -25,18 +25,19 @@ internal enum ResultSetScalarType VALUE_POINT } - private readonly RedisResult[] _rawResults; - private readonly GraphCache _graphCache; + private readonly RedisResult[]? _rawResults; + private readonly GraphCache? _graphCache; public Statistics Statistics { get; } - public Header Header { get; } + public Header? Header { get; } public int Count { get; } + [Obsolete] internal ResultSet(RedisResult result, GraphCache graphCache) { if (result.Type == ResultType.MultiBulk) { - var resultArray = (RedisResult[])result; + var resultArray = (RedisResult[])result!; ScanForErrors(resultArray); @@ -47,7 +48,7 @@ internal ResultSet(RedisResult result, GraphCache graphCache) Header = new Header(resultArray[0]); Statistics = ParseStatistics(resultArray[2]); - _rawResults = (RedisResult[])resultArray[1]; + _rawResults = (RedisResult[])resultArray[1]!; Count = _rawResults.Length; } @@ -61,7 +62,7 @@ internal ResultSet(RedisResult result, GraphCache graphCache) { if (result.Type == ResultType.Error) { - throw new RedisServerException(result.ToString()); + throw new RedisServerException(result.ToString()!); } Statistics = ParseStatistics(result); @@ -73,14 +74,17 @@ internal ResultSet(RedisResult result, GraphCache graphCache) /// Get the enumerator for this result set. /// /// + [Obsolete] public IEnumerator GetEnumerator() => RecordIterator().GetEnumerator(); /// /// Get the enumerator for this result set. /// /// + [Obsolete] IEnumerator IEnumerable.GetEnumerator() => RecordIterator().GetEnumerator(); + [Obsolete] private IEnumerable RecordIterator() { if (_rawResults == default) @@ -89,14 +93,14 @@ private IEnumerable RecordIterator() } else { - foreach (RedisResult[] row in _rawResults) + foreach (RedisResult[]? row in _rawResults) { - var parsedRow = new List(row.Length); + var parsedRow = new List(row!.Length); for (int i = 0; i < row.Length; i++) { - var obj = (RedisResult[])row[i]; - var objType = Header.SchemaTypes[i]; + var obj = (RedisResult[])row[i]!; + var objType = Header!.SchemaTypes[i]; switch (objType) { @@ -115,49 +119,52 @@ private IEnumerable RecordIterator() } } - yield return new Record(Header.SchemaNames, parsedRow); + yield return new Record(Header!.SchemaNames, parsedRow!); } yield break; } } + [Obsolete] private Node DeserializeNode(RedisResult[] rawNodeData) { var node = new Node(); DeserializeGraphEntityId(node, rawNodeData[0]); - var labelIndices = (int[])rawNodeData[1]; + var labelIndices = (int[])rawNodeData[1]!; foreach (var labelIndex in labelIndices) { - var label = _graphCache.GetLabel(labelIndex); + var label = _graphCache!.GetLabel(labelIndex); node.Labels.Add(label); } - DeserializeGraphEntityProperties(node, (RedisResult[])rawNodeData[2]); + DeserializeGraphEntityProperties(node, (RedisResult[])rawNodeData[2]!); return node; } + [Obsolete] private Edge DeserializeEdge(RedisResult[] rawEdgeData) { var edge = new Edge(); DeserializeGraphEntityId(edge, rawEdgeData[0]); - edge.RelationshipType = _graphCache.GetRelationshipType((int)rawEdgeData[1]); + edge.RelationshipType = _graphCache!.GetRelationshipType((int)rawEdgeData[1]); edge.Source = (int)rawEdgeData[2]; edge.Destination = (int)rawEdgeData[3]; - DeserializeGraphEntityProperties(edge, (RedisResult[])rawEdgeData[4]); + DeserializeGraphEntityProperties(edge, (RedisResult[])rawEdgeData[4]!); return edge; } - private object DeserializeScalar(RedisResult[] rawScalarData) + [Obsolete] + private object? DeserializeScalar(RedisResult[] rawScalarData) { var type = GetValueTypeFromObject(rawScalarData[0]); @@ -166,25 +173,25 @@ private object DeserializeScalar(RedisResult[] rawScalarData) case ResultSetScalarType.VALUE_NULL: return null; case ResultSetScalarType.VALUE_BOOLEAN: - return bool.Parse((string)rawScalarData[1]); + return bool.Parse((string)rawScalarData[1]!); case ResultSetScalarType.VALUE_DOUBLE: return (double)rawScalarData[1]; case ResultSetScalarType.VALUE_INT64: return (long)rawScalarData[1]; case ResultSetScalarType.VALUE_STRING: - return (string)rawScalarData[1]; + return (string)rawScalarData[1]!; case ResultSetScalarType.VALUE_ARRAY: - return DeserializeArray((RedisResult[])rawScalarData[1]); + return DeserializeArray((RedisResult[])rawScalarData[1]!); case ResultSetScalarType.VALUE_NODE: - return DeserializeNode((RedisResult[])rawScalarData[1]); + return DeserializeNode((RedisResult[])rawScalarData[1]!); case ResultSetScalarType.VALUE_EDGE: - return DeserializeEdge((RedisResult[])rawScalarData[1]); + return DeserializeEdge((RedisResult[])rawScalarData[1]!); case ResultSetScalarType.VALUE_PATH: - return DeserializePath((RedisResult[])rawScalarData[1]); + return DeserializePath((RedisResult[])rawScalarData[1]!); case ResultSetScalarType.VALUE_MAP: return DeserializeDictionary(rawScalarData[1]); case ResultSetScalarType.VALUE_POINT: - return DeserializePoint((RedisResult[])rawScalarData[1]); + return DeserializePoint((RedisResult[])rawScalarData[1]!); case ResultSetScalarType.VALUE_UNKNOWN: default: return (object)rawScalarData[1]; @@ -194,42 +201,45 @@ private object DeserializeScalar(RedisResult[] rawScalarData) private static void DeserializeGraphEntityId(GraphEntity graphEntity, RedisResult rawEntityId) => graphEntity.Id = (int)rawEntityId; + [Obsolete] private void DeserializeGraphEntityProperties(GraphEntity graphEntity, RedisResult[] rawProperties) { - foreach (RedisResult[] rawProperty in rawProperties) + foreach (RedisResult[]? rawProperty in rawProperties) { - var Key = _graphCache.GetPropertyName((int)rawProperty[0]); + var Key = _graphCache!.GetPropertyName((int)rawProperty![0]); var Value = DeserializeScalar(rawProperty.Skip(1).ToArray()); - graphEntity.PropertyMap.Add(Key, Value); + graphEntity.PropertyMap.Add(Key, Value!); } } + [Obsolete] private object[] DeserializeArray(RedisResult[] serializedArray) { var result = new object[serializedArray.Length]; for (var i = 0; i < serializedArray.Length; i++) { - result[i] = DeserializeScalar((RedisResult[])serializedArray[i]); + result[i] = DeserializeScalar((RedisResult[])serializedArray[i]!)!; } return result; } + [Obsolete] private DataTypes.Path DeserializePath(RedisResult[] rawPath) { - var deserializedNodes = (object[])DeserializeScalar((RedisResult[])rawPath[0]); + var deserializedNodes = (object[])DeserializeScalar((RedisResult[])rawPath[0]!)!; var nodes = Array.ConvertAll(deserializedNodes, n => (Node)n); - var deserializedEdges = (object[])DeserializeScalar((RedisResult[])rawPath[1]); + var deserializedEdges = (object[])DeserializeScalar((RedisResult[])rawPath[1]!)!; var edges = Array.ConvertAll(deserializedEdges, p => (Edge)p); return new DataTypes.Path(nodes, edges); } - private object DeserializePoint(RedisResult[] rawPath) // Should return Point? + private object? DeserializePoint(RedisResult[] rawPath) // Should return Point? { if (null == rawPath) { @@ -245,17 +255,18 @@ private DataTypes.Path DeserializePath(RedisResult[] rawPath) } // @SuppressWarnings("unchecked") + [Obsolete] private Dictionary DeserializeDictionary(RedisResult rawPath) { - RedisResult[] keyTypeValueEntries = (RedisResult[])rawPath; + RedisResult[] keyTypeValueEntries = (RedisResult[])rawPath!; int size = keyTypeValueEntries.Length; Dictionary dict = new Dictionary(size / 2); // set the capacity to half of the list for (int i = 0; i < size; i += 2) { - string key = keyTypeValueEntries[i].ToString(); - object value = DeserializeScalar((RedisResult[])keyTypeValueEntries[i+1]); + string key = keyTypeValueEntries[i].ToString()!; + object value = DeserializeScalar((RedisResult[])keyTypeValueEntries[i + 1]!)!; dict.Add(key, value); } return dict; @@ -270,7 +281,7 @@ private static void ScanForErrors(RedisResult[] results) { if (result.Type == ResultType.Error) { - throw new RedisServerException(result.ToString()); + throw new RedisServerException(result.ToString()!); } } } @@ -281,7 +292,7 @@ private Statistics ParseStatistics(RedisResult result) if (result.Type == ResultType.MultiBulk) { - statistics = (RedisResult[])result; + statistics = (RedisResult[])result!; } else { @@ -291,7 +302,7 @@ private Statistics ParseStatistics(RedisResult result) return new Statistics( ((RedisResult[])statistics).Select(x => { - var s = ((string)x).Split(':'); + var s = ((string)x!).Split(':'); return new { diff --git a/src/NRedisStack/Graph/Statistics.cs b/src/NRedisStack/Graph/Statistics.cs index 0991998c..a67f8c9c 100644 --- a/src/NRedisStack/Graph/Statistics.cs +++ b/src/NRedisStack/Graph/Statistics.cs @@ -11,28 +11,28 @@ internal Statistics(Dictionary statistics) { _statistics = statistics; - NodesCreated = GetIntValue("Nodes created"); - NodesDeleted = GetIntValue("Nodes deleted"); - IndicesAdded = GetIntValue("Indices added"); - IndicesCreated = GetIntValue("Indices created"); - IndicesDeleted = GetIntValue("Indices deleted"); - LabelsAdded = GetIntValue("Labels added"); - RelationshipsDeleted = GetIntValue("Relationships deleted"); - RelationshipsCreated = GetIntValue("Relationships created"); - PropertiesSet = GetIntValue("Properties set"); - QueryInternalExecutionTime = GetStringValue("Query internal execution time"); - GraphRemovedInternalExecutionTime = GetStringValue("Graph removed, internal execution time"); - CachedExecution = (GetIntValue("Cached execution") == 1); + NodesCreated = GetIntValue("Nodes created"); + NodesDeleted = GetIntValue("Nodes deleted"); + IndicesAdded = GetIntValue("Indices added"); + IndicesCreated = GetIntValue("Indices created"); + IndicesDeleted = GetIntValue("Indices deleted"); + LabelsAdded = GetIntValue("Labels added"); + RelationshipsDeleted = GetIntValue("Relationships deleted"); + RelationshipsCreated = GetIntValue("Relationships created"); + PropertiesSet = GetIntValue("Properties set"); + QueryInternalExecutionTime = GetStringValue("Query internal execution time")!; + GraphRemovedInternalExecutionTime = GetStringValue("Graph removed, internal execution time")!; + CachedExecution = (GetIntValue("Cached execution") == 1); - } + } - /// - /// Retrieves the relevant statistic. - /// - /// The requested statistic label. - /// A string representation of the specific statistic or null - public string? GetStringValue(string label) => - _statistics.TryGetValue(label, out string? value) ? value : null; + /// + /// Retrieves the relevant statistic. + /// + /// The requested statistic label. + /// A string representation of the specific statistic or null + public string? GetStringValue(string label) => + _statistics.TryGetValue(label, out string? value) ? value : null; private int GetIntValue(string label) diff --git a/src/NRedisStack/Json/DataTypes/KeyValuePath.cs b/src/NRedisStack/Json/DataTypes/KeyValuePath.cs index 252b639e..a5801e7e 100644 --- a/src/NRedisStack/Json/DataTypes/KeyValuePath.cs +++ b/src/NRedisStack/Json/DataTypes/KeyValuePath.cs @@ -18,7 +18,7 @@ public string[] ToArray() { if (Value is string) { - return new string[] { Key, Path, Value.ToString() }; + return new string[] { Key, Path, Value.ToString()! }; } return new string[] { Key, Path, JsonSerializer.Serialize(Value) }; } diff --git a/src/NRedisStack/Json/JsonCommandBuilder.cs b/src/NRedisStack/Json/JsonCommandBuilder.cs index b5505100..c78845f0 100644 --- a/src/NRedisStack/Json/JsonCommandBuilder.cs +++ b/src/NRedisStack/Json/JsonCommandBuilder.cs @@ -16,7 +16,7 @@ public static SerializedCommand Resp(RedisKey key, string? path = null) return new SerializedCommand(JSON.RESP, key); } - return new SerializedCommand(JSON.RESP, key, path); + return new SerializedCommand(JSON.RESP, key, path!); } public static SerializedCommand Set(RedisKey key, RedisValue path, RedisValue json, When when = When.Always) @@ -34,8 +34,8 @@ public static SerializedCommand MSet(KeyPathValue[] KeyPathValueList) if (KeyPathValueList.Length < 1) throw new ArgumentOutOfRangeException(nameof(KeyPathValueList)); - var args = KeyPathValueList.SelectMany(x => x.ToArray()).ToArray(); - return new SerializedCommand(JSON.MSET, args); + var args = KeyPathValueList.SelectMany(x => x.ToArray()).ToArray(); + return new SerializedCommand(JSON.MSET, args); } public static SerializedCommand Merge(RedisKey key, RedisValue path, RedisValue json) diff --git a/src/NRedisStack/Json/JsonCommands.cs b/src/NRedisStack/Json/JsonCommands.cs index d1e588f7..582036fa 100644 --- a/src/NRedisStack/Json/JsonCommands.cs +++ b/src/NRedisStack/Json/JsonCommands.cs @@ -241,7 +241,7 @@ public RedisResult Get(RedisKey key, string[] paths, RedisValue? indent = null, public IEnumerable GetEnumerable(RedisKey key, string path = "$") { RedisResult res = _db.Execute(JsonCommandBuilder.Get(key, path)); - return JsonSerializer.Deserialize>(res.ToString()); + return JsonSerializer.Deserialize>(res.ToString()!)!; } /// @@ -254,7 +254,7 @@ public RedisResult[] MGet(RedisKey[] keys, string path) public double?[] NumIncrby(RedisKey key, string path, double value) { var res = _db.Execute(JsonCommandBuilder.NumIncrby(key, path, value)); - return JsonSerializer.Deserialize(res.ToString()); + return JsonSerializer.Deserialize(res.ToString()!)!; } /// diff --git a/src/NRedisStack/Json/JsonCommandsAsync.cs b/src/NRedisStack/Json/JsonCommandsAsync.cs index c42fcbd5..a4d12639 100644 --- a/src/NRedisStack/Json/JsonCommandsAsync.cs +++ b/src/NRedisStack/Json/JsonCommandsAsync.cs @@ -97,7 +97,7 @@ public async Task GetAsync(RedisKey key, string[] paths, RedisValue public async Task> GetEnumerableAsync(RedisKey key, string path = "$") { RedisResult res = await _db.ExecuteAsync(JsonCommandBuilder.Get(key, path)); - return JsonSerializer.Deserialize>(res.ToString()); + return JsonSerializer.Deserialize>(res.ToString()!)!; } public async Task MGetAsync(RedisKey[] keys, string path) @@ -108,7 +108,7 @@ public async Task MGetAsync(RedisKey[] keys, string path) public async Task NumIncrbyAsync(RedisKey key, string path, double value) { var res = await _db.ExecuteAsync(JsonCommandBuilder.NumIncrby(key, path, value)); - return JsonSerializer.Deserialize(res.ToString()); + return JsonSerializer.Deserialize(res.ToString()!)!; } public async Task>> ObjKeysAsync(RedisKey key, string? path = null) @@ -169,7 +169,7 @@ public async Task SetFromFileAsync(RedisKey key, RedisValue path, string f throw new FileNotFoundException($"File {filePath} not found."); } - string fileContent = File.ReadAllText(filePath); + string fileContent = File.ReadAllText(filePath); return await SetAsync(key, path, fileContent, when); } @@ -181,7 +181,7 @@ public async Task SetFromDirectoryAsync(RedisValue path, string filesPath, foreach (var filePath in files) { key = filePath.Substring(0, filePath.IndexOf(".")); - if(await SetFromFileAsync(key, path, filePath, when)) + if (await SetFromFileAsync(key, path, filePath, when)) { inserted++; } diff --git a/src/NRedisStack/ModulePrefixes.cs b/src/NRedisStack/ModulePrefixes.cs index e497f874..70dce707 100644 --- a/src/NRedisStack/ModulePrefixes.cs +++ b/src/NRedisStack/ModulePrefixes.cs @@ -10,6 +10,7 @@ public static class ModulePrefixes public static CmsCommands CMS(this IDatabase db) => new CmsCommands(db); + [Obsolete] public static GraphCommands GRAPH(this IDatabase db) => new GraphCommands(db); public static TopKCommands TOPK(this IDatabase db) => new TopKCommands(db); diff --git a/src/NRedisStack/Pipeline.cs b/src/NRedisStack/Pipeline.cs index 182a73c2..67f23ff8 100644 --- a/src/NRedisStack/Pipeline.cs +++ b/src/NRedisStack/Pipeline.cs @@ -17,6 +17,8 @@ public Pipeline(IDatabase db) public BloomCommandsAsync Bf => new BloomCommandsAsync(_batch); public CmsCommandsAsync Cms => new CmsCommandsAsync(_batch); public CuckooCommandsAsync Cf => new CuckooCommandsAsync(_batch); + + [Obsolete] public GraphCommandsAsync Graph => new GraphCommandsAsync(_batch); public JsonCommandsAsync Json => new JsonCommandsAsync(_batch); public SearchCommandsAsync Ft => new SearchCommandsAsync(_batch); diff --git a/src/NRedisStack/ResponseParser.cs b/src/NRedisStack/ResponseParser.cs index 2865531e..81f22eb3 100644 --- a/src/NRedisStack/ResponseParser.cs +++ b/src/NRedisStack/ResponseParser.cs @@ -80,31 +80,31 @@ public static long[] ToLongArray(this RedisResult result) public static TimeStamp ToTimeStamp(this RedisResult result) { - if (result.Type == ResultType.None) return null; + if (result.Type == ResultType.None) return null!; return new TimeStamp((long)result); } public static IReadOnlyList ToTimeStampArray(this RedisResult result) { - RedisResult[] redisResults = (RedisResult[])result; + RedisResult[] redisResults = (RedisResult[])result!; var list = new List(redisResults.Length); if (redisResults.Length == 0) return list; Array.ForEach(redisResults, timestamp => list.Add(ToTimeStamp(timestamp))); return list; } - public static TimeSeriesTuple? ToTimeSeriesTuple(this RedisResult result) + public static TimeSeriesTuple ToTimeSeriesTuple(this RedisResult result) { RedisResult[] redisResults = result.ToArray(); - if (redisResults.Length == 0) return null; + if (redisResults.Length == 0) return null!; return new TimeSeriesTuple(ToTimeStamp(redisResults[0]), (double)redisResults[1]); } - public static Tuple ToScanDumpTuple(this RedisResult result) + public static Tuple ToScanDumpTuple(this RedisResult result) { RedisResult[] redisResults = result.ToArray(); - if (redisResults == null || redisResults.Length == 0) return null; - return new Tuple((long)redisResults[0], (Byte[])redisResults[1]); + if (redisResults == null || redisResults.Length == 0) return null!; + return new Tuple((long)redisResults[0], (byte[])redisResults[1]!); } // TODO: check if this is needed: @@ -131,22 +131,22 @@ public static Tuple ToScanDumpTuple(this RedisResult result) public static IReadOnlyList ToTimeSeriesTupleArray(this RedisResult result) { - RedisResult[] redisResults = (RedisResult[])result; + RedisResult[] redisResults = (RedisResult[])result!; var list = new List(redisResults.Length); if (redisResults.Length == 0) return list; - Array.ForEach(redisResults, tuple => list.Add(ToTimeSeriesTuple(tuple))); + Array.ForEach(redisResults, tuple => list.Add(ToTimeSeriesTuple(tuple)!)); return list; } public static IReadOnlyList ToLabelArray(this RedisResult result) { - RedisResult[] redisResults = (RedisResult[])result; + RedisResult[] redisResults = (RedisResult[])result!; var list = new List(redisResults.Length); if (redisResults.Length == 0) return list; Array.ForEach(redisResults, labelResult => { - RedisResult[] labelTuple = (RedisResult[])labelResult; - list.Add(new TimeSeriesLabel((string)labelTuple[0], (string)labelTuple[1])); + var labelTuple = (RedisResult[])labelResult!; + list.Add(new TimeSeriesLabel(labelTuple[0].ToString()!, labelTuple[1].ToString()!)); }); return list; } @@ -166,29 +166,29 @@ public static IReadOnlyList ToLabelArray(this RedisResult resul public static IReadOnlyList<(string key, IReadOnlyList labels, TimeSeriesTuple value)> ParseMGetResponse(this RedisResult result) { - RedisResult[] redisResults = (RedisResult[])result; + var redisResults = (RedisResult[])result!; var list = new List<(string key, IReadOnlyList labels, TimeSeriesTuple values)>(redisResults.Length); if (redisResults.Length == 0) return list; Array.ForEach(redisResults, MRangeValue => { - RedisResult[] MRangeTuple = (RedisResult[])MRangeValue; - string key = (string)MRangeTuple[0]; + var MRangeTuple = (RedisResult[])MRangeValue!; + string key = MRangeTuple[0].ToString()!; IReadOnlyList labels = ToLabelArray(MRangeTuple[1]); - TimeSeriesTuple value = ToTimeSeriesTuple(MRangeTuple[2]); - list.Add((key, labels, value)); + TimeSeriesTuple? value = ToTimeSeriesTuple(MRangeTuple[2]); + list.Add((key!, labels!, value!)); }); return list; } public static IReadOnlyList<(string key, IReadOnlyList labels, IReadOnlyList values)> ParseMRangeResponse(this RedisResult result) { - RedisResult[] redisResults = (RedisResult[])result; + var redisResults = (RedisResult[])result!; var list = new List<(string key, IReadOnlyList labels, IReadOnlyList values)>(redisResults.Length); if (redisResults.Length == 0) return list; Array.ForEach(redisResults, MRangeValue => { - RedisResult[] MRangeTuple = (RedisResult[])MRangeValue; - string key = (string)MRangeTuple[0]; + var MRangeTuple = (RedisResult[])MRangeValue!; + string key = MRangeTuple[0].ToString()!; IReadOnlyList labels = ToLabelArray(MRangeTuple[1]); IReadOnlyList values = ToTimeSeriesTupleArray(MRangeTuple[2]); list.Add((key, labels, values)); @@ -198,16 +198,16 @@ public static IReadOnlyList ToLabelArray(this RedisResult resul public static TimeSeriesRule ToRule(this RedisResult result) { - RedisResult[] redisResults = (RedisResult[])result; - string destKey = (string)redisResults[0]; + var redisResults = (RedisResult[])result!; + string destKey = redisResults[0].ToString()!; long bucketTime = (long)redisResults[1]; - var aggregation = AggregationExtensions.AsAggregation((string)redisResults[2]); + var aggregation = AggregationExtensions.AsAggregation(redisResults[2].ToString()!); return new TimeSeriesRule(destKey, bucketTime, aggregation); } public static IReadOnlyList ToRuleArray(this RedisResult result) { - RedisResult[] redisResults = (RedisResult[])result; + var redisResults = (RedisResult[])result!; var list = new List(); if (redisResults.Length == 0) return list; Array.ForEach(redisResults, rule => list.Add(ToRule(rule))); @@ -216,7 +216,7 @@ public static IReadOnlyList ToRuleArray(this RedisResult result) public static TsDuplicatePolicy? ToPolicy(this RedisResult result) { - var policyStatus = (string)result; + var policyStatus = result.ToString(); if (String.IsNullOrEmpty(policyStatus) || policyStatus == "(nil)") { return null; @@ -419,6 +419,7 @@ public static IReadOnlyList ToRuleArray(this RedisResult result) mergedWeight, unmergedWeight, observations, totalCompressions, memoryUsage); } + [Obsolete] public static TimeSeriesInformation ToTimeSeriesInfo(this RedisResult result) { long totalSamples = -1, memoryUsage = -1, retentionTime = -1, chunkSize = -1, chunkCount = -1; @@ -428,10 +429,10 @@ public static TimeSeriesInformation ToTimeSeriesInfo(this RedisResult result) string? sourceKey = null, keySelfName = null; TsDuplicatePolicy? duplicatePolicy = null; IReadOnlyList? chunks = null; - RedisResult[] redisResults = (RedisResult[])result; + var redisResults = (RedisResult[])result!; for (int i = 0; i < redisResults.Length; ++i) { - string label = (string)redisResults[i++]; + string label = redisResults[i++].ToString()!; switch (label) { case "totalSamples": @@ -464,7 +465,7 @@ public static TimeSeriesInformation ToTimeSeriesInfo(this RedisResult result) labels = ToLabelArray(redisResults[i]); break; case "sourceKey": - sourceKey = (string)redisResults[i]; + sourceKey = redisResults[i].ToString(); break; case "rules": rules = ToRuleArray(redisResults[i]); @@ -506,19 +507,19 @@ public static TimeSeriesInformation ToTimeSeriesInfo(this RedisResult result) public static Dictionary ToConfigDictionary(this RedisResult value) { - var res = (RedisResult[])value; + var res = (RedisResult[])value!; var dict = new Dictionary(); foreach (var pair in res) { - var arr = (RedisResult[])pair; - dict.Add(arr[0].ToString(), arr[1].ToString()); + var arr = (RedisResult[])pair!; + dict.Add(arr[0].ToString()!, arr[1].ToString()!); } return dict; } public static IReadOnlyList ToTimeSeriesChunkArray(this RedisResult result) { - RedisResult[] redisResults = (RedisResult[])result; + var redisResults = (RedisResult[])result!; var list = new List(); if (redisResults.Length == 0) return list; Array.ForEach(redisResults, chunk => list.Add(ToTimeSeriesChunk(chunk))); @@ -529,10 +530,10 @@ public static TimeSeriesChunck ToTimeSeriesChunk(this RedisResult result) { long startTimestamp = -1, endTimestamp = -1, samples = -1, size = -1; string bytesPerSample = ""; - RedisResult[] redisResults = (RedisResult[])result; + var redisResults = (RedisResult[])result!; for (int i = 0; i < redisResults.Length; ++i) { - string label = (string)redisResults[i++]; + string label = redisResults[i++].ToString()!; switch (label) { case "startTimestamp": @@ -548,7 +549,7 @@ public static TimeSeriesChunck ToTimeSeriesChunk(this RedisResult result) size = (long)redisResults[i]; break; case "bytesPerSample": - bytesPerSample = redisResults[i].ToString(); + bytesPerSample = redisResults[i].ToString()!; break; } } @@ -564,7 +565,7 @@ public static List ToStringList(this RedisResult result) var list = new List(); if (redisResults.Length == 0) return list; - Array.ForEach(redisResults, str => list.Add((string)str)); + Array.ForEach(redisResults, str => list.Add(str.ToString()!)); return list; } @@ -580,7 +581,7 @@ public static List ToStringList(this RedisResult result) return new[] { (long?)result }; } - return ((RedisResult[])result!).Select(x=>(long?)x).ToArray(); + return ((RedisResult[])result!).Select(x => (long?)x).ToArray(); } public static IEnumerable> ToHashSets(this RedisResult result) @@ -626,7 +627,7 @@ public static Dictionary> ToFtSpellCheckResul string termValue = rawElements[1].ToString()!; - var list = (RedisResult[]) rawElements[2]!; + var list = (RedisResult[])rawElements[2]!; Dictionary entries = new Dictionary(list.Length); foreach (var entry in list) { @@ -653,7 +654,7 @@ public static List> ToStringDoubleTupleList(this RedisResu } return list; } - + public static Dictionary ToStringRedisResultDictionary(this RedisResult value) { var res = (RedisResult[])value!; @@ -661,7 +662,7 @@ public static Dictionary ToStringRedisResultDictionary(this foreach (var pair in res) { var arr = (RedisResult[])pair!; - dict.Add(arr[0].ToString(), arr[1]); + dict.Add(arr[0].ToString()!, arr[1]); } return dict; } diff --git a/src/NRedisStack/Search/AggregationRequest.cs b/src/NRedisStack/Search/AggregationRequest.cs index e5854f99..29eee63c 100644 --- a/src/NRedisStack/Search/AggregationRequest.cs +++ b/src/NRedisStack/Search/AggregationRequest.cs @@ -39,7 +39,7 @@ public class AggregationRequest // Params: private Dictionary nameValue = new Dictionary(); - public int? dialect {get; private set;} = null; + public int? dialect { get; private set; } = null; public AggregationRequest(string query, int? defaultDialect = null) { @@ -57,7 +57,7 @@ public AggregationRequest Verbatim(bool verbatim = true) private void Verbatim() { - if(verbatim == true) + if (verbatim == true) args.Add("VERBATIM"); } diff --git a/src/NRedisStack/Search/AggregationResult.cs b/src/NRedisStack/Search/AggregationResult.cs index 70c2dffb..b8e4d38e 100644 --- a/src/NRedisStack/Search/AggregationResult.cs +++ b/src/NRedisStack/Search/AggregationResult.cs @@ -11,7 +11,7 @@ public sealed class AggregationResult internal AggregationResult(RedisResult result, long cursorId = -1) { - var arr = (RedisResult[])result; + var arr = (RedisResult[])result!; // the first element is always the number of results TotalResults = (long)arr[0]; @@ -19,11 +19,11 @@ internal AggregationResult(RedisResult result, long cursorId = -1) _results = new Dictionary[arr.Length - 1]; for (int i = 1; i < arr.Length; i++) { - var raw = (RedisResult[])arr[i]; + var raw = (RedisResult[])arr[i]!; var cur = new Dictionary(); for (int j = 0; j < raw.Length;) { - var key = (string)raw[j++]; + var key = (string)raw[j++]!; var val = raw[j++]; if (val.Type == ResultType.MultiBulk) continue; // TODO: handle multi-bulk (maybe change to object?) @@ -36,7 +36,7 @@ internal AggregationResult(RedisResult result, long cursorId = -1) } public IReadOnlyList> GetResults() => _results; - public Dictionary this[int index] + public Dictionary? this[int index] => index >= _results.Length ? null : _results[index]; public Row GetRow(int index) diff --git a/src/NRedisStack/Search/DataTypes/InfoResult.cs b/src/NRedisStack/Search/DataTypes/InfoResult.cs index e0d21de6..f245b5d8 100644 --- a/src/NRedisStack/Search/DataTypes/InfoResult.cs +++ b/src/NRedisStack/Search/DataTypes/InfoResult.cs @@ -6,15 +6,15 @@ public class InfoResult { private readonly Dictionary _all = new Dictionary(); - public string IndexName => GetString("index_name"); - public Dictionary IndexOption => GetRedisResultDictionary("index_options"); + public string IndexName => GetString("index_name")!; + public Dictionary IndexOption => GetRedisResultDictionary("index_options")!; - public Dictionary[] Attributes => GetRedisResultDictionaryArray("attributes"); + public Dictionary[] Attributes => GetRedisResultDictionaryArray("attributes")!; public long NumDocs => GetLong("num_docs"); - public string MaxDocId => GetString("max_doc_id"); + public string MaxDocId => GetString("max_doc_id")!; public long NumTerms => GetLong("num_terms"); @@ -59,24 +59,24 @@ public class InfoResult public long NumberOfUses => GetLong("number_of_uses"); - public Dictionary GcStats => GetRedisResultDictionary("gc_stats"); + public Dictionary GcStats => GetRedisResultDictionary("gc_stats")!; - public Dictionary CursorStats => GetRedisResultDictionary("cursor_stats"); + public Dictionary CursorStats => GetRedisResultDictionary("cursor_stats")!; public InfoResult(RedisResult result) { - var results = (RedisResult[])result; + var results = (RedisResult[])result!; for (var i = 0; i < results.Length; i += 2) { - var key = (string)results[i]; + var key = (string)results[i]!; var value = results[i + 1]; _all.Add(key, value); } } - private string GetString(string key) => _all.TryGetValue(key, out var value) ? (string)value : default; + private string? GetString(string key) => _all.TryGetValue(key, out var value) ? (string)value! : default; private long GetLong(string key) => _all.TryGetValue(key, out var value) ? (long)value : default; @@ -84,7 +84,7 @@ private double GetDouble(string key) { if (_all.TryGetValue(key, out var value)) { - if ((string)value == "-nan") + if ((string)value! == "-nan") { return default; } @@ -99,16 +99,16 @@ private double GetDouble(string key) } } - private Dictionary GetRedisResultDictionary(string key) + private Dictionary? GetRedisResultDictionary(string key) { if (_all.TryGetValue(key, out var value)) { - var values = (RedisResult[])value; + var values = (RedisResult[])value!; var result = new Dictionary(); for (var ii = 0; ii < values.Length; ii += 2) { - result.Add((string)values[ii], values[ii + 1]); + result.Add((string)values[ii]!, values[ii + 1]); } return result; @@ -119,19 +119,19 @@ private Dictionary GetRedisResultDictionary(string key) } } - private Dictionary[] GetRedisResultDictionaryArray(string key) + private Dictionary[]? GetRedisResultDictionaryArray(string key) { if (_all.TryGetValue(key, out var value)) { - var values = (RedisResult[])value; + var values = (RedisResult[])value!; var result = new Dictionary[values.Length]; for (int i = 0; i < values.Length; i++) { - var fv = (RedisResult[])values[i]; + var fv = (RedisResult[])values[i]!; var dict = new Dictionary(); for (int j = 0; j < fv.Length; j += 2) { - dict.Add((string)fv[j], fv[j + 1]); + dict.Add((string)fv[j]!, fv[j + 1]); } result[i] = dict; } diff --git a/src/NRedisStack/Search/Document.cs b/src/NRedisStack/Search/Document.cs index 7c61b1c1..159071d4 100644 --- a/src/NRedisStack/Search/Document.cs +++ b/src/NRedisStack/Search/Document.cs @@ -8,16 +8,16 @@ namespace NRedisStack.Search public class Document { public string Id { get; } - public double Score { get; set;} - public byte[] Payload { get; } - public string[] ScoreExplained { get; private set; } // TODO: check if this is needed (Jedis does not have it) + public double Score { get; set; } + public byte[]? Payload { get; } + public string[]? ScoreExplained { get; private set; } // TODO: check if this is needed (Jedis does not have it) internal readonly Dictionary _properties; - public Document(string id, double score, byte[] payload) : this(id, null, score, payload) { } + public Document(string id, double score, byte[]? payload) : this(id, null, score, payload) { } public Document(string id) : this(id, null, 1.0, null) { } public Document(string id, Dictionary fields, double score = 1.0) : this(id, fields, score, null) { } - public Document(string id, Dictionary fields, double score, byte[] payload) + public Document(string id, Dictionary? fields, double score, byte[]? payload) { Id = id; _properties = fields ?? new Dictionary(); @@ -27,18 +27,20 @@ public Document(string id, Dictionary fields, double score, public IEnumerable> GetProperties() => _properties; - public static Document Load(string id, double score, byte[] payload, RedisValue[] fields) + public static Document Load(string id, double score, byte[]? payload, RedisValue[]? fields) { Document ret = new Document(id, score, payload); if (fields != null) { for (int i = 0; i < fields.Length; i += 2) { - string fieldName = (string)fields[i]; - if (fieldName == "$") { + string fieldName = (string)fields[i]!; + if (fieldName == "$") + { ret["json"] = fields[i + 1]; } - else { + else + { ret[fieldName] = fields[i + 1]; } } @@ -46,7 +48,7 @@ public static Document Load(string id, double score, byte[] payload, RedisValue[ return ret; } - public static Document Load(string id, double score, byte[] payload, RedisValue[] fields, string[] scoreExplained) + public static Document Load(string id, double score, byte[]? payload, RedisValue[]? fields, string[]? scoreExplained) { Document ret = Document.Load(id, score, payload, fields); if (scoreExplained != null) diff --git a/src/NRedisStack/Search/FTCreateParams.cs b/src/NRedisStack/Search/FTCreateParams.cs index b06cffce..9ae3e4f4 100644 --- a/src/NRedisStack/Search/FTCreateParams.cs +++ b/src/NRedisStack/Search/FTCreateParams.cs @@ -5,20 +5,20 @@ namespace NRedisStack.Search public class FTCreateParams { private IndexDataType dataType; - private List prefixes; - private string filter; - private string language; - private string languageField; + private List? prefixes; + private string? filter; + private string? language; + private string? languageField; private double score; - private string scoreField; - private string payloadField; + private string? scoreField; + private string? payloadField; private bool maxTextFields; private bool noOffsets; private long temporary; private bool noHL; private bool noFields; private bool noFreqs; - private List stopwords; + private List? stopwords; private bool skipInitialScan; public FTCreateParams() diff --git a/src/NRedisStack/Search/FTSpellCheckParams.cs b/src/NRedisStack/Search/FTSpellCheckParams.cs index 97242604..74d3af86 100644 --- a/src/NRedisStack/Search/FTSpellCheckParams.cs +++ b/src/NRedisStack/Search/FTSpellCheckParams.cs @@ -76,12 +76,12 @@ private void Dialect() private void Terms() { - foreach (var term in terms) - { - args.Add(SearchArgs.TERMS); - args.Add(term.Value); - args.Add(term.Key); - } + foreach (var term in terms) + { + args.Add(SearchArgs.TERMS); + args.Add(term.Value); + args.Add(term.Key); + } } private void Distance() diff --git a/src/NRedisStack/Search/FieldName.cs b/src/NRedisStack/Search/FieldName.cs index 2ce9f850..b07d23f4 100644 --- a/src/NRedisStack/Search/FieldName.cs +++ b/src/NRedisStack/Search/FieldName.cs @@ -3,11 +3,11 @@ namespace NRedisStack.Search public class FieldName { private readonly string fieldName; - private string alias; + private string? alias; public FieldName(string name) : this(name, null) { } - public FieldName(string name, string attribute) + public FieldName(string name, string? attribute) { this.fieldName = name; this.alias = attribute; diff --git a/src/NRedisStack/Search/Group.cs b/src/NRedisStack/Search/Group.cs index 04ffb321..a45e065f 100644 --- a/src/NRedisStack/Search/Group.cs +++ b/src/NRedisStack/Search/Group.cs @@ -36,7 +36,7 @@ internal void SerializeRedisArgs(List args) if (!string.IsNullOrEmpty(alias)) { args.Add("AS"); - args.Add(alias); + args.Add(alias!); } } _limit.SerializeRedisArgs(args); diff --git a/src/NRedisStack/Search/Limit.cs b/src/NRedisStack/Search/Limit.cs index 151cbeec..e3e9e917 100644 --- a/src/NRedisStack/Search/Limit.cs +++ b/src/NRedisStack/Search/Limit.cs @@ -11,14 +11,14 @@ public Limit(int offset, int count) _count = count; } -// public void addArgs(List args) { -// if (count == 0) { -// return; -// } -// args.add("LIMIT"); -// args.add(Integer.toString(offset)); -// args.add(Integer.toString(count)); -// } + // public void addArgs(List args) { + // if (count == 0) { + // return; + // } + // args.add("LIMIT"); + // args.add(Integer.toString(offset)); + // args.add(Integer.toString(count)); + // } internal void SerializeRedisArgs(List args) { diff --git a/src/NRedisStack/Search/Query.cs b/src/NRedisStack/Search/Query.cs index 4b2bad54..baa41598 100644 --- a/src/NRedisStack/Search/Query.cs +++ b/src/NRedisStack/Search/Query.cs @@ -153,29 +153,29 @@ public HighlightTags(string open, string close) /// /// Set the query language, for stemming purposes; see http://redisearch.io for documentation on languages and stemming /// - public string Language { get; set; } - - internal string[] _fields = null; - internal string[] _keys = null; - internal string[] _returnFields = null; - internal FieldName[] _returnFieldsNames = null; - internal string[] _highlightFields = null; - internal string[] _summarizeFields = null; - internal HighlightTags? _highlightTags = null; - internal string _summarizeSeparator = null; + public string? Language { get; set; } + + internal string[]? _fields; + internal string[]? _keys; + internal string[]? _returnFields; + internal FieldName[]? _returnFieldsNames; + internal string[]? _highlightFields; + internal string[]? _summarizeFields; + internal HighlightTags? _highlightTags; + internal string? _summarizeSeparator; internal int _summarizeNumFragments = -1, _summarizeFragmentLen = -1; /// /// Set the query payload to be evaluated by the scoring function /// - public string Payload { get; set; } // TODO: should this be a byte[]? + public string? Payload { get; set; } // TODO: should this be a byte[]? // TODO: Check if I need to add here WITHSORTKEYS /// /// Set the query parameter to sort by /// - public string SortBy { get; set; } + public string? SortBy { get; set; } /// /// Set the query parameter to sort by ASC by default @@ -188,11 +188,11 @@ public HighlightTags(string open, string close) /// /// Set the query scoring. see https://oss.redislabs.com/redisearch/Scoring.html for documentation /// - public string Scorer { get; set; } + public string? Scorer { get; set; } // public bool ExplainScore { get; set; } // TODO: Check if this is needed because Jedis doesn't have it private Dictionary _params = new Dictionary(); - public int? dialect { get; private set;} = null; + public int? dialect { get; private set; } = null; private int _slop = -1; private long _timeout = -1; private bool _inOrder = false; @@ -585,7 +585,7 @@ private Query HighlightFieldsImpl(HighlightTags? tags, string[] fields) return this; } - public Query SummarizeFields(int contextLen, int fragmentCount, string separator, params string[] fields) + public Query SummarizeFields(int contextLen, int fragmentCount, string? separator, params string[] fields) { if (fields == null || fields.Length > 0) { diff --git a/src/NRedisStack/Search/Reducer.cs b/src/NRedisStack/Search/Reducer.cs index 0a870024..a55fcd5a 100644 --- a/src/NRedisStack/Search/Reducer.cs +++ b/src/NRedisStack/Search/Reducer.cs @@ -10,10 +10,10 @@ public abstract class Reducer public abstract string Name { get; } public string? Alias { get; set; } - private readonly string _field; + private readonly string? _field; - protected Reducer(string field) + protected Reducer(string? field) { _field = field; Alias = null; diff --git a/src/NRedisStack/Search/Row.cs b/src/NRedisStack/Search/Row.cs index 12795ffc..0caac94e 100644 --- a/src/NRedisStack/Search/Row.cs +++ b/src/NRedisStack/Search/Row.cs @@ -14,7 +14,7 @@ internal Row(Dictionary fields) public bool ContainsKey(string key) => _fields.ContainsKey(key); public RedisValue this[string key] => _fields.TryGetValue(key, out var result) ? result : RedisValue.Null; - public string GetString(string key) => _fields.TryGetValue(key, out var result) ? (string)result : default; + public string? GetString(string key) => _fields.TryGetValue(key, out var result) ? result.ToString() : default; public long GetLong(string key) => _fields.TryGetValue(key, out var result) ? (long)result : default; public double GetDouble(string key) => _fields.TryGetValue(key, out var result) ? (double)result : default; } diff --git a/src/NRedisStack/Search/SearchCommandBuilder.cs b/src/NRedisStack/Search/SearchCommandBuilder.cs index 7da5b388..1d962a96 100644 --- a/src/NRedisStack/Search/SearchCommandBuilder.cs +++ b/src/NRedisStack/Search/SearchCommandBuilder.cs @@ -163,8 +163,8 @@ public static SerializedCommand ProfileSearch(string IndexName, Query q, bool li { var args = (limited) - ? new List(){IndexName, SearchArgs.SEARCH, SearchArgs.LIMITED, SearchArgs.QUERY} - : new List(){IndexName, SearchArgs.SEARCH, SearchArgs.QUERY}; + ? new List() { IndexName, SearchArgs.SEARCH, SearchArgs.LIMITED, SearchArgs.QUERY } + : new List() { IndexName, SearchArgs.SEARCH, SearchArgs.QUERY }; q.SerializeRedisArgs(args); return new SerializedCommand(FT.PROFILE, args); @@ -172,9 +172,9 @@ public static SerializedCommand ProfileSearch(string IndexName, Query q, bool li public static SerializedCommand ProfileAggregate(string IndexName, AggregationRequest query, bool limited = false) { - var args = (limited) - ? new List{IndexName, SearchArgs.AGGREGATE, SearchArgs.LIMITED, SearchArgs.QUERY} - : new List{IndexName, SearchArgs.AGGREGATE, SearchArgs.QUERY}; + var args = (limited) + ? new List { IndexName, SearchArgs.AGGREGATE, SearchArgs.LIMITED, SearchArgs.QUERY } + : new List { IndexName, SearchArgs.AGGREGATE, SearchArgs.QUERY }; query.SerializeRedisArgs(); args.AddRange(query.GetArgs()); diff --git a/src/NRedisStack/Search/SearchCommands.cs b/src/NRedisStack/Search/SearchCommands.cs index a53772d8..9bb74dde 100644 --- a/src/NRedisStack/Search/SearchCommands.cs +++ b/src/NRedisStack/Search/SearchCommands.cs @@ -16,7 +16,7 @@ public SearchCommands(IDatabase db, int? defaultDialect) : base(db) public void SetDefaultDialect(int? defaultDialect) { - if(defaultDialect == 0) + if (defaultDialect == 0) { throw new System.ArgumentOutOfRangeException("DIALECT=0 cannot be set."); } @@ -87,7 +87,7 @@ public bool Create(string indexName, FTCreateParams parameters, Schema schema) /// public bool Create(string indexName, Schema schema) { - return Create(indexName, new FTCreateParams(), schema); + return Create(indexName, new FTCreateParams(), schema); } /// @@ -134,7 +134,7 @@ public string Explain(string indexName, string query, int? dialect = null) { dialect = defaultDialect; } - return _db.Execute(SearchCommandBuilder.Explain(indexName, query, dialect)).ToString(); + return _db.Execute(SearchCommandBuilder.Explain(indexName, query, dialect)).ToString()!; } /// @@ -222,7 +222,7 @@ public Dictionary> SynDump(string indexName) { var term = resp[i].ToString(); var synonyms = (resp[i + 1]).ToArray().Select(x => x.ToString()).ToList(); // TODO: consider leave synonyms as RedisValue[] - result.Add(term, synonyms); + result.Add(term!, synonyms!); } return result; } diff --git a/src/NRedisStack/Search/SearchCommandsAsync.cs b/src/NRedisStack/Search/SearchCommandsAsync.cs index 96994a73..6935e948 100644 --- a/src/NRedisStack/Search/SearchCommandsAsync.cs +++ b/src/NRedisStack/Search/SearchCommandsAsync.cs @@ -31,7 +31,7 @@ public async Task AggregateAsync(string index, AggregationReq var result = await _db.ExecuteAsync(SearchCommandBuilder.Aggregate(index, query)); if (query.IsWithCursor()) { - var results = (RedisResult[])result; + var results = (RedisResult[])result!; return new AggregationResult(results[0], (long)results[1]); } @@ -134,7 +134,7 @@ public async Task ExplainAsync(string indexName, string query, int? dial dialect = defaultDialect; } - return (await _db.ExecuteAsync(SearchCommandBuilder.Explain(indexName, query, dialect))).ToString(); + return (await _db.ExecuteAsync(SearchCommandBuilder.Explain(indexName, query, dialect))).ToString()!; } /// @@ -227,7 +227,7 @@ public async Task>> SynDumpAsync(string indexNam { var term = resp[i].ToString(); var synonyms = (resp[i + 1]).ToArray().Select(x => x.ToString()).ToList(); // TODO: consider leave synonyms as RedisValue[] - result.Add(term, synonyms); + result.Add(term!, synonyms!); } return result; } diff --git a/src/NRedisStack/Search/SearchResult.cs b/src/NRedisStack/Search/SearchResult.cs index d111f6eb..51c34e95 100644 --- a/src/NRedisStack/Search/SearchResult.cs +++ b/src/NRedisStack/Search/SearchResult.cs @@ -50,11 +50,11 @@ internal SearchResult(RedisResult[] resp, bool hasContent, bool hasScores, bool Documents = docs; for (int i = 1; i < resp.Length; i += step) { - var id = (string)resp[i]; + var id = resp[i].ToString(); double score = 1.0; - byte[] payload = null; - RedisValue[] fields = null; - string[] scoreExplained = null; + byte[]? payload = null; + RedisValue[]? fields = null; + string[]? scoreExplained = null; if (hasScores) { // if (shouldExplainScore) @@ -66,20 +66,20 @@ internal SearchResult(RedisResult[] resp, bool hasContent, bool hasScores, bool // } //else //{ - score = (double)resp[i + scoreOffset]; + score = (double)resp[i + scoreOffset]; //} } if (hasPayloads) { - payload = (byte[])resp[i + payloadOffset]; + payload = (byte[]?)resp[i + payloadOffset]; } if (hasContent) { - fields = (RedisValue[])resp[i + contentOffset]; + fields = (RedisValue[]?)resp[i + contentOffset]; } - docs.Add(Document.Load(id, score, payload, fields, scoreExplained)); + docs.Add(Document.Load(id!, score, payload, fields, scoreExplained)); } } } diff --git a/src/NRedisStack/Tdigest/TdigestCommands.cs b/src/NRedisStack/Tdigest/TdigestCommands.cs index 72d5f847..fd11a3e8 100644 --- a/src/NRedisStack/Tdigest/TdigestCommands.cs +++ b/src/NRedisStack/Tdigest/TdigestCommands.cs @@ -45,7 +45,7 @@ public double Max(RedisKey key) public double Min(RedisKey key) { var cmd = TdigestCommandBuilder.Min(key); - var res =_db.Execute(cmd); + var res = _db.Execute(cmd); return res.ToDouble(); } diff --git a/src/NRedisStack/TimeSeries/DataTypes/TimeSeriesInformation.cs b/src/NRedisStack/TimeSeries/DataTypes/TimeSeriesInformation.cs index e127ea44..3478c25a 100644 --- a/src/NRedisStack/TimeSeries/DataTypes/TimeSeriesInformation.cs +++ b/src/NRedisStack/TimeSeries/DataTypes/TimeSeriesInformation.cs @@ -22,12 +22,12 @@ public class TimeSeriesInformation /// /// First timestamp present in the time-series. /// - public TimeStamp FirstTimeStamp { get; private set; } + public TimeStamp? FirstTimeStamp { get; private set; } /// /// Last timestamp present in the time-series. /// - public TimeStamp LastTimeStamp { get; private set; } + public TimeStamp? LastTimeStamp { get; private set; } /// /// Retention time, in milliseconds, for the time-series. @@ -53,36 +53,38 @@ public class TimeSeriesInformation /// /// A readonly list of TimeSeriesLabel that represent metadata labels of the time-series. /// - public IReadOnlyList Labels { get; private set; } + public IReadOnlyList? Labels { get; private set; } /// /// Source key for the queries time series key. /// - public string SourceKey { get; private set; } + public string? SourceKey { get; private set; } /// /// A readonly list of TimeSeriesRules that represent compaction Rules of the time-series. /// - public IReadOnlyList Rules { get; private set; } + public IReadOnlyList? Rules { get; private set; } /// /// The policy will define handling of duplicate samples. /// - public TsDuplicatePolicy? DuplicatePolicy { get; private set; } + public TsDuplicatePolicy? DuplicatePolicy { get; private set; } /// /// In DEBUG mode: Key self name. /// - public string? KeySelfName { get; private set; } + public string? KeySelfName { get; private set; } /// /// In DEBUG mode: gives more information about the chunks /// public IReadOnlyList? Chunks { get; private set; } + + [Obsolete] internal TimeSeriesInformation(long totalSamples, long memoryUsage, - TimeStamp firstTimeStamp, TimeStamp lastTimeStamp, long retentionTime, - long chunkCount, long chunkSize, IReadOnlyList labels, - string sourceKey, IReadOnlyList rules, TsDuplicatePolicy? policy, + TimeStamp? firstTimeStamp, TimeStamp? lastTimeStamp, long retentionTime, + long chunkCount, long chunkSize, IReadOnlyList? labels, + string? sourceKey, IReadOnlyList? rules, TsDuplicatePolicy? policy, string? keySelfName = null, IReadOnlyList? chunks = null) { TotalSamples = totalSamples; @@ -95,7 +97,7 @@ internal TimeSeriesInformation(long totalSamples, long memoryUsage, SourceKey = sourceKey; Rules = rules; // backwards compatible with RedisTimeSeries < v1.4 - MaxSamplesPerChunk = chunkSize/16; + MaxSamplesPerChunk = chunkSize / 16; ChunkSize = chunkSize; // configure what to do on duplicate sample > v1.4 DuplicatePolicy = policy; diff --git a/src/NRedisStack/TimeSeries/DataTypes/TimeSeriesTuple.cs b/src/NRedisStack/TimeSeries/DataTypes/TimeSeriesTuple.cs index abba2ec5..bc4afd85 100644 --- a/src/NRedisStack/TimeSeries/DataTypes/TimeSeriesTuple.cs +++ b/src/NRedisStack/TimeSeries/DataTypes/TimeSeriesTuple.cs @@ -37,7 +37,7 @@ obj is TimeSeriesTuple tuple && /// /// TimeSeriesTuple public static implicit operator string(TimeSeriesTuple tst) => - string.Format("Time: {0}, Val:{1}", (string)tst.Time, tst.Val); + string.Format("Time: {0}, Val:{1}", (string)tst.Time!, tst.Val); /// /// TimeSeriesTuple object hash code. diff --git a/src/NRedisStack/TimeSeries/DataTypes/TimeStamp.cs b/src/NRedisStack/TimeSeries/DataTypes/TimeStamp.cs index 1dfe3e76..86892ac3 100644 --- a/src/NRedisStack/TimeSeries/DataTypes/TimeStamp.cs +++ b/src/NRedisStack/TimeSeries/DataTypes/TimeStamp.cs @@ -64,7 +64,7 @@ public static implicit operator long(TimeStamp ts) => /// Implicit cast from TimeStamp to string. /// /// TimeStamp - public static implicit operator string(TimeStamp ts) => ts.Value.ToString(); + public static implicit operator string?(TimeStamp ts) => ts.Value.ToString(); /// /// Implicit cast from DateTime to TimeStamp. diff --git a/src/NRedisStack/TimeSeries/ITimeSeriesCommands.cs b/src/NRedisStack/TimeSeries/ITimeSeriesCommands.cs index e9c13abf..8caec91f 100644 --- a/src/NRedisStack/TimeSeries/ITimeSeriesCommands.cs +++ b/src/NRedisStack/TimeSeries/ITimeSeriesCommands.cs @@ -18,7 +18,7 @@ public interface ITimeSeriesCommands /// Optinal: Define handling of duplicate samples behavior (avalible for RedisTimeseries >= 1.4) /// If the operation executed successfully /// - bool Create(string key, long? retentionTime = null, IReadOnlyCollection labels = null, bool? uncompressed = null, long? chunkSizeBytes = null, TsDuplicatePolicy? duplicatePolicy = null); + bool Create(string key, long? retentionTime = null, IReadOnlyCollection? labels = null, bool? uncompressed = null, long? chunkSizeBytes = null, TsDuplicatePolicy? duplicatePolicy = null); #endregion @@ -52,7 +52,7 @@ public interface ITimeSeriesCommands /// The timestamp value of the new sample /// TimeStamp Add(string key, TimeStamp timestamp, double value, long? retentionTime = null, - IReadOnlyCollection labels = null, bool? uncompressed = null, + IReadOnlyCollection? labels = null, bool? uncompressed = null, long? chunkSizeBytes = null, TsDuplicatePolicy? duplicatePolicy = null); /// diff --git a/src/NRedisStack/TimeSeries/ITimeSeriesCommandsAsync.cs b/src/NRedisStack/TimeSeries/ITimeSeriesCommandsAsync.cs index 57b0ca7e..dfd46657 100644 --- a/src/NRedisStack/TimeSeries/ITimeSeriesCommandsAsync.cs +++ b/src/NRedisStack/TimeSeries/ITimeSeriesCommandsAsync.cs @@ -18,7 +18,7 @@ public interface ITimeSeriesCommandsAsync /// Optinal: Define handling of duplicate samples behavior (avalible for RedisTimeseries >= 1.4) /// If the operation executed successfully /// - Task CreateAsync(string key, long? retentionTime = null, IReadOnlyCollection labels = null, bool? uncompressed = null, long? chunkSizeBytes = null, TsDuplicatePolicy? duplicatePolicy = null); + Task CreateAsync(string key, long? retentionTime = null, IReadOnlyCollection? labels = null, bool? uncompressed = null, long? chunkSizeBytes = null, TsDuplicatePolicy? duplicatePolicy = null); #endregion @@ -51,7 +51,7 @@ public interface ITimeSeriesCommandsAsync /// Optioal: overwrite key and database configuration for DUPLICATE_POLICY /// The timestamp value of the new sample /// - Task AddAsync(string key, TimeStamp timestamp, double value, long? retentionTime = null, IReadOnlyCollection labels = null, bool? uncompressed = null, long? chunkSizeBytes = null, TsDuplicatePolicy? duplicatePolicy = null); + Task AddAsync(string key, TimeStamp timestamp, double value, long? retentionTime = null, IReadOnlyCollection? labels = null, bool? uncompressed = null, long? chunkSizeBytes = null, TsDuplicatePolicy? duplicatePolicy = null); /// /// Append new samples to multiple series. diff --git a/src/NRedisStack/TimeSeries/TimeSeriesAux.cs b/src/NRedisStack/TimeSeries/TimeSeriesAux.cs index 9a0a0291..b7dfb289 100644 --- a/src/NRedisStack/TimeSeries/TimeSeriesAux.cs +++ b/src/NRedisStack/TimeSeries/TimeSeriesAux.cs @@ -30,7 +30,7 @@ public static void AddChunkSize(this IList args, long? chunkSize) } } - public static void AddLabels(this IList args, IReadOnlyCollection labels) + public static void AddLabels(this IList args, IReadOnlyCollection? labels) { if (labels != null) { @@ -215,7 +215,7 @@ public static void AddRule(this IList args, TimeSeriesRule rule) args.Add(rule.TimeBucket); } - public static List BuildTsCreateArgs(string key, long? retentionTime, IReadOnlyCollection labels, bool? uncompressed, + public static List BuildTsCreateArgs(string key, long? retentionTime, IReadOnlyCollection? labels, bool? uncompressed, long? chunkSizeBytes, TsDuplicatePolicy? policy) { var args = new List { key }; @@ -239,7 +239,7 @@ public static List BuildTsAlterArgs(string key, long? retentionTime, lon } public static List BuildTsAddArgs(string key, TimeStamp timestamp, double value, long? retentionTime, - IReadOnlyCollection labels, bool? uncompressed, long? chunkSizeBytes, TsDuplicatePolicy? policy) + IReadOnlyCollection? labels, bool? uncompressed, long? chunkSizeBytes, TsDuplicatePolicy? policy) { var args = new List { key, timestamp.Value, value }; args.AddRetentionTime(retentionTime); diff --git a/src/NRedisStack/TimeSeries/TimeSeriesCommands.cs b/src/NRedisStack/TimeSeries/TimeSeriesCommands.cs index b6566fa1..3b304b79 100644 --- a/src/NRedisStack/TimeSeries/TimeSeriesCommands.cs +++ b/src/NRedisStack/TimeSeries/TimeSeriesCommands.cs @@ -14,7 +14,7 @@ public TimeSeriesCommands(IDatabase db) : base(db) #region Create /// - public bool Create(string key, long? retentionTime = null, IReadOnlyCollection labels = null, bool? uncompressed = null, long? chunkSizeBytes = null, TsDuplicatePolicy? duplicatePolicy = null) + public bool Create(string key, long? retentionTime = null, IReadOnlyCollection? labels = null, bool? uncompressed = null, long? chunkSizeBytes = null, TsDuplicatePolicy? duplicatePolicy = null) { return _db.Execute(TimeSeriesCommandsBuilder.Create(key, retentionTime, labels, uncompressed, chunkSizeBytes, @@ -34,7 +34,7 @@ public bool Alter(string key, long? retentionTime = null, long? chunkSizeBytes = /// public TimeStamp Add(string key, TimeStamp timestamp, double value, long? retentionTime = null, - IReadOnlyCollection labels = null, bool? uncompressed = null, + IReadOnlyCollection? labels = null, bool? uncompressed = null, long? chunkSizeBytes = null, TsDuplicatePolicy? duplicatePolicy = null) { return _db.Execute(TimeSeriesCommandsBuilder.Add(key, timestamp, value, retentionTime, labels, @@ -44,7 +44,7 @@ public TimeStamp Add(string key, TimeStamp timestamp, double value, long? retent /// public IReadOnlyList MAdd(IReadOnlyCollection<(string key, TimeStamp timestamp, double value)> sequence) { - return _db.Execute(TimeSeriesCommandsBuilder.MAdd(sequence)).ToTimeStampArray(); + return _db.Execute(TimeSeriesCommandsBuilder.MAdd(sequence)).ToTimeStampArray()!; } /// @@ -195,6 +195,7 @@ public IReadOnlyList RevRange(string key, #region General /// + [Obsolete] public TimeSeriesInformation Info(string key, bool debug = false) { return _db.Execute(TimeSeriesCommandsBuilder.Info(key, debug)).ToTimeSeriesInfo(); diff --git a/src/NRedisStack/TimeSeries/TimeSeriesCommandsAsync.cs b/src/NRedisStack/TimeSeries/TimeSeriesCommandsAsync.cs index ede7f288..3a7e1a4b 100644 --- a/src/NRedisStack/TimeSeries/TimeSeriesCommandsAsync.cs +++ b/src/NRedisStack/TimeSeries/TimeSeriesCommandsAsync.cs @@ -14,7 +14,7 @@ public TimeSeriesCommandsAsync(IDatabaseAsync db) #region Create /// - public async Task CreateAsync(string key, long? retentionTime = null, IReadOnlyCollection labels = null, bool? uncompressed = null, long? chunkSizeBytes = null, TsDuplicatePolicy? duplicatePolicy = null) + public async Task CreateAsync(string key, long? retentionTime = null, IReadOnlyCollection? labels = null, bool? uncompressed = null, long? chunkSizeBytes = null, TsDuplicatePolicy? duplicatePolicy = null) { return (await _db.ExecuteAsync(TimeSeriesCommandsBuilder.Create(key, retentionTime, labels, uncompressed, chunkSizeBytes, @@ -32,7 +32,7 @@ public async Task AlterAsync(string key, long? retentionTime = null, long? } /// - public async Task AddAsync(string key, TimeStamp timestamp, double value, long? retentionTime = null, IReadOnlyCollection labels = null, bool? uncompressed = null, long? chunkSizeBytes = null, TsDuplicatePolicy? duplicatePolicy = null) + public async Task AddAsync(string key, TimeStamp timestamp, double value, long? retentionTime = null, IReadOnlyCollection? labels = null, bool? uncompressed = null, long? chunkSizeBytes = null, TsDuplicatePolicy? duplicatePolicy = null) { return (await _db.ExecuteAsync(TimeSeriesCommandsBuilder.Add(key, timestamp, value, retentionTime, labels, uncompressed, chunkSizeBytes, duplicatePolicy))).ToTimeStamp(); @@ -192,6 +192,7 @@ public async Task> RevRangeAsync(string key, #region General /// + [Obsolete] public async Task InfoAsync(string key, bool debug = false) { return (await _db.ExecuteAsync(TimeSeriesCommandsBuilder.Info(key, debug))).ToTimeSeriesInfo(); diff --git a/src/NRedisStack/TimeSeries/TimeSeriesCommandsBuilder.cs b/src/NRedisStack/TimeSeries/TimeSeriesCommandsBuilder.cs index 9c3362e4..a9ae45a9 100644 --- a/src/NRedisStack/TimeSeries/TimeSeriesCommandsBuilder.cs +++ b/src/NRedisStack/TimeSeries/TimeSeriesCommandsBuilder.cs @@ -9,7 +9,7 @@ public static class TimeSeriesCommandsBuilder { #region Create - public static SerializedCommand Create(string key, long? retentionTime = null, IReadOnlyCollection labels = null, bool? uncompressed = null, long? chunkSizeBytes = null, TsDuplicatePolicy? duplicatePolicy = null) + public static SerializedCommand Create(string key, long? retentionTime = null, IReadOnlyCollection? labels = null, bool? uncompressed = null, long? chunkSizeBytes = null, TsDuplicatePolicy? duplicatePolicy = null) { var args = TimeSeriesAux.BuildTsCreateArgs(key, retentionTime, labels, uncompressed, chunkSizeBytes, duplicatePolicy); return new SerializedCommand(TS.CREATE, args); @@ -26,7 +26,7 @@ public static SerializedCommand Alter(string key, long? retentionTime = null, lo } public static SerializedCommand Add(string key, TimeStamp timestamp, double value, long? retentionTime = null, - IReadOnlyCollection labels = null, bool? uncompressed = null, + IReadOnlyCollection? labels = null, bool? uncompressed = null, long? chunkSizeBytes = null, TsDuplicatePolicy? duplicatePolicy = null) { var args = TimeSeriesAux.BuildTsAddArgs(key, timestamp, value, retentionTime, labels, uncompressed, chunkSizeBytes, duplicatePolicy); diff --git a/src/NRedisStack/TopK/TopKCommandBuilder.cs b/src/NRedisStack/TopK/TopKCommandBuilder.cs index 2adf5fa7..fd697a1d 100644 --- a/src/NRedisStack/TopK/TopKCommandBuilder.cs +++ b/src/NRedisStack/TopK/TopKCommandBuilder.cs @@ -40,7 +40,7 @@ public static SerializedCommand IncrBy(RedisKey key, params Tuple public RedisResult[]? Add(RedisKey key, params RedisValue[] items) { - return (RedisResult[]?) _db.Execute(TopKCommandBuilder.Add(key, items)); + return (RedisResult[]?)_db.Execute(TopKCommandBuilder.Add(key, items)); } /// diff --git a/src/NRedisStack/TopK/TopKCommandsAsync.cs b/src/NRedisStack/TopK/TopKCommandsAsync.cs index 20576147..0fd9656a 100644 --- a/src/NRedisStack/TopK/TopKCommandsAsync.cs +++ b/src/NRedisStack/TopK/TopKCommandsAsync.cs @@ -14,7 +14,7 @@ public TopKCommandsAsync(IDatabaseAsync db) /// public async Task AddAsync(RedisKey key, params RedisValue[] items) { - return (RedisResult[]?) await _db.ExecuteAsync(TopKCommandBuilder.Add(key, items)); + return (RedisResult[]?)await _db.ExecuteAsync(TopKCommandBuilder.Add(key, items)); } /// diff --git a/src/NRedisStack/Transactions.cs b/src/NRedisStack/Transactions.cs index 2399090d..b14e68de 100644 --- a/src/NRedisStack/Transactions.cs +++ b/src/NRedisStack/Transactions.cs @@ -12,15 +12,17 @@ public Transaction(IDatabase db) _transaction = db.CreateTransaction(); } - public ConditionResult AddCondition(Condition condition) => _transaction.AddCondition(condition); + public ConditionResult AddCondition(Condition condition) => _transaction.AddCondition(condition); - public bool Execute(CommandFlags flags = CommandFlags.None) => _transaction.Execute(flags); + public bool Execute(CommandFlags flags = CommandFlags.None) => _transaction.Execute(flags); public Task ExecuteAsync(CommandFlags flags = CommandFlags.None) => _transaction.ExecuteAsync(flags); public BloomCommandsAsync Bf => new BloomCommandsAsync(_transaction); public CmsCommandsAsync Cms => new CmsCommandsAsync(_transaction); public CuckooCommandsAsync Cf => new CuckooCommandsAsync(_transaction); + + [Obsolete] public GraphCommandsAsync Graph => new GraphCommandsAsync(_transaction); public JsonCommandsAsync Json => new JsonCommandsAsync(_transaction); public SearchCommandsAsync Ft => new SearchCommandsAsync(_transaction); diff --git a/tests/Doc/HashExample.cs b/tests/Doc/HashExample.cs index 309d0374..38c279fd 100644 --- a/tests/Doc/HashExample.cs +++ b/tests/Doc/HashExample.cs @@ -122,7 +122,7 @@ public void run() //REMOVE_END // Bike stats: crashes=1, owners=1 //STEP_END - //HIDE_START + //HIDE_START } } //HIDE_END \ No newline at end of file diff --git a/tests/Doc/SearchQuickstartExample.cs b/tests/Doc/SearchQuickstartExample.cs index 7ced7c4f..256e3833 100644 --- a/tests/Doc/SearchQuickstartExample.cs +++ b/tests/Doc/SearchQuickstartExample.cs @@ -38,7 +38,7 @@ public void run() Brand = "Velorim", Model = "Jigger", Price = 270M, - Description = "Small and powerful, the Jigger is the best ride " + + Description = "Small and powerful, the Jigger is the best ride " + "for the smallest of tikes! This is the tiniest " + "kids’ pedal bike on the market available without" + " a coaster brake, the Jigger is the vehicle of " + diff --git a/tests/Doc/SetGetExample.cs b/tests/Doc/SetGetExample.cs index 9f92fa35..447d1dbc 100644 --- a/tests/Doc/SetGetExample.cs +++ b/tests/Doc/SetGetExample.cs @@ -31,7 +31,7 @@ public void run() Assert.True(status); Assert.Equal("Process 134", value.ToString()); //REMOVE_END - //HIDE_START + //HIDE_START } } //HIDE_END diff --git a/tests/NRedisStack.Tests/CuckooFilter/CuckooTests.cs b/tests/NRedisStack.Tests/CuckooFilter/CuckooTests.cs index 2cc62157..7ac2ca3d 100644 --- a/tests/NRedisStack.Tests/CuckooFilter/CuckooTests.cs +++ b/tests/NRedisStack.Tests/CuckooFilter/CuckooTests.cs @@ -30,7 +30,7 @@ public async Task TestReserveBasicAsync() db.Execute("FLUSHALL"); var cf = db.CF(); Assert.True(await cf.ReserveAsync(key, 100L, maxIterations: 20, expansion: 1)); - Assert.ThrowsAsync(async () => await cf.ReserveAsync(key, 100L)); + _ = Assert.ThrowsAsync(async () => await cf.ReserveAsync(key, 100L)); Assert.True(await (cf.AddAsync(key, "item1"))); Assert.True(await cf.ExistsAsync(key, "item1")); @@ -90,7 +90,7 @@ public void TestCountFilterDoesNotExist() db.Execute("FLUSHALL"); var cf = db.CF(); - Assert.Equal(cf.Count("notExistFilter", "notExistItem"), 0); + Assert.Equal(0, cf.Count("notExistFilter", "notExistItem")); } [Fact] @@ -100,7 +100,7 @@ public async Task TestCountFilterDoesNotExistAsync() db.Execute("FLUSHALL"); var cf = db.CF(); - Assert.Equal(await cf.CountAsync("notExistFilter", "notExistItem"), 0); + Assert.Equal(0, await cf.CountAsync("notExistFilter", "notExistItem")); } [Fact] @@ -111,7 +111,7 @@ public void TestCountFilterExist() var cf = db.CF(); cf.Insert(key, new RedisValue[] { "foo" }); - Assert.Equal(cf.Count(key, "notExistItem"), 0); + Assert.Equal(0, cf.Count(key, "notExistItem")); } [Fact] @@ -122,7 +122,7 @@ public async Task TestCountFilterExistAsync() var cf = db.CF(); await cf.InsertAsync(key, new RedisValue[] { "foo" }); - Assert.Equal(await cf.CountAsync(key, "notExistItem"), 0); + Assert.Equal(0, await cf.CountAsync(key, "notExistItem")); } [Fact] @@ -133,7 +133,7 @@ public void TestCountItemExist() var cf = db.CF(); cf.Insert(key, new RedisValue[] { "foo" }); - Assert.Equal(cf.Count(key, "foo"), 1); + Assert.Equal(1, cf.Count(key, "foo")); } [Fact] @@ -144,7 +144,7 @@ public async Task TestCountItemExistAsync() var cf = db.CF(); await cf.InsertAsync(key, new RedisValue[] { "foo" }); - Assert.Equal(await cf.CountAsync(key, "foo"), 1); + Assert.Equal(1, await cf.CountAsync(key, "foo")); } [Fact] @@ -280,7 +280,7 @@ public void TestInsertNX() Assert.Equal(result, new bool[] { false, false, false }); // test empty items: - Assert.Throws(() => cf.InsertNX(key, new RedisValue[]{})); + Assert.Throws(() => cf.InsertNX(key, new RedisValue[] { })); } [Fact] @@ -292,7 +292,7 @@ public async Task TestInsertNXAsync() RedisValue[] items = new RedisValue[] { "item1", "item2", "item3" }; - Assert.ThrowsAsync(async () => await cf.InsertNXAsync(key, items, 1024, true)); + _ = Assert.ThrowsAsync(async () => await cf.InsertNXAsync(key, items, 1024, true)); var result = await cf.InsertNXAsync(key, items, 1024); await cf.InsertNXAsync(key, items, 10245, true); var trues = new bool[] { true, true, true }; @@ -308,7 +308,7 @@ public async Task TestInsertNXAsync() Assert.Equal(result, new bool[] { false, false, false }); // test empty items: - Assert.ThrowsAsync(async () => await cf.InsertNXAsync(key, new RedisValue[]{})); + _ = Assert.ThrowsAsync(async () => await cf.InsertNXAsync(key, new RedisValue[] { })); } [Fact] diff --git a/tests/NRedisStack.Tests/Examples/ExampleTests.cs b/tests/NRedisStack.Tests/Examples/ExampleTests.cs index de9a6971..be3f2ca7 100644 --- a/tests/NRedisStack.Tests/Examples/ExampleTests.cs +++ b/tests/NRedisStack.Tests/Examples/ExampleTests.cs @@ -20,7 +20,7 @@ namespace NRedisStack.Tests; public class ExampleTests : AbstractNRedisStackTest, IDisposable { private readonly ITestOutputHelper testOutputHelper; - private readonly string key = "EXAMPLES_TESTS"; + // private readonly string key = "EXAMPLES_TESTS"; public ExampleTests(RedisFixture redisFixture, ITestOutputHelper testOutputHelper) : base(redisFixture) { this.testOutputHelper = testOutputHelper; @@ -105,13 +105,13 @@ public void PipelineExample() pipeline.Json.SetAsync("person", "$", new { name = "John", age = 30, city = "New York", nicknames = new[] { "John", "Johny", "Jo" } }); // Increase age by 2 - pipeline.Json.NumIncrbyAsync("person", "$.age", 2); + _ = pipeline.Json.NumIncrbyAsync("person", "$.age", 2); // Clear the nicknames from the Json - pipeline.Json.ClearAsync("person", "$.nicknames"); + _ = pipeline.Json.ClearAsync("person", "$.nicknames"); // Del the nicknames - pipeline.Json.DelAsync("person", "$.nicknames"); + _ = pipeline.Json.DelAsync("person", "$.nicknames"); // Get the Json response var getResponse = pipeline.Json.GetAsync("person"); @@ -192,8 +192,8 @@ public async Task PipelineWithAsync() var labels2 = new List { label2 }; // Create a new time-series. - pipeline.Ts.CreateAsync("temp:TLV", labels: labels1); - pipeline.Ts.CreateAsync("temp:JLM", labels: labels2); + _ = pipeline.Ts.CreateAsync("temp:TLV", labels: labels1); + _ = pipeline.Ts.CreateAsync("temp:JLM", labels: labels2); // Adding multiple sequenece of time-series data. List<(string, TimeStamp, double)> sequence1 = new List<(string, TimeStamp, double)>() @@ -212,8 +212,8 @@ public async Task PipelineWithAsync() }; // Adding mutiple samples to mutiple series. - pipeline.Ts.MAddAsync(sequence1); - pipeline.Ts.MAddAsync(sequence2); + _ = pipeline.Ts.MAddAsync(sequence1); + _ = pipeline.Ts.MAddAsync(sequence2); // Execute the pipeline pipeline.Execute(); @@ -230,7 +230,7 @@ public async Task PipelineWithAsync() } [SkipIfRedis(Is.OSSCluster)] - public async Task TransactionExample() + public void TransactionExample() { // Connect to the Redis server // var redis = ConnectionMultiplexer.Connect("localhost"); @@ -245,18 +245,18 @@ public async Task TransactionExample() var tran = new Transaction(db); // Add account details with Json.Set to transaction - tran.Json.SetAsync("accdetails:Jeeva", "$", new { name = "Jeeva", totalAmount = 1000, bankName = "City" }); - tran.Json.SetAsync("accdetails:Shachar", "$", new { name = "Shachar", totalAmount = 1000, bankName = "City" }); + _ = tran.Json.SetAsync("accdetails:Jeeva", "$", new { name = "Jeeva", totalAmount = 1000, bankName = "City" }); + _ = tran.Json.SetAsync("accdetails:Shachar", "$", new { name = "Shachar", totalAmount = 1000, bankName = "City" }); // Get the Json response var getShachar = tran.Json.GetAsync("accdetails:Shachar"); var getJeeva = tran.Json.GetAsync("accdetails:Jeeva"); // Debit 200 from Jeeva - tran.Json.NumIncrbyAsync("accdetails:Jeeva", "$.totalAmount", -200); + _ = tran.Json.NumIncrbyAsync("accdetails:Jeeva", "$.totalAmount", -200); // Credit 200 from Shachar - tran.Json.NumIncrbyAsync("accdetails:Shachar", "$.totalAmount", 200); + _ = tran.Json.NumIncrbyAsync("accdetails:Shachar", "$.totalAmount", 200); // Get total amount for both Jeeva = 800 & Shachar = 1200 var totalAmtOfJeeva = tran.Json.GetAsync("accdetails:Jeeva", path: "$.totalAmount"); diff --git a/tests/NRedisStack.Tests/Gears/GearsTests.cs b/tests/NRedisStack.Tests/Gears/GearsTests.cs index 16074dbf..e4c5e7bb 100644 --- a/tests/NRedisStack.Tests/Gears/GearsTests.cs +++ b/tests/NRedisStack.Tests/Gears/GearsTests.cs @@ -5,7 +5,7 @@ namespace NRedisStack.Tests.Gears; public class GearsTests : AbstractNRedisStackTest, IDisposable { - private readonly string key = "GEARS_TESTS"; + // private readonly string key = "GEARS_TESTS"; public GearsTests(RedisFixture redisFixture) : base(redisFixture) { } [SkipIfRedis(Comparison.LessThan, "7.1.242")] diff --git a/tests/NRedisStack.Tests/Graph/GraphTests.cs b/tests/NRedisStack.Tests/Graph/GraphTests.cs index 28a742cf..10a6e6b3 100644 --- a/tests/NRedisStack.Tests/Graph/GraphTests.cs +++ b/tests/NRedisStack.Tests/Graph/GraphTests.cs @@ -8,20 +8,13 @@ namespace NRedisStack.Tests.Graph; public class GraphTests : AbstractNRedisStackTest, IDisposable { - private readonly string key = "GRAPH_TESTS"; + // private readonly string key = "GRAPH_TESTS"; public GraphTests(RedisFixture redisFixture) : base(redisFixture) { } #region SyncTests [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] - public void TestReserveBasic() - { - IDatabase db = redisFixture.Redis.GetDatabase(); - db.Execute("FLUSHALL"); - var graph = db.GRAPH(); - } - - [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestCreateNode() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -38,13 +31,14 @@ public void TestCreateNode() Assert.Equal(2, stats.PropertiesSet); Assert.NotNull(stats.QueryInternalExecutionTime); - Assert.Equal(0, resultSet.Count); + Assert.Empty(resultSet); // delete graph.Delete("social"); } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestCreateLabeledNode() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -61,11 +55,12 @@ public void TestCreateLabeledNode() // Assert.NotNull(stats.getstringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); Assert.NotNull(stats.QueryInternalExecutionTime); - Assert.Equal(0, resultSet.Count); + Assert.Empty(resultSet); // Assert.False(resultSet..iterator().MoveNext()); } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestConnectNodes() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -89,10 +84,11 @@ public void TestConnectNodes() // Assert.NotNull(stats.getstringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); Assert.NotNull(stats.QueryInternalExecutionTime); - Assert.Equal(0, resultSet.Count); + Assert.Empty(resultSet); } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestDeleteNodes() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -115,7 +111,7 @@ public void TestDeleteNodes() Assert.Equal(0, delStats.PropertiesSet); // Assert.NotNull(delStats.getstringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); Assert.NotNull(delStats.QueryInternalExecutionTime); - Assert.Equal(0, deleteResult.Count); + Assert.Empty(deleteResult); // Assert.False(deleteResult.iterator().MoveNext()); Assert.NotNull(graph.Query("social", "CREATE (:person{name:'roi',age:32})")); @@ -135,11 +131,12 @@ public void TestDeleteNodes() Assert.Equal(0, delStats.PropertiesSet); // Assert.NotNull(delStats.getstringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); Assert.NotNull(delStats.QueryInternalExecutionTime); - Assert.Equal(0, deleteResult.Count); + Assert.Empty(deleteResult); // Assert.False(deleteResult.iterator().MoveNext()); } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestDeleteRelationship() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -165,11 +162,12 @@ public void TestDeleteRelationship() Assert.Equal(0, delStats.PropertiesSet); // Assert.NotNull(delStats.getstringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); Assert.NotNull(delStats.QueryInternalExecutionTime); - Assert.Equal(0, deleteResult.Count); + Assert.Empty(deleteResult); // Assert.False(deleteResult.iterator().MoveNext()); } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestIndex() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -197,6 +195,7 @@ public void TestIndex() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestHeader() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -210,7 +209,7 @@ public void TestHeader() ResultSet queryResult = graph.Query("social", "MATCH (a:person)-[r:knows]->(b:person) RETURN a,r, a.age"); - Header header = queryResult.Header; + Header header = queryResult.Header!; Assert.NotNull(header); Assert.Equal("Header{" // + "schemaTypes=[COLUMN_SCALAR, COLUMN_SCALAR, COLUMN_SCALAR], " @@ -228,6 +227,7 @@ public void TestHeader() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestRecord() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -300,7 +300,7 @@ public void TestRecord() Assert.NotNull(stats.QueryInternalExecutionTime); Assert.NotEmpty(stats.QueryInternalExecutionTime); - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); // IReadOnlyCollection iterator = resultSet.GetEnumerator(); var iterator = resultSet.GetEnumerator(); Assert.True(iterator.MoveNext()); @@ -353,6 +353,7 @@ public void TestRecord() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestAdditionToProcedures() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -383,13 +384,13 @@ public void TestAdditionToProcedures() ResultSet resultSet = graph.Query("social", "MATCH (a:person)-[r:knows]->(b:person) RETURN a,r"); Assert.NotNull(resultSet.Header); - Header header = resultSet.Header; + Header header = resultSet.Header!; List schemaNames = header.SchemaNames; Assert.NotNull(schemaNames); Assert.Equal(2, schemaNames.Count); Assert.Equal("a", schemaNames[0]); Assert.Equal("r", schemaNames[1]); - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); var iterator = resultSet.GetEnumerator(); Assert.True(iterator.MoveNext()); var record = iterator.Current; @@ -416,13 +417,13 @@ public void TestAdditionToProcedures() "MATCH (a:worker), (b:worker) WHERE (a.lastName = 'a' AND b.lastName='b') CREATE (a)-[:worksWith]->(b)")); resultSet = graph.Query("social", "MATCH (a:worker)-[r:worksWith]->(b:worker) RETURN a,r"); Assert.NotNull(resultSet.Header); - header = resultSet.Header; + header = resultSet.Header!; schemaNames = header.SchemaNames; Assert.NotNull(schemaNames); Assert.Equal(2, schemaNames.Count); Assert.Equal("a", schemaNames[0]); Assert.Equal("r", schemaNames[1]); - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); iterator = resultSet.GetEnumerator(); Assert.True(iterator.MoveNext()); record = iterator.Current; @@ -433,6 +434,7 @@ record = iterator.Current; } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestEscapedQuery() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -452,6 +454,7 @@ public void TestEscapedQuery() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestArraySupport() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -487,15 +490,15 @@ public void TestArraySupport() // check header Assert.NotNull(resultSet.Header); - Header header = resultSet.Header; + Header header = resultSet.Header!; List schemaNames = header.SchemaNames; Assert.NotNull(schemaNames); - Assert.Equal(1, schemaNames.Count); + Assert.Single(schemaNames); Assert.Equal("x", schemaNames[0]); // check record - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); var iterator = resultSet.GetEnumerator(); Assert.True(iterator.MoveNext()); NRedisStack.Graph.Record record = iterator.Current; @@ -509,15 +512,15 @@ public void TestArraySupport() resultSet = graph.Query("social", "MATCH(n) return collect(n) as x"); Assert.NotNull(resultSet.Header); - header = resultSet.Header; + header = resultSet.Header!; schemaNames = header.SchemaNames; Assert.NotNull(schemaNames); - Assert.Equal(1, schemaNames.Count); + Assert.Single(schemaNames); Assert.Equal("x", schemaNames[0]); // check record - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); iterator = resultSet.GetEnumerator(); Assert.True(iterator.MoveNext()); record = iterator.Current; @@ -532,11 +535,11 @@ record = iterator.Current; resultSet = graph.Query("social", "unwind([0,1,2]) as x return x"); Assert.NotNull(resultSet.Header); - header = resultSet.Header; + header = resultSet.Header!; schemaNames = header.SchemaNames; Assert.NotNull(schemaNames); - Assert.Equal(1, schemaNames.Count); + Assert.Single(schemaNames); Assert.Equal("x", schemaNames[0]); // check record @@ -552,6 +555,7 @@ record = iterator.Current; } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestPath() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -604,6 +608,7 @@ public void TestPath() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestNullGraphEntities() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -613,12 +618,14 @@ public void TestNullGraphEntities() Assert.NotNull(graph.Query("social", "CREATE (:L)-[:E]->(:L2)")); // Test a query that produces 1 record with 3 null values. ResultSet resultSet = graph.Query("social", "OPTIONAL MATCH (a:NONEXISTENT)-[e]->(b) RETURN a, e, b"); - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); IEnumerator iterator = resultSet.GetEnumerator(); Assert.True(iterator.MoveNext()); NRedisStack.Graph.Record record = iterator.Current; Assert.False(iterator.MoveNext()); - Assert.Equal(new List() { null, null, null }, record.Values); + Assert.Equal(new List() { null!, null!, null! }, record.Values); + + // Test a query that produces 2 records, with 2 null values in the second. resultSet = graph.Query("social", "MATCH (a) OPTIONAL MATCH (a)-[e]->(b) RETURN a, e, b ORDER BY ID(a)"); @@ -658,6 +665,7 @@ record = resultSet.Skip(1).First(); } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void Test64BitNumber() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -667,7 +675,7 @@ public void Test64BitNumber() Dictionary parameters = new Dictionary(); parameters.Add("val", value); ResultSet resultSet = graph.Query("social", "CREATE (n {val:$val}) RETURN n.val", parameters); - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); // NRedisStack.Graph.Record r = resultSet.GetEnumerator().Current; // Assert.Equal(value, r.Values[0]); @@ -676,6 +684,7 @@ public void Test64BitNumber() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestCachedExecution() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -687,7 +696,7 @@ public void TestCachedExecution() Dictionary parameters = new Dictionary(); parameters.Add("val", 1L); ResultSet resultSet = graph.Query("social", "MATCH (n:N {val:$val}) RETURN n.val", parameters); - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); // NRedisStack.Graph.Record r = resultSet.GetEnumerator().Current; Assert.Equal(parameters["val"], resultSet.First().Values[0]); Assert.False(resultSet.Statistics.CachedExecution); @@ -698,7 +707,7 @@ public void TestCachedExecution() { resultSet = graph.Query("social", "MATCH (n:N {val:$val}) RETURN n.val", parameters); } - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); // r = resultSet.GetEnumerator().Current; // Assert.Equal(parameters["val"], r.Values[0]); Assert.Equal(parameters["val"], resultSet.First().Values[0]); @@ -707,27 +716,29 @@ public void TestCachedExecution() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestMapDataType() { IDatabase db = redisFixture.Redis.GetDatabase(); db.Execute("FLUSHALL"); var graph = db.GRAPH(); - Dictionary expected = new Dictionary(); - expected.Add("a", (long)1); - expected.Add("b", "str"); - expected.Add("c", null); - List d = new List(); - d.Add((long)1); - d.Add((long)2); - d.Add((long)3); + Dictionary expected = new Dictionary + { + { "a", (long)1 }, + { "b", "str" }, + { "c", null } + }; + List d = new List { 1L, 2L, 3L }; expected.Add("d", d); expected.Add("e", true); - Dictionary f = new Dictionary(); - f.Add("x", (long)1); - f.Add("y", (long)2); + Dictionary f = new Dictionary + { + { "x", (long)1 }, + { "y", (long)2 } + }; expected.Add("f", f); ResultSet res = graph.Query("social", "RETURN {a:1, b:'str', c:NULL, d:[1,2,3], e:True, f:{x:1, y:2}}"); - Assert.Equal(1, res.Count); + Assert.Single(res); var iterator = res.GetEnumerator(); iterator.MoveNext(); @@ -737,6 +748,7 @@ public void TestMapDataType() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestGeoPointLatLon() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -751,6 +763,7 @@ public void TestGeoPointLatLon() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestGeoPointLonLat() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -764,10 +777,11 @@ public void TestGeoPointLonLat() AssertTestGeoPoint(graph); } + [Obsolete] private void AssertTestGeoPoint(IGraphCommands graph) { ResultSet results = graph.Query("social", "MATCH (restaurant) RETURN restaurant"); - Assert.Equal(1, results.Count); + Assert.Single(results); var record = results.GetEnumerator(); record.MoveNext(); Assert.Equal(1, record.Current.Size); @@ -780,6 +794,7 @@ private void AssertTestGeoPoint(IGraphCommands graph) } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestPoint() { var point = new Point(30.27822306, -97.75134723); @@ -792,20 +807,22 @@ public void TestPoint() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void timeoutArgument() { IDatabase db = redisFixture.Redis.GetDatabase(); db.Execute("FLUSHALL"); var graph = db.GRAPH(); ResultSet rs = graph.Query("social", "UNWIND range(0,100) AS x WITH x AS x WHERE x = 100 RETURN x", 1L); - Assert.Equal(1, rs.Count); + Assert.Single(rs); var iterator = rs.GetEnumerator(); iterator.MoveNext(); var r = iterator.Current; - Assert.Equal(100l, (long)r.Values[0]); + Assert.Equal(100, (long)r.Values[0]); } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestCachedExecutionReadOnly() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -817,7 +834,7 @@ public void TestCachedExecutionReadOnly() Dictionary parameters = new Dictionary(); parameters.Add("val", 1L); ResultSet resultSet = graph.RO_Query("social", "MATCH (n:N {val:$val}) RETURN n.val", parameters); - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); var iterator = resultSet.GetEnumerator(); iterator.MoveNext(); NRedisStack.Graph.Record r = iterator.Current; @@ -830,7 +847,7 @@ public void TestCachedExecutionReadOnly() { resultSet = graph.RO_Query("social", "MATCH (n:N {val:$val}) RETURN n.val", parameters); } - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); iterator = resultSet.GetEnumerator(); iterator.MoveNext(); r = iterator.Current; @@ -839,6 +856,7 @@ public void TestCachedExecutionReadOnly() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestSimpleReadOnly() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -846,7 +864,7 @@ public void TestSimpleReadOnly() var graph = db.GRAPH(); graph.Query("social", "CREATE (:person{name:'filipe',age:30})"); ResultSet rsRo = graph.RO_Query("social", "MATCH (a:person) WHERE (a.name = 'filipe') RETURN a.age"); - Assert.Equal(1, rsRo.Count); + Assert.Single(rsRo); var iterator = rsRo.GetEnumerator(); iterator.MoveNext(); var r = iterator.Current; @@ -854,6 +872,7 @@ public void TestSimpleReadOnly() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestProfile() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -872,6 +891,7 @@ public void TestProfile() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestExplain() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -890,6 +910,7 @@ public void TestExplain() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestSlowlog() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -905,6 +926,7 @@ public void TestSlowlog() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestList() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -918,6 +940,7 @@ public void TestList() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestConfig() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -931,13 +954,14 @@ public void TestConfig() Assert.True(graph.ConfigSet(name, 250L)); var actual = graph.ConfigGet(name); - Assert.Equal(actual.Count, 1); + Assert.Single(actual); Assert.Equal("250", actual[name].ToString()); - graph.ConfigSet(name, existingValue != null ? existingValue.ToString() : -1); + graph.ConfigSet(name, existingValue != null ? existingValue.ToString()! : -1); } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestModulePrefixs() { IDatabase db1 = redisFixture.Redis.GetDatabase(); @@ -950,6 +974,7 @@ public void TestModulePrefixs() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestCallProcedureDbLabels() { var db = redisFixture.Redis.GetDatabase(); @@ -971,6 +996,7 @@ public void TestCallProcedureDbLabels() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestCallProcedureReadOnly() { var db = redisFixture.Redis.GetDatabase(); @@ -997,14 +1023,7 @@ public void TestCallProcedureReadOnly() #region AsyncTests [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] - public async Task TestReserveBasicAsync() - { - IDatabase db = redisFixture.Redis.GetDatabase(); - db.Execute("FLUSHALL"); - var graph = db.GRAPH(); - } - - [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestCreateNodeAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1021,13 +1040,14 @@ public async Task TestCreateNodeAsync() Assert.Equal(2, stats.PropertiesSet); Assert.NotNull(stats.QueryInternalExecutionTime); - Assert.Equal(0, resultSet.Count); + Assert.Empty(resultSet); // delete await graph.DeleteAsync("social"); } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestCreateLabeledNodeAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1044,11 +1064,12 @@ public async Task TestCreateLabeledNodeAsync() // Assert.NotNull(stats.getstringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); Assert.NotNull(stats.QueryInternalExecutionTime); - Assert.Equal(0, resultSet.Count); + Assert.Empty(resultSet); // Assert.False(resultSet..iterator().MoveNext()); } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestConnectNodesAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1072,11 +1093,12 @@ public async Task TestConnectNodesAsync() // Assert.NotNull(stats.getstringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); Assert.NotNull(stats.QueryInternalExecutionTime); - Assert.Equal(0, resultSet.Count); + Assert.Empty(resultSet); // Assert.False(resultSet.GetEnumerator().MoveNext()); } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestDeleteNodesAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1099,7 +1121,7 @@ public async Task TestDeleteNodesAsync() Assert.Equal(0, delStats.PropertiesSet); // Assert.NotNull(delStats.getstringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); Assert.NotNull(delStats.QueryInternalExecutionTime); - Assert.Equal(0, deleteResult.Count); + Assert.Empty(deleteResult); // Assert.False(deleteResult.iterator().MoveNext()); Assert.NotNull(await graph.QueryAsync("social", "CREATE (:person{name:'roi',age:32})")); @@ -1119,11 +1141,12 @@ public async Task TestDeleteNodesAsync() Assert.Equal(0, delStats.PropertiesSet); // Assert.NotNull(delStats.getstringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); Assert.NotNull(delStats.QueryInternalExecutionTime); - Assert.Equal(0, deleteResult.Count); + Assert.Empty(deleteResult); // Assert.False(deleteResult.iterator().MoveNext()); } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestDeleteRelationshipAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1149,11 +1172,12 @@ public async Task TestDeleteRelationshipAsync() Assert.Equal(0, delStats.PropertiesSet); // Assert.NotNull(delStats.getstringValue(Label.QUERY_INTERNAL_EXECUTION_TIME)); Assert.NotNull(delStats.QueryInternalExecutionTime); - Assert.Equal(0, deleteResult.Count); + Assert.Empty(deleteResult); // Assert.False(deleteResult.iterator().MoveNext()); } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestIndexAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1181,6 +1205,7 @@ public async Task TestIndexAsync() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestHeaderAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1194,7 +1219,7 @@ public async Task TestHeaderAsync() ResultSet queryResult = await graph.QueryAsync("social", "MATCH (a:person)-[r:knows]->(b:person) RETURN a,r, a.age"); - Header header = queryResult.Header; + Header header = queryResult.Header!; Assert.NotNull(header); Assert.Equal("Header{" // + "schemaTypes=[COLUMN_SCALAR, COLUMN_SCALAR, COLUMN_SCALAR], " @@ -1212,6 +1237,7 @@ public async Task TestHeaderAsync() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestRecordAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1286,7 +1312,7 @@ await graph.QueryAsync("social", "MATCH (a:person), (b:person) WHERE (a.name = ' Assert.NotNull(stats.QueryInternalExecutionTime); Assert.NotEmpty(stats.QueryInternalExecutionTime); - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); // IReadOnlyCollection iterator = resultSet.GetEnumerator(); var iterator = resultSet.GetEnumerator(); Assert.True(iterator.MoveNext()); @@ -1339,6 +1365,7 @@ await graph.QueryAsync("social", "MATCH (a:person), (b:person) WHERE (a.name = ' } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestAdditionToProceduresAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1369,13 +1396,13 @@ public async Task TestAdditionToProceduresAsync() ResultSet resultSet = await graph.QueryAsync("social", "MATCH (a:person)-[r:knows]->(b:person) RETURN a,r"); Assert.NotNull(resultSet.Header); - Header header = resultSet.Header; + Header header = resultSet.Header!; List schemaNames = header.SchemaNames; Assert.NotNull(schemaNames); Assert.Equal(2, schemaNames.Count); Assert.Equal("a", schemaNames[0]); Assert.Equal("r", schemaNames[1]); - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); var iterator = resultSet.GetEnumerator(); Assert.True(iterator.MoveNext()); var record = iterator.Current; @@ -1402,13 +1429,13 @@ public async Task TestAdditionToProceduresAsync() "MATCH (a:worker), (b:worker) WHERE (a.lastName = 'a' AND b.lastName='b') CREATE (a)-[:worksWith]->(b)")); resultSet = await graph.QueryAsync("social", "MATCH (a:worker)-[r:worksWith]->(b:worker) RETURN a,r"); Assert.NotNull(resultSet.Header); - header = resultSet.Header; + header = resultSet.Header!; schemaNames = header.SchemaNames; Assert.NotNull(schemaNames); Assert.Equal(2, schemaNames.Count); Assert.Equal("a", schemaNames[0]); Assert.Equal("r", schemaNames[1]); - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); iterator = resultSet.GetEnumerator(); Assert.True(iterator.MoveNext()); record = iterator.Current; @@ -1419,6 +1446,7 @@ record = iterator.Current; } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestEscapedQueryAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1438,6 +1466,7 @@ public async Task TestEscapedQueryAsync() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestArraySupportAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1473,15 +1502,15 @@ public async Task TestArraySupportAsync() // check header Assert.NotNull(resultSet.Header); - Header header = resultSet.Header; + Header header = resultSet.Header!; List schemaNames = header.SchemaNames; Assert.NotNull(schemaNames); - Assert.Equal(1, schemaNames.Count); + Assert.Single(schemaNames); Assert.Equal("x", schemaNames[0]); // check record - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); var iterator = resultSet.GetEnumerator(); Assert.True(iterator.MoveNext()); NRedisStack.Graph.Record record = iterator.Current; @@ -1495,15 +1524,15 @@ public async Task TestArraySupportAsync() resultSet = await graph.QueryAsync("social", "MATCH(n) return collect(n) as x"); Assert.NotNull(resultSet.Header); - header = resultSet.Header; + header = resultSet.Header!; schemaNames = header.SchemaNames; Assert.NotNull(schemaNames); - Assert.Equal(1, schemaNames.Count); + Assert.Single(schemaNames); Assert.Equal("x", schemaNames[0]); // check record - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); iterator = resultSet.GetEnumerator(); Assert.True(iterator.MoveNext()); record = iterator.Current; @@ -1518,11 +1547,11 @@ record = iterator.Current; resultSet = await graph.QueryAsync("social", "unwind([0,1,2]) as x return x"); Assert.NotNull(resultSet.Header); - header = resultSet.Header; + header = resultSet.Header!; schemaNames = header.SchemaNames; Assert.NotNull(schemaNames); - Assert.Equal(1, schemaNames.Count); + Assert.Single(schemaNames); Assert.Equal("x", schemaNames[0]); // check record @@ -1538,6 +1567,7 @@ record = iterator.Current; } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestPathAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1590,6 +1620,7 @@ public async Task TestPathAsync() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestNullGraphEntitiesAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1599,12 +1630,12 @@ public async Task TestNullGraphEntitiesAsync() Assert.NotNull(await graph.QueryAsync("social", "CREATE (:L)-[:E]->(:L2)")); // Test a query that produces 1 record with 3 null values. ResultSet resultSet = await graph.QueryAsync("social", "OPTIONAL MATCH (a:NONEXISTENT)-[e]->(b) RETURN a, e, b"); - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); IEnumerator iterator = resultSet.GetEnumerator(); Assert.True(iterator.MoveNext()); NRedisStack.Graph.Record record = iterator.Current; Assert.False(iterator.MoveNext()); - Assert.Equal(new List() { null, null, null }, record.Values); + Assert.Equal(new List() { null!, null!, null! }, record.Values); // Test a query that produces 2 records, with 2 null values in the second. resultSet = await graph.QueryAsync("social", "MATCH (a) OPTIONAL MATCH (a)-[e]->(b) RETURN a, e, b ORDER BY ID(a)"); @@ -1644,6 +1675,7 @@ record = resultSet.Skip(1).First(); } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task Test64bitnumberAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1653,7 +1685,7 @@ public async Task Test64bitnumberAsync() Dictionary parameters = new Dictionary(); parameters.Add("val", value); ResultSet resultSet = await graph.QueryAsync("social", "CREATE (n {val:$val}) RETURN n.val", parameters); - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); // NRedisStack.Graph.Record r = resultSet.GetEnumerator().Current; // Assert.Equal(value, r.Values[0]); @@ -1662,6 +1694,7 @@ public async Task Test64bitnumberAsync() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestCachedExecutionAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1673,7 +1706,7 @@ public async Task TestCachedExecutionAsync() Dictionary parameters = new Dictionary(); parameters.Add("val", 1L); ResultSet resultSet = await graph.QueryAsync("social", "MATCH (n:N {val:$val}) RETURN n.val", parameters); - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); // NRedisStack.Graph.Record r = resultSet.GetEnumerator().Current; Assert.Equal(parameters["val"], resultSet.First().Values[0]); Assert.False(resultSet.Statistics.CachedExecution); @@ -1684,7 +1717,7 @@ public async Task TestCachedExecutionAsync() { resultSet = await graph.QueryAsync("social", "MATCH (n:N {val:$val}) RETURN n.val", parameters); } - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); // r = resultSet.GetEnumerator().Current; // Assert.Equal(parameters["val"], r.Values[0]); Assert.Equal(parameters["val"], resultSet.First().Values[0]); @@ -1693,15 +1726,18 @@ public async Task TestCachedExecutionAsync() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestMapDataTypeAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); db.Execute("FLUSHALL"); var graph = db.GRAPH(); - Dictionary expected = new Dictionary(); - expected.Add("a", (long)1); - expected.Add("b", "str"); - expected.Add("c", null); + Dictionary expected = new Dictionary + { + { "a", (long)1 }, + { "b", "str" }, + { "c", null! } + }; List d = new List(); d.Add((long)1); d.Add((long)2); @@ -1713,7 +1749,7 @@ public async Task TestMapDataTypeAsync() f.Add("y", (long)2); expected.Add("f", f); ResultSet res = await graph.QueryAsync("social", "RETURN {a:1, b:'str', c:NULL, d:[1,2,3], e:True, f:{x:1, y:2}}"); - Assert.Equal(1, res.Count); + Assert.Single(res); var iterator = res.GetEnumerator(); iterator.MoveNext(); @@ -1723,6 +1759,7 @@ public async Task TestMapDataTypeAsync() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestGeoPointLatLonAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1737,6 +1774,7 @@ public async Task TestGeoPointLatLonAsync() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestGeoPointLonLatAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1750,10 +1788,11 @@ public async Task TestGeoPointLonLatAsync() AssertTestGeoPoint(graph); } + [Obsolete] private async Task AssertTestGeoPointAsync(GraphCommands graph) { ResultSet results = await graph.QueryAsync("social", "MATCH (restaurant) RETURN restaurant"); - Assert.Equal(1, results.Count); + Assert.Single(results); var record = results.GetEnumerator(); record.MoveNext(); Assert.Equal(1, record.Current.Size); @@ -1765,20 +1804,22 @@ private async Task AssertTestGeoPointAsync(GraphCommands graph) } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task timeoutArgumentAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); db.Execute("FLUSHALL"); var graph = db.GRAPH(); ResultSet rs = await graph.QueryAsync("social", "UNWIND range(0,100) AS x WITH x AS x WHERE x = 100 RETURN x", 1L); - Assert.Equal(1, rs.Count); + Assert.Single(rs); var iterator = rs.GetEnumerator(); iterator.MoveNext(); var r = iterator.Current; - Assert.Equal(100l, (long)r.Values[0]); + Assert.Equal(100, (long)r.Values[0]); } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestCachedExecutionReadOnlyAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1790,7 +1831,7 @@ public async Task TestCachedExecutionReadOnlyAsync() Dictionary parameters = new Dictionary(); parameters.Add("val", 1L); ResultSet resultSet = await graph.RO_QueryAsync("social", "MATCH (n:N {val:$val}) RETURN n.val", parameters); - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); var iterator = resultSet.GetEnumerator(); iterator.MoveNext(); NRedisStack.Graph.Record r = iterator.Current; @@ -1803,7 +1844,7 @@ public async Task TestCachedExecutionReadOnlyAsync() { resultSet = await graph.RO_QueryAsync("social", "MATCH (n:N {val:$val}) RETURN n.val", parameters); } - Assert.Equal(1, resultSet.Count); + Assert.Single(resultSet); iterator = resultSet.GetEnumerator(); iterator.MoveNext(); r = iterator.Current; @@ -1812,6 +1853,7 @@ public async Task TestCachedExecutionReadOnlyAsync() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestSimpleReadOnlyAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1819,7 +1861,7 @@ public async Task TestSimpleReadOnlyAsync() var graph = db.GRAPH(); await graph.QueryAsync("social", "CREATE (:person{name:'filipe',age:30})"); ResultSet rsRo = await graph.RO_QueryAsync("social", "MATCH (a:person) WHERE (a.name = 'filipe') RETURN a.age"); - Assert.Equal(1, rsRo.Count); + Assert.Single(rsRo); var iterator = rsRo.GetEnumerator(); iterator.MoveNext(); var r = iterator.Current; @@ -1827,6 +1869,7 @@ public async Task TestSimpleReadOnlyAsync() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestProfileAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1845,6 +1888,7 @@ public async Task TestProfileAsync() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestExplainAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1863,6 +1907,7 @@ public async Task TestExplainAsync() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestSlowlogAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1878,6 +1923,7 @@ public async Task TestSlowlogAsync() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestListAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1891,6 +1937,7 @@ public async Task TestListAsync() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestConfigAsync() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1904,25 +1951,14 @@ public async Task TestConfigAsync() Assert.True(await graph.ConfigSetAsync(name, 250L)); var actual = await graph.ConfigGetAsync(name); - Assert.Equal(actual.Count, 1); + Assert.Single(actual); Assert.Equal("250", actual[name].ToString()); - await graph.ConfigSetAsync(name, existingValue != null ? existingValue.ToString() : -1); - } - - [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] - public async Task TestModulePrefixsAsync() - { - IDatabase db1 = redisFixture.Redis.GetDatabase(); - IDatabase db2 = redisFixture.Redis.GetDatabase(); - - var graph1 = db1.GRAPH(); - var graph2 = db2.GRAPH(); - - Assert.NotEqual(graph1.GetHashCode(), graph2.GetHashCode()); + await graph.ConfigSetAsync(name, existingValue != null ? existingValue.ToString()! : -1); } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestCallProcedureDbLabelsAsync() { var db = redisFixture.Redis.GetDatabase(); @@ -1944,6 +1980,7 @@ public async Task TestCallProcedureDbLabelsAsync() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestCallProcedureReadOnlyAsync() { var db = redisFixture.Redis.GetDatabase(); @@ -1966,13 +2003,14 @@ public async Task TestCallProcedureReadOnlyAsync() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestParseInfinity() { IDatabase db = redisFixture.Redis.GetDatabase(); db.Execute("FLUSHALL"); var graph = db.GRAPH(); ResultSet rs = graph.Query("db", "RETURN 10^100000"); - Assert.Equal(1, rs.Count()); + Assert.Single(rs); var iterator = rs.GetEnumerator(); iterator.MoveNext(); var r = iterator.Current; @@ -1980,6 +2018,7 @@ public void TestParseInfinity() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestEqualsAndToString() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -1994,7 +2033,7 @@ public void TestEqualsAndToString() Assert.True(iterator2.MoveNext()); var record2 = iterator2.Current; - Assert.True(resultSet1.Header.Equals(resultSet1.Header)); + Assert.True(resultSet1.Header!.Equals(resultSet1.Header)); Assert.False(resultSet1.Header.Equals(resultSet2.Header)); Assert.False(resultSet1.Header.Equals(new object())); Assert.False(resultSet1.Header.Equals(null)); @@ -2031,22 +2070,22 @@ public void TestEqualsAndToString() - var path = new NRedisStack.Graph.DataTypes.Path(new List() { node1, node2 }, - new List() { edge1, edge2 }); - var pathCopy = new NRedisStack.Graph.DataTypes.Path(new List() { node1, node2 }, - new List() { edge1, edge2 }); - var path2 = new NRedisStack.Graph.DataTypes.Path(new List() { node1, node2 }, - new List() { edge1 }); + var path = new NRedisStack.Graph.DataTypes.Path(new List() { node1!, node2 }, + new List() { edge1!, edge2 }); + var pathCopy = new NRedisStack.Graph.DataTypes.Path(new List() { node1!, node2 }, + new List() { edge1!, edge2 }); + var path2 = new NRedisStack.Graph.DataTypes.Path(new List() { node1!, node2 }, + new List() { edge1! }); Assert.True(path.Equals(pathCopy)); Assert.True(path.Equals(path)); Assert.False(path.Equals(path2)); Assert.False(path.Equals(node1)); - Assert.True(record1.ToString() == "Record{values=Infinity}" || record1.ToString() == "Record{values=∞}"); + Assert.True(record1!.ToString() == "Record{values=Infinity}" || record1.ToString() == "Record{values=∞}"); Assert.NotEqual(record2.GetHashCode(), record1.GetHashCode()); - var node1String = node1.ToString(); - var edge1String = edge1.ToString(); + var node1String = node1!.ToString(); + var edge1String = edge1!.ToString(); var pathString = path.ToString(); var expectedNode1String = "Node{labels=[], id=1, propertyMap={}}"; var expectedEdge1String = "Edge{relationshipType='', source=0, destination=0, id=1, propertyMap={}}"; @@ -2057,6 +2096,7 @@ public void TestEqualsAndToString() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public void TestPrepareQuery() { const string return1Query = "RETURN 1"; @@ -2073,7 +2113,7 @@ public void TestPrepareQuery() Assert.Equal(return1QueryRecordString, res1.Single().ToString()); // handle null - var buildCommand2 = GraphCommandBuilder.Query("graph", return1Query, new Dictionary { { "a", null } }); + var buildCommand2 = GraphCommandBuilder.Query("graph", return1Query, new Dictionary { { "a", null! } }); var expectedPreparedQuery2 = $"CYPHER a=null {return1Query}"; Assert.Equal(expectedPreparedQuery2, buildCommand2.Args[1].ToString()!); var res2 = graph.Query("graph", buildCommand2.Args[1].ToString()!); diff --git a/tests/NRedisStack.Tests/Graph/Utils/PathBuilderTest.cs b/tests/NRedisStack.Tests/Graph/Utils/PathBuilderTest.cs index 8dd7a921..7d30e546 100644 --- a/tests/NRedisStack.Tests/Graph/Utils/PathBuilderTest.cs +++ b/tests/NRedisStack.Tests/Graph/Utils/PathBuilderTest.cs @@ -8,7 +8,7 @@ public class PathBuilderTest [Fact] public void TestPathBuilderSizeException() { - var thrownException = Assert.Throws(()=> + var thrownException = Assert.Throws(() => { var pathBuilder = new PathBuilder(0); diff --git a/tests/NRedisStack.Tests/Json/JsonTests.cs b/tests/NRedisStack.Tests/Json/JsonTests.cs index 94ee6afe..36b8fa3a 100644 --- a/tests/NRedisStack.Tests/Json/JsonTests.cs +++ b/tests/NRedisStack.Tests/Json/JsonTests.cs @@ -9,14 +9,9 @@ namespace NRedisStack.Tests; public class JsonTests : AbstractNRedisStackTest, IDisposable { - private readonly string _testName = "JSON_TESTS"; + // private readonly string _testName = "JSON_TESTS"; public JsonTests(RedisFixture redisFixture) : base(redisFixture) { } - public void Dispose() - { - redisFixture.Redis.GetDatabase().KeyDelete(_testName); - } - [Fact] public void TestSetFromFile() { @@ -775,12 +770,12 @@ public void Merge() // Create a connection to Redis var commands = new JsonCommands(redisFixture.Redis.GetDatabase()); - Assert.True(commands.Set("test_merge", "$", new { person = new { name = "John Doe", age = 25, address = new {home = "123 Main Street"}, phone = "123-456-7890" } })); + Assert.True(commands.Set("test_merge", "$", new { person = new { name = "John Doe", age = 25, address = new { home = "123 Main Street" }, phone = "123-456-7890" } })); Assert.True(commands.Merge("test_merge", "$", new { person = new { age = 30 } })); Assert.Equal("{\"person\":{\"name\":\"John Doe\",\"age\":30,\"address\":{\"home\":\"123 Main Street\"},\"phone\":\"123-456-7890\"}}", commands.Get("test_merge").ToString()); // Test with root path path $.a.b - Assert.True(commands.Merge("test_merge", "$.person.address", new {work = "Redis office"})); + Assert.True(commands.Merge("test_merge", "$.person.address", new { work = "Redis office" })); Assert.Equal("{\"person\":{\"name\":\"John Doe\",\"age\":30,\"address\":{\"home\":\"123 Main Street\",\"work\":\"Redis office\"},\"phone\":\"123-456-7890\"}}", commands.Get("test_merge").ToString()); // Test with null value to delete a value @@ -794,12 +789,12 @@ public async Task MergeAsync() // Create a connection to Redis var commands = new JsonCommands(redisFixture.Redis.GetDatabase()); - Assert.True(await commands.SetAsync("test_merge", "$", new { person = new { name = "John Doe", age = 25, address = new {home = "123 Main Street"}, phone = "123-456-7890" } })); + Assert.True(await commands.SetAsync("test_merge", "$", new { person = new { name = "John Doe", age = 25, address = new { home = "123 Main Street" }, phone = "123-456-7890" } })); Assert.True(await commands.MergeAsync("test_merge", "$", new { person = new { age = 30 } })); Assert.Equal("{\"person\":{\"name\":\"John Doe\",\"age\":30,\"address\":{\"home\":\"123 Main Street\"},\"phone\":\"123-456-7890\"}}", (await commands.GetAsync("test_merge")).ToString()); // Test with root path path $.a.b - Assert.True(await commands.MergeAsync("test_merge", "$.person.address", new {work = "Redis office"})); + Assert.True(await commands.MergeAsync("test_merge", "$.person.address", new { work = "Redis office" })); Assert.Equal("{\"person\":{\"name\":\"John Doe\",\"age\":30,\"address\":{\"home\":\"123 Main Street\",\"work\":\"Redis office\"},\"phone\":\"123-456-7890\"}}", (await commands.GetAsync("test_merge")).ToString()); // Test with null value to delete a value @@ -939,8 +934,8 @@ public void TestMultiPathGet() var key = keys[0]; commands.Set(key, "$", new { a = "hello", b = new { a = "world" } }); var res = commands.Get(key, new[] { "$..a", "$.b" }).ToString(); - var obj = JsonSerializer.Deserialize(res); - Assert.True(obj.ContainsKey("$..a")); + var obj = JsonSerializer.Deserialize(res!); + Assert.True(obj!.ContainsKey("$..a")); Assert.True(obj.ContainsKey("$.b")); if (obj["$..a"] is JsonArray arr) { @@ -963,8 +958,8 @@ public async Task TestMultiPathGetAsync() var key = keys[0]; await commands.SetAsync(key, "$", new { a = "hello", b = new { a = "world" } }); var res = (await commands.GetAsync(key, new[] { "$..a", "$.b" })).ToString(); - var obj = JsonSerializer.Deserialize(res); - Assert.True(obj.ContainsKey("$..a")); + var obj = JsonSerializer.Deserialize(res!); + Assert.True(obj!.ContainsKey("$..a")); Assert.True(obj.ContainsKey("$.b")); if (obj["$..a"] is JsonArray arr) { diff --git a/tests/NRedisStack.Tests/Person.cs b/tests/NRedisStack.Tests/Person.cs index 6859401b..fc217a05 100644 --- a/tests/NRedisStack.Tests/Person.cs +++ b/tests/NRedisStack.Tests/Person.cs @@ -2,7 +2,7 @@ namespace NRedisStack.Tests { public class Person { - public string Name { get; set; } + public string? Name { get; set; } public int Age { get; set; } } } \ No newline at end of file diff --git a/tests/NRedisStack.Tests/PipelineTests.cs b/tests/NRedisStack.Tests/PipelineTests.cs index f6285371..747f1ba1 100644 --- a/tests/NRedisStack.Tests/PipelineTests.cs +++ b/tests/NRedisStack.Tests/PipelineTests.cs @@ -12,29 +12,30 @@ public class PipelineTests : AbstractNRedisStackTest, IDisposable public PipelineTests(RedisFixture redisFixture) : base(redisFixture) { } [SkipIfRedis(Is.OSSCluster, Comparison.GreaterThanOrEqual, "7.1.242")] - public async Task TestModulsPipeline() + [Obsolete] + public void TestModulsPipeline() { IDatabase db = redisFixture.Redis.GetDatabase(); db.Execute("FLUSHALL"); var pipeline = new Pipeline(db); - pipeline.Bf.ReserveAsync("bf-key", 0.001, 100); - pipeline.Bf.AddAsync("bf-key", "1"); - pipeline.Cms.InitByDimAsync("cms-key", 100, 5); - pipeline.Cf.ReserveAsync("cf-key", 100); - pipeline.Graph.QueryAsync("graph-key", "CREATE ({name:'shachar',age:23})"); - pipeline.Json.SetAsync("json-key", "$", "{}"); - pipeline.Ft.CreateAsync("ft-key", new FTCreateParams(), new Schema().AddTextField("txt")); - pipeline.Tdigest.CreateAsync("tdigest-key", 100); - pipeline.Ts.CreateAsync("ts-key", 100); - pipeline.TopK.ReserveAsync("topk-key", 100, 100, 100); + _ = pipeline.Bf.ReserveAsync("bf-key", 0.001, 100); + _ = pipeline.Bf.AddAsync("bf-key", "1"); + _ = pipeline.Cms.InitByDimAsync("cms-key", 100, 5); + _ = pipeline.Cf.ReserveAsync("cf-key", 100); + _ = pipeline.Graph.QueryAsync("graph-key", "CREATE ({name:'shachar',age:23})"); + _ = pipeline.Json.SetAsync("json-key", "$", "{}"); + _ = pipeline.Ft.CreateAsync("ft-key", new FTCreateParams(), new Schema().AddTextField("txt")); + _ = pipeline.Tdigest.CreateAsync("tdigest-key", 100); + _ = pipeline.Ts.CreateAsync("ts-key", 100); + _ = pipeline.TopK.ReserveAsync("topk-key", 100, 100, 100); Assert.False(db.KeyExists("bf-key")); Assert.False(db.KeyExists("cms-key")); Assert.False(db.KeyExists("cf-key")); Assert.False(db.KeyExists("graph-key")); Assert.False(db.KeyExists("json-key")); - Assert.Equal(0, db.FT()._List().Length); + Assert.Empty(db.FT()._List()); Assert.False(db.KeyExists("tdigest-key")); Assert.False(db.KeyExists("ts-key")); Assert.False(db.KeyExists("topk-key")); @@ -46,13 +47,13 @@ public async Task TestModulsPipeline() Assert.True(db.KeyExists("cf-key")); Assert.True(db.KeyExists("graph-key")); Assert.True(db.KeyExists("json-key")); - Assert.True(db.FT()._List().Length == 1); + Assert.Single(db.FT()._List()); Assert.True(db.KeyExists("tdigest-key")); Assert.True(db.KeyExists("ts-key")); Assert.True(db.KeyExists("topk-key")); Assert.True(db.BF().Exists("bf-key", "1")); - Assert.True(db.CMS().Info("cms-key").Width == 100); + Assert.Equal(100, db.CMS().Info("cms-key").Width); Assert.True(db.CF().Info("cf-key").Size > 0); Assert.True(db.GRAPH().List().Count > 0); Assert.False(db.JSON().Get("json-key").IsNull); @@ -63,27 +64,28 @@ public async Task TestModulsPipeline() } [SkipIfRedis(Is.OSSCluster)] - public async Task TestModulsPipelineWithotGraph() + [Obsolete] + public void TestModulsPipelineWithotGraph() { IDatabase db = redisFixture.Redis.GetDatabase(); db.Execute("FLUSHALL"); var pipeline = new Pipeline(db); - pipeline.Bf.ReserveAsync("bf-key", 0.001, 100); - pipeline.Bf.AddAsync("bf-key", "1"); - pipeline.Cms.InitByDimAsync("cms-key", 100, 5); - pipeline.Cf.ReserveAsync("cf-key", 100); - pipeline.Json.SetAsync("json-key", "$", "{}"); - pipeline.Ft.CreateAsync("ft-key", new FTCreateParams(), new Schema().AddTextField("txt")); - pipeline.Tdigest.CreateAsync("tdigest-key", 100); - pipeline.Ts.CreateAsync("ts-key", 100); - pipeline.TopK.ReserveAsync("topk-key", 100, 100, 100); + _ = pipeline.Bf.ReserveAsync("bf-key", 0.001, 100); + _ = pipeline.Bf.AddAsync("bf-key", "1"); + _ = pipeline.Cms.InitByDimAsync("cms-key", 100, 5); + _ = pipeline.Cf.ReserveAsync("cf-key", 100); + _ = pipeline.Json.SetAsync("json-key", "$", "{}"); + _ = pipeline.Ft.CreateAsync("ft-key", new FTCreateParams(), new Schema().AddTextField("txt")); + _ = pipeline.Tdigest.CreateAsync("tdigest-key", 100); + _ = pipeline.Ts.CreateAsync("ts-key", 100); + _ = pipeline.TopK.ReserveAsync("topk-key", 100, 100, 100); Assert.False(db.KeyExists("bf-key")); Assert.False(db.KeyExists("cms-key")); Assert.False(db.KeyExists("cf-key")); Assert.False(db.KeyExists("json-key")); - Assert.Equal(0, db.FT()._List().Length); + Assert.Empty(db.FT()._List()); Assert.False(db.KeyExists("tdigest-key")); Assert.False(db.KeyExists("ts-key")); Assert.False(db.KeyExists("topk-key")); @@ -94,13 +96,13 @@ public async Task TestModulsPipelineWithotGraph() Assert.True(db.KeyExists("cms-key")); Assert.True(db.KeyExists("cf-key")); Assert.True(db.KeyExists("json-key")); - Assert.True(db.FT()._List().Length == 1); + Assert.Single(db.FT()._List()); Assert.True(db.KeyExists("tdigest-key")); Assert.True(db.KeyExists("ts-key")); Assert.True(db.KeyExists("topk-key")); Assert.True(db.BF().Exists("bf-key", "1")); - Assert.True(db.CMS().Info("cms-key").Width == 100); + Assert.Equal(100, db.CMS().Info("cms-key").Width); Assert.True(db.CF().Info("cf-key").Size > 0); Assert.False(db.JSON().Get("json-key").IsNull); Assert.NotNull(db.FT().Info("ft-key")); @@ -110,40 +112,40 @@ public async Task TestModulsPipelineWithotGraph() } [SkipIfRedis(Is.OSSCluster)] - public async Task TestBloomPipeline() + public void TestBloomPipeline() { IDatabase db = redisFixture.Redis.GetDatabase(); db.Execute("FLUSHALL"); var pipeline = new Pipeline(db); - pipeline.Bf.ReserveAsync(key, 0.001, 100); - for(int i = 0; i < 1000; i++) + _ = pipeline.Bf.ReserveAsync(key, 0.001, 100); + for (int i = 0; i < 1000; i++) { - pipeline.Bf.AddAsync(key, i.ToString()); + _ = pipeline.Bf.AddAsync(key, i.ToString()); } - for(int i = 0; i < 100; i++) + for (int i = 0; i < 100; i++) { Assert.False(db.BF().Exists(key, i.ToString())); } pipeline.Execute(); - for(int i = 0; i < 1000; i++) + for (int i = 0; i < 1000; i++) { Assert.True(db.BF().Exists(key, i.ToString())); } } [Fact] - public async Task TestJsonPipeline() + public void TestJsonPipeline() { IDatabase db = redisFixture.Redis.GetDatabase(); var pipeline = new Pipeline(db); pipeline.Db.ExecuteAsync("FLUSHALL"); string jsonPerson = JsonSerializer.Serialize(new Person { Name = "Shachar", Age = 23 }); - pipeline.Json.SetAsync("key", "$", jsonPerson); + _ = pipeline.Json.SetAsync("key", "$", jsonPerson); // var setResponse = pipeline.Json.SetAsync("key", "$", jsonPerson); var getResponse = pipeline.Json.GetAsync("key"); diff --git a/tests/NRedisStack.Tests/RedisFixture.cs b/tests/NRedisStack.Tests/RedisFixture.cs index 98ea4689..aca9ba67 100644 --- a/tests/NRedisStack.Tests/RedisFixture.cs +++ b/tests/NRedisStack.Tests/RedisFixture.cs @@ -34,6 +34,7 @@ public RedisFixture() { EndPoints = endpoints }; + isOSSCluster = true; Redis = ConnectionMultiplexer.Connect(clusterConfig); } diff --git a/tests/NRedisStack.Tests/Search/SearchTests.cs b/tests/NRedisStack.Tests/Search/SearchTests.cs index bb769b2e..2a4ecbe3 100644 --- a/tests/NRedisStack.Tests/Search/SearchTests.cs +++ b/tests/NRedisStack.Tests/Search/SearchTests.cs @@ -170,7 +170,6 @@ public void TestAggregations() Assert.Equal(2, res.TotalResults); Row r1 = res.GetRow(0); - Assert.NotNull(r1); Assert.Equal("def", r1.GetString("name")); Assert.Equal(30, r1.GetLong("sum")); Assert.Equal(30, r1.GetDouble("sum"), 0); @@ -180,7 +179,6 @@ public void TestAggregations() Assert.Null(r1.GetString("nosuchcol")); Row r2 = res.GetRow(1); - Assert.NotNull(r2); Assert.Equal("abc", r2.GetString("name")); Assert.Equal(10, r2.GetLong("sum")); } @@ -211,7 +209,6 @@ public async Task TestAggregationsAsync() Assert.Equal(2, res.TotalResults); Row r1 = res.GetRow(0); - Assert.NotNull(r1); Assert.Equal("def", r1.GetString("name")); Assert.Equal(30, r1.GetLong("sum")); Assert.Equal(30, r1.GetDouble("sum"), 0); @@ -221,7 +218,6 @@ public async Task TestAggregationsAsync() Assert.Null(r1.GetString("nosuchcol")); Row r2 = res.GetRow(1); - Assert.NotNull(r2); Assert.Equal("abc", r2.GetString("name")); Assert.Equal(10, r2.GetLong("sum")); } @@ -241,18 +237,18 @@ public void TestAggregationsLoad() // load t1 var req = new AggregationRequest("*").Load(new FieldName("t1")); var res = ft.Aggregate("idx", req); - Assert.Equal(res[0]["t1"].ToString(), "hello"); + Assert.Equal("hello", res[0]!["t1"].ToString()); // load t2 req = new AggregationRequest("*").Load(new FieldName("t2")); res = ft.Aggregate("idx", req); - Assert.Equal(res[0]["t2"], "world"); + Assert.Equal("world", res[0]!["t2"]); // load all req = new AggregationRequest("*").LoadAll(); res = ft.Aggregate("idx", req); - Assert.Equal(res[0]["t1"].ToString(), "hello"); - Assert.Equal(res[0]["t2"], "world"); + Assert.Equal("hello", res[0]!["t1"].ToString()); + Assert.Equal("world", res[0]!["t2"]); } [SkipIfRedis(Is.OSSCluster)] @@ -269,18 +265,18 @@ public async Task TestAggregationsLoadAsync() // load t1 var req = new AggregationRequest("*").Load(new FieldName("t1")); var res = await ft.AggregateAsync("idx", req); - Assert.Equal(res[0]["t1"].ToString(), "hello"); + Assert.Equal("hello", res[0]!["t1"].ToString()); // load t2 req = new AggregationRequest("*").Load(new FieldName("t2")); res = await ft.AggregateAsync("idx", req); - Assert.Equal(res[0]["t2"], "world"); + Assert.Equal("world", res[0]!["t2"]); // load all req = new AggregationRequest("*").LoadAll(); res = await ft.AggregateAsync("idx", req); - Assert.Equal(res[0]["t1"].ToString(), "hello"); - Assert.Equal(res[0]["t2"], "world"); + Assert.Equal("hello", res[0]!["t1"].ToString()); + Assert.Equal("world", res[0]!["t2"]); } @@ -312,7 +308,6 @@ public void TestAggregationRequestParamsDialect() Assert.Equal(1, res.TotalResults); Row r1 = res.GetRow(0); - Assert.NotNull(r1); Assert.Equal("abc", r1.GetString("name")); Assert.Equal(10, r1.GetLong("sum")); } @@ -348,7 +343,6 @@ public async Task TestAggregationRequestParamsDialectAsync() Assert.Equal(1, res.TotalResults); Row r1 = res.GetRow(0); - Assert.NotNull(r1); Assert.Equal("abc", r1.GetString("name")); Assert.Equal(10, r1.GetLong("sum")); } @@ -380,7 +374,6 @@ public void TestAggregationRequestParamsWithDefaultDialect() Assert.Equal(1, res.TotalResults); Row r1 = res.GetRow(0); - Assert.NotNull(r1); Assert.Equal("abc", r1.GetString("name")); Assert.Equal(10, r1.GetLong("sum")); } @@ -412,7 +405,6 @@ public async Task TestAggregationRequestParamsWithDefaultDialectAsync() Assert.Equal(1, res.TotalResults); Row r1 = res.GetRow(0); - Assert.NotNull(r1); Assert.Equal("abc", r1.GetString("name")); Assert.Equal(10, r1.GetLong("sum")); } @@ -518,12 +510,10 @@ public void TestApplyAndFilterAggregations() Assert.Equal(3, res.TotalResults); Row r1 = res.GetRow(0); - Assert.NotNull(r1); Assert.Equal("def", r1.GetString("name")); Assert.Equal(52.5, r1.GetDouble("avgscore"), 0); Row r2 = res.GetRow(1); - Assert.NotNull(r2); Assert.Equal("ghi", r2.GetString("name")); Assert.Equal(67.5, r2.GetDouble("avgscore"), 0); } @@ -741,7 +731,7 @@ public void AlterAdd() var info = ft.Info(index); Assert.Equal(index, info.IndexName); - Assert.Equal(0, info.IndexOption.Count); + Assert.Empty(info.IndexOption); // Assert.Equal(,info.IndexDefinition); Assert.Equal("title", (info.Attributes[0]["identifier"]).ToString()); Assert.Equal("TAG", (info.Attributes[1]["type"]).ToString()); @@ -1083,68 +1073,68 @@ public void TestAggregationGroupBy() var req = new AggregationRequest("redis").GroupBy("@parent", Reducers.Count()); var res = ft.Aggregate("idx", req).GetRow(0); Assert.True(res.ContainsKey("parent")); - Assert.Equal(res["parent"], "redis"); + Assert.Equal("redis", res["parent"]); // Assert.Equal(res["__generated_aliascount"], "3"); req = new AggregationRequest("redis").GroupBy("@parent", Reducers.CountDistinct("@title")); res = ft.Aggregate("idx", req).GetRow(0); - Assert.Equal(res["parent"], "redis"); - Assert.Equal(res.GetLong("__generated_aliascount_distincttitle"), 3); + Assert.Equal("redis", res["parent"]); + Assert.Equal(3, res.GetLong("__generated_aliascount_distincttitle")); req = new AggregationRequest("redis").GroupBy("@parent", Reducers.CountDistinctish("@title")); res = ft.Aggregate("idx", req).GetRow(0); - Assert.Equal(res["parent"], "redis"); - Assert.Equal(res.GetLong("__generated_aliascount_distinctishtitle"), 3); + Assert.Equal("redis", res["parent"]); + Assert.Equal(3, res.GetLong("__generated_aliascount_distinctishtitle")); req = new AggregationRequest("redis").GroupBy("@parent", Reducers.Sum("@random_num")); res = ft.Aggregate("idx", req).GetRow(0); - Assert.Equal(res["parent"], "redis"); - Assert.Equal(res.GetLong("__generated_aliassumrandom_num"), 21); // 10+8+3 + Assert.Equal("redis", res["parent"]); + Assert.Equal(21, res.GetLong("__generated_aliassumrandom_num")); // 10+8+3 req = new AggregationRequest("redis").GroupBy("@parent", Reducers.Min("@random_num")); res = ft.Aggregate("idx", req).GetRow(0); - Assert.Equal(res["parent"], "redis"); - Assert.Equal(res.GetLong("__generated_aliasminrandom_num"), 3); // min(10,8,3) + Assert.Equal("redis", res["parent"]); + Assert.Equal(3, res.GetLong("__generated_aliasminrandom_num")); // min(10,8,3) req = new AggregationRequest("redis").GroupBy("@parent", Reducers.Max("@random_num")); res = ft.Aggregate("idx", req).GetRow(0); - Assert.Equal(res["parent"], "redis"); - Assert.Equal(res.GetLong("__generated_aliasmaxrandom_num"), 10); // max(10,8,3) + Assert.Equal("redis", res["parent"]); + Assert.Equal(10, res.GetLong("__generated_aliasmaxrandom_num")); // max(10,8,3) req = new AggregationRequest("redis").GroupBy("@parent", Reducers.Avg("@random_num")); res = ft.Aggregate("idx", req).GetRow(0); - Assert.Equal(res["parent"], "redis"); - Assert.Equal(res.GetLong("__generated_aliasavgrandom_num"), 7); // (10+3+8)/3 + Assert.Equal("redis", res["parent"]); + Assert.Equal(7, res.GetLong("__generated_aliasavgrandom_num")); // (10+3+8)/3 req = new AggregationRequest("redis").GroupBy("@parent", Reducers.StdDev("@random_num")); res = ft.Aggregate("idx", req).GetRow(0); - Assert.Equal(res["parent"], "redis"); - Assert.Equal(res.GetDouble("__generated_aliasstddevrandom_num"), 3.60555127546); + Assert.Equal("redis", res["parent"]); + Assert.Equal(3.60555127546, res.GetDouble("__generated_aliasstddevrandom_num")); req = new AggregationRequest("redis").GroupBy( "@parent", Reducers.Quantile("@random_num", 0.5)); res = ft.Aggregate("idx", req).GetRow(0); - Assert.Equal(res["parent"], "redis"); - Assert.Equal(res.GetLong("__generated_aliasquantilerandom_num,0.5"), 8); // median of 3,8,10 + Assert.Equal("redis", res["parent"]); + Assert.Equal(8, res.GetLong("__generated_aliasquantilerandom_num,0.5")); // median of 3,8,10 req = new AggregationRequest("redis").GroupBy( "@parent", Reducers.ToList("@title")); var rawRes = ft.Aggregate("idx", req); res = rawRes.GetRow(0); - Assert.Equal(res["parent"], "redis"); + Assert.Equal("redis", res["parent"]); // TODO: complete this assert after handling multi bulk reply //Assert.Equal((RedisValue[])res["__generated_aliastolisttitle"], { "RediSearch", "RedisAI", "RedisJson"}); req = new AggregationRequest("redis").GroupBy( "@parent", Reducers.FirstValue("@title").As("first")); res = ft.Aggregate("idx", req).GetRow(0); - Assert.Equal(res["parent"], "redis"); - Assert.Equal(res["first"], "RediSearch"); + Assert.Equal("redis", res["parent"]); + Assert.Equal("RediSearch", res["first"]); req = new AggregationRequest("redis").GroupBy( "@parent", Reducers.RandomSample("@title", 2).As("random")); res = ft.Aggregate("idx", req).GetRow(0); - Assert.Equal(res["parent"], "redis"); + Assert.Equal("redis", res["parent"]); // TODO: complete this assert after handling multi bulk reply // Assert.Equal(res[2], "random"); // Assert.Equal(len(res[3]), 2); @@ -1170,7 +1160,7 @@ public void TestDictionary() Assert.Equal("hello world", dumResult[i].ToString()); Assert.Equal(3L, ft.DictDel("dict", "foo", "bar", "hello world")); - Assert.Equal(ft.DictDump("dict").Length, 0); + Assert.Empty(ft.DictDump("dict")); } [SkipIfRedis(Is.OSSCluster)] @@ -1201,7 +1191,7 @@ public void TestDropIndex() } catch (RedisServerException ex) { - Assert.True(ex.Message.Contains("no such index")); + Assert.Contains("no such index", ex.Message); } Assert.Equal("100", db.Execute("DBSIZE").ToString()); } @@ -1234,7 +1224,7 @@ public async Task TestDropIndexAsync() } catch (RedisServerException ex) { - Assert.True(ex.Message.Contains("no such index")); + Assert.Contains("no such index", ex.Message); } Assert.Equal("100", db.Execute("DBSIZE").ToString()); } @@ -1260,8 +1250,8 @@ public void dropIndexDD() Assert.True(ft.DropIndex(index, true)); - RedisResult[] keys = (RedisResult[])db.Execute("KEYS", "*"); - Assert.True(keys.Length == 0); + RedisResult[] keys = (RedisResult[])db.Execute("KEYS", "*")!; + Assert.Empty(keys); Assert.Equal("0", db.Execute("DBSIZE").ToString()); } @@ -1286,8 +1276,8 @@ public async Task dropIndexDDAsync() Assert.True(await ft.DropIndexAsync(index, true)); - RedisResult[] keys = (RedisResult[])db.Execute("KEYS", "*"); - Assert.True(keys.Length == 0); + RedisResult[] keys = (RedisResult[])db.Execute("KEYS", "*")!; + Assert.Empty(keys); Assert.Equal("0", db.Execute("DBSIZE").ToString()); } @@ -1307,7 +1297,7 @@ public async Task TestDictionaryAsync() Assert.Equal("hello world", dumResult[i].ToString()); Assert.Equal(3L, await ft.DictDelAsync("dict", "foo", "bar", "hello world")); - Assert.Equal((await ft.DictDumpAsync("dict")).Length, 0); + Assert.Empty((await ft.DictDumpAsync("dict"))); } string explainQuery = "@f3:f3_val @f2:f2_val @f1:f1_val"; @@ -1545,19 +1535,19 @@ public async Task GetTagFieldSyncAsync() var SyncRes = ft.TagVals(index, "category"); int i = 0; - Assert.Equal(SyncRes[i++].ToString(), "blue"); - Assert.Equal(SyncRes[i++].ToString(), "green"); - Assert.Equal(SyncRes[i++].ToString(), "orange;purple"); - Assert.Equal(SyncRes[i++].ToString(), "red"); - Assert.Equal(SyncRes[i++].ToString(), "yellow"); + Assert.Equal("blue", SyncRes[i++].ToString()); + Assert.Equal("green", SyncRes[i++].ToString()); + Assert.Equal("orange;purple", SyncRes[i++].ToString()); + Assert.Equal("red", SyncRes[i++].ToString()); + Assert.Equal("yellow", SyncRes[i++].ToString()); var AsyncRes = await ft.TagValsAsync(index, "category"); i = 0; - Assert.Equal(SyncRes[i++].ToString(), "blue"); - Assert.Equal(SyncRes[i++].ToString(), "green"); - Assert.Equal(SyncRes[i++].ToString(), "orange;purple"); - Assert.Equal(SyncRes[i++].ToString(), "red"); - Assert.Equal(SyncRes[i++].ToString(), "yellow"); + Assert.Equal("blue", SyncRes[i++].ToString()); + Assert.Equal("green", SyncRes[i++].ToString()); + Assert.Equal("orange;purple", SyncRes[i++].ToString()); + Assert.Equal("red", SyncRes[i++].ToString()); + Assert.Equal("yellow", SyncRes[i++].ToString()); } [SkipIfRedis(Is.OSSCluster)] @@ -1603,19 +1593,19 @@ public async Task TestGetTagFieldWithNonDefaultSeparatorSyncAsync() var SyncRes = ft.TagVals(index, "category"); int i = 0; - Assert.Equal(SyncRes[i++].ToString(), "blue"); - Assert.Equal(SyncRes[i++].ToString(), "green"); - Assert.Equal(SyncRes[i++].ToString(), "orange,purple"); - Assert.Equal(SyncRes[i++].ToString(), "red"); - Assert.Equal(SyncRes[i++].ToString(), "yellow"); + Assert.Equal("blue", SyncRes[i++].ToString()); + Assert.Equal("green", SyncRes[i++].ToString()); + Assert.Equal("orange,purple", SyncRes[i++].ToString()); + Assert.Equal("red", SyncRes[i++].ToString()); + Assert.Equal("yellow", SyncRes[i++].ToString()); var AsyncRes = await ft.TagValsAsync(index, "category"); i = 0; - Assert.Equal(SyncRes[i++].ToString(), "blue"); - Assert.Equal(SyncRes[i++].ToString(), "green"); - Assert.Equal(SyncRes[i++].ToString(), "orange,purple"); - Assert.Equal(SyncRes[i++].ToString(), "red"); - Assert.Equal(SyncRes[i++].ToString(), "yellow"); + Assert.Equal("blue", SyncRes[i++].ToString()); + Assert.Equal("green", SyncRes[i++].ToString()); + Assert.Equal("orange,purple", SyncRes[i++].ToString()); + Assert.Equal("red", SyncRes[i++].ToString()); + Assert.Equal("yellow", SyncRes[i++].ToString()); } @@ -1882,7 +1872,7 @@ public void TestQueryCommandBuilder() var ft = db.FT(); ft.Create("idx", new FTCreateParams(), new Schema().AddTextField("txt")); var res = ft.Search("idx", testQuery); - Assert.Equal(0, res.Documents.Count()); + Assert.Empty(res.Documents); } [Fact] @@ -1918,7 +1908,7 @@ public void TestQueryCommandBuilderReturnField() var ft = db.FT(); ft.Create("idx", new FTCreateParams(), new Schema().AddTextField("txt")); var res = ft.Search("idx", testQuery); - Assert.Equal(0, res.Documents.Count()); + Assert.Empty(res.Documents); } [SkipIfRedis(Is.OSSCluster)] @@ -2012,8 +2002,8 @@ public void TestLimit() var req = new AggregationRequest("*").SortBy("@t1").Limit(1); var res = ft.Aggregate("idx", req); - Assert.Equal(res.GetResults().Count, 1); - Assert.Equal(res.GetResults()[0]["t1"].ToString(), "a"); + Assert.Equal(1, res.GetResults().Count); + Assert.Equal("a", res.GetResults()[0]["t1"].ToString()); } [SkipIfRedis(Is.OSSCluster)] @@ -2032,8 +2022,8 @@ public async Task TestLimitAsync() var req = new AggregationRequest("*").SortBy("@t1").Limit(1, 1); var res = await ft.AggregateAsync("idx", req); - Assert.Equal(res.GetResults().Count, 1); - Assert.Equal(res.GetResults()[0]["t1"].ToString(), "b"); + Assert.Equal(1, res.GetResults().Count); + Assert.Equal("b", res.GetResults()[0]["t1"].ToString()); } [Fact] @@ -2055,7 +2045,7 @@ public async Task Test_ListAsync() } [Fact] - public async Task TestVectorCount_Issue70() + public void TestVectorCount_Issue70() { var schema = new Schema().AddVectorField("fieldTest", Schema.VectorField.VectorAlgo.HNSW, new Dictionary() { @@ -2259,7 +2249,7 @@ public void TestBasicSpellCheck() db.HashSet("doc1", new HashEntry[] { new HashEntry("name", "name2"), new HashEntry("body", "name2") }); var reply = ft.SpellCheck(index, "name"); - Assert.Equal(1, reply.Keys.Count); + Assert.Single(reply.Keys); Assert.Equal("name", reply.Keys.First()); Assert.Equal(1, reply["name"]["name1"]); Assert.Equal(2, reply["name"]["name2"]); @@ -2279,7 +2269,7 @@ public async Task TestBasicSpellCheckAsync() db.HashSet("doc1", new HashEntry[] { new HashEntry("name", "name2"), new HashEntry("body", "name2") }); var reply = await ft.SpellCheckAsync(index, "name"); - Assert.Equal(1, reply.Keys.Count); + Assert.Single(reply.Keys); Assert.Equal("name", reply.Keys.First()); Assert.Equal(1, reply["name"]["name1"]); Assert.Equal(2, reply["name"]["name2"]); @@ -2425,13 +2415,13 @@ public void TestAddAndGetSuggestion() Assert.True(ft.SugAdd(key, noMatch, 1d) > 0); // test that with a partial part of that string will have the entire word returned - Assert.Equal(1, ft.SugGet(key, suggestion.Substring(0, 3), true, max: 5).Count); + Assert.Single(ft.SugGet(key, suggestion.Substring(0, 3), true, max: 5)); // turn off fuzzy start at second word no hit - Assert.Equal(0, ft.SugGet(key, noMatch.Substring(1, 6), false, max: 5).Count); + Assert.Empty(ft.SugGet(key, noMatch.Substring(1, 6), false, max: 5)); // my attempt to trigger the fuzzy by 1 character - Assert.Equal(1, ft.SugGet(key, noMatch.Substring(1, 6), true, max: 5).Count); + Assert.Single(ft.SugGet(key, noMatch.Substring(1, 6), true, max: 5)); } [Fact] @@ -2448,13 +2438,13 @@ public async Task TestAddAndGetSuggestionAsync() Assert.True(await ft.SugAddAsync(key, noMatch, 1d) > 0); // test that with a partial part of that string will have the entire word returned - Assert.Equal(1, (await ft.SugGetAsync(key, suggestion.Substring(0, 3), true, max: 5)).Count); + Assert.Single((await ft.SugGetAsync(key, suggestion.Substring(0, 3), true, max: 5))); // turn off fuzzy start at second word no hit - Assert.Equal(0, (await ft.SugGetAsync(key, noMatch.Substring(1, 6), false, max: 5)).Count); + Assert.Empty((await ft.SugGetAsync(key, noMatch.Substring(1, 6), false, max: 5))); // my attempt to trigger the fuzzy by 1 character - Assert.Equal(1, (await ft.SugGetAsync(key, noMatch.Substring(1, 6), true, max: 5)).Count); + Assert.Single((await ft.SugGetAsync(key, noMatch.Substring(1, 6), true, max: 5))); } [Fact] @@ -2567,8 +2557,8 @@ public void getSuggestionNoHit() var ft = db.FT(); ft.SugAdd(key, "NO WORD", 0.4); - Assert.Equal(0, ft.SugGetWithScores(key, "DIF").Count); - Assert.Equal(0, ft.SugGet(key, "DIF").Count); + Assert.Empty(ft.SugGetWithScores(key, "DIF")); + Assert.Empty(ft.SugGet(key, "DIF")); } [Fact] @@ -2579,8 +2569,8 @@ public async Task getSuggestionNoHitAsync() var ft = db.FT(); await ft.SugAddAsync(key, "NO WORD", 0.4); - Assert.Equal(0, (await ft.SugGetWithScoresAsync(key, "DIF")).Count); - Assert.Equal(0, (await ft.SugGetAsync(key, "DIF")).Count); + Assert.Empty((await ft.SugGetWithScoresAsync(key, "DIF"))); + Assert.Empty((await ft.SugGetAsync(key, "DIF"))); } [Fact] @@ -2695,16 +2685,17 @@ public void TestProfile() var searchRes = profileSearch.Item1; var searchDet = profileSearch.Item2; - Assert.Equal(searchDet.Count, 5); - Assert.Equal(searchRes.Documents.Count, 2); + Assert.Equal(5, searchDet.Count); + Assert.Equal(2, searchRes.Documents.Count); + // check using AggregationRequest var aggReq = new AggregationRequest("*").Load(FieldName.Of("t")).Apply("startswith(@t, 'hel')", "prefix"); var profileAggregate = ft.ProfileAggregate(index, aggReq); var aggregateRes = profileAggregate.Item1; var aggregateDet = profileAggregate.Item2; - Assert.Equal(aggregateDet.Count, 5); - Assert.Equal(aggregateRes.TotalResults, 1); + Assert.Equal(5, aggregateDet.Count); + Assert.Equal(1, aggregateRes.TotalResults); } [Fact] @@ -2724,16 +2715,16 @@ public async Task TestProfileAsync() var searchRes = profileSearch.Item1; var searchDet = profileSearch.Item2; - Assert.Equal(searchDet.Count, 5); - Assert.Equal(searchRes.Documents.Count, 2); + Assert.Equal(5, searchDet.Count); + Assert.Equal(2, searchRes.Documents.Count); // check using AggregationRequest var aggReq = new AggregationRequest("*").Load(FieldName.Of("t")).Apply("startswith(@t, 'hel')", "prefix"); var profileAggregate = await ft.ProfileAggregateAsync(index, aggReq); var aggregateRes = profileAggregate.Item1; var aggregateDet = profileAggregate.Item2; - Assert.Equal(aggregateDet.Count, 5); - Assert.Equal(aggregateRes.TotalResults, 1); + Assert.Equal(5, aggregateDet.Count); + Assert.Equal(1, aggregateRes.TotalResults); } [Fact] diff --git a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestAdd.cs b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestAdd.cs index 6a4e0e80..804eda42 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestAdd.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestAdd.cs @@ -11,7 +11,9 @@ public class TestAdd : AbstractNRedisStackTest, IDisposable public TestAdd(RedisFixture redisFixture) : base(redisFixture) { } + [Fact] + [Obsolete] public void TestAddNotExistingTimeSeries() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -26,6 +28,7 @@ public void TestAddNotExistingTimeSeries() } [Fact] + [Obsolete] public void TestAddExistingTimeSeries() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -41,6 +44,7 @@ public void TestAddExistingTimeSeries() } [Fact] + [Obsolete] public void TestAddStar() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -49,11 +53,12 @@ public void TestAddStar() ts.Add(key, "*", 1.1); TimeSeriesInformation info = ts.Info(key); - Assert.True(info.FirstTimeStamp > 0); + Assert.True(info.FirstTimeStamp! > 0); Assert.Equal(info.FirstTimeStamp, info.LastTimeStamp); } [Fact] + [Obsolete] public void TestAddWithRetentionTime() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -69,6 +74,7 @@ public void TestAddWithRetentionTime() } [Fact] + [Obsolete] public void TestAddWithLabels() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -85,6 +91,7 @@ public void TestAddWithLabels() } [Fact] + [Obsolete] public void TestAddWithUncompressed() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -99,6 +106,7 @@ public void TestAddWithUncompressed() } [Fact] + [Obsolete] public void TestAddWithChunkSize() { IDatabase db = redisFixture.Redis.GetDatabase(); diff --git a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestAddAsync.cs b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestAddAsync.cs index c7ec525d..7e641ab3 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestAddAsync.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestAddAsync.cs @@ -11,6 +11,7 @@ public class TestAddAsync : AbstractNRedisStackTest public TestAddAsync(RedisFixture redisFixture) : base(redisFixture) { } [Fact] + [Obsolete] public async Task TestAddNotExistingTimeSeries() { var key = CreateKeyName(); @@ -26,6 +27,7 @@ public async Task TestAddNotExistingTimeSeries() } [Fact] + [Obsolete] public async Task TestAddExistingTimeSeries() { var key = CreateKeyName(); @@ -42,6 +44,7 @@ public async Task TestAddExistingTimeSeries() } [Fact] + [Obsolete] public async Task TestAddStar() { var key = CreateKeyName(); @@ -50,11 +53,12 @@ public async Task TestAddStar() var ts = db.TS(); await ts.AddAsync(key, "*", 1.1); var info = await ts.InfoAsync(key); - Assert.True(info.FirstTimeStamp > 0); + Assert.True(info.FirstTimeStamp! > 0); Assert.Equal(info.FirstTimeStamp, info.LastTimeStamp); } [Fact] + [Obsolete] public async Task TestAddWithRetentionTime() { var key = CreateKeyName(); @@ -72,6 +76,7 @@ public async Task TestAddWithRetentionTime() } [Fact] + [Obsolete] public async Task TestAddWithLabels() { var key = CreateKeyName(); @@ -90,6 +95,7 @@ public async Task TestAddWithLabels() } [Fact] + [Obsolete] public async Task TestAddWithChunkSize() { var key = CreateKeyName(); @@ -105,6 +111,7 @@ public async Task TestAddWithChunkSize() } [Fact] + [Obsolete] public async Task TestAddWithUncompressed() { var key = CreateKeyName(); diff --git a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestAlter.cs b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestAlter.cs index af66cc42..281518b4 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestAlter.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestAlter.cs @@ -12,7 +12,9 @@ public class TestAlter : AbstractNRedisStackTest, IDisposable public TestAlter(RedisFixture redisFixture) : base(redisFixture) { } + [Fact] + [Obsolete] public void TestAlterRetentionTime() { long retentionTime = 5000; @@ -26,6 +28,7 @@ public void TestAlterRetentionTime() } [Fact] + [Obsolete] public void TestAlterLabels() { TimeSeriesLabel label = new TimeSeriesLabel("key", "value"); @@ -44,6 +47,7 @@ public void TestAlterLabels() } [Fact] + [Obsolete] public void TestAlterPolicyAndChunk() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -52,8 +56,8 @@ public void TestAlterPolicyAndChunk() ts.Create(key); Assert.True(ts.Alter(key, chunkSizeBytes: 128, duplicatePolicy: TsDuplicatePolicy.MIN)); TimeSeriesInformation info = ts.Info(key); - Assert.Equal(info.ChunkSize, 128); - Assert.Equal(info.DuplicatePolicy, TsDuplicatePolicy.MIN); + Assert.Equal(128, info.ChunkSize); + Assert.Equal(TsDuplicatePolicy.MIN, info.DuplicatePolicy); } } } diff --git a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestAlterAsync.cs b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestAlterAsync.cs index 688860e9..ff5df550 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestAlterAsync.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestAlterAsync.cs @@ -10,6 +10,7 @@ public class TestAlterAsync : AbstractNRedisStackTest public TestAlterAsync(RedisFixture redisFixture) : base(redisFixture) { } [Fact] + [Obsolete] public async Task TestAlterRetentionTime() { var key = CreateKeyName(); @@ -25,6 +26,7 @@ public async Task TestAlterRetentionTime() } [Fact] + [Obsolete] public async Task TestAlterLabels() { var key = CreateKeyName(); @@ -47,6 +49,7 @@ public async Task TestAlterLabels() } [Fact] + [Obsolete] public async Task TestAlterPolicyAndChunkAsync() { var key = CreateKeyName(); @@ -56,8 +59,8 @@ public async Task TestAlterPolicyAndChunkAsync() ts.Create(key); Assert.True(await ts.AlterAsync(key, chunkSizeBytes: 128, duplicatePolicy: TsDuplicatePolicy.MIN)); TimeSeriesInformation info = ts.Info(key); - Assert.Equal(info.ChunkSize, 128); - Assert.Equal(info.DuplicatePolicy, TsDuplicatePolicy.MIN); + Assert.Equal(128, info.ChunkSize); + Assert.Equal(TsDuplicatePolicy.MIN, info.DuplicatePolicy); } } diff --git a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestCreate.cs b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestCreate.cs index 9d7b2cc2..317235af 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestCreate.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestCreate.cs @@ -12,7 +12,9 @@ public class TestCreate : AbstractNRedisStackTest, IDisposable public TestCreate(RedisFixture redisFixture) : base(redisFixture) { } + [Fact] + [Obsolete] public void TestCreateOK() { IDatabase db = redisFixture.Redis.GetDatabase(); @@ -23,6 +25,7 @@ public void TestCreateOK() } [Fact] + [Obsolete] public void TestCreateRetentionTime() { long retentionTime = 5000; @@ -35,6 +38,7 @@ public void TestCreateRetentionTime() } [Fact] + [Obsolete] public void TestCreateLabels() { TimeSeriesLabel label = new TimeSeriesLabel("key", "value"); @@ -48,6 +52,7 @@ public void TestCreateLabels() } [Fact] + [Obsolete] public void TestCreateEmptyLabels() { var labels = new List(); diff --git a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestCreateAsync.cs b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestCreateAsync.cs index 39b1951f..36993d4b 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestCreateAsync.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestCreateAsync.cs @@ -20,6 +20,7 @@ public async Task TestCreateOK() } [Fact] + [Obsolete] public async Task TestCreateRetentionTime() { var key = CreateKeyName(); @@ -34,6 +35,7 @@ public async Task TestCreateRetentionTime() } [Fact] + [Obsolete] public async Task TestCreateLabels() { var key = CreateKeyName(); @@ -49,6 +51,7 @@ public async Task TestCreateLabels() } [Fact] + [Obsolete] public async Task TestCreateEmptyLabels() { var key = CreateKeyName(); diff --git a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestDecrBy.cs b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestDecrBy.cs index c6afa19e..14e54e6c 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestDecrBy.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestDecrBy.cs @@ -11,6 +11,7 @@ public class TestDecrBy : AbstractNRedisStackTest, IDisposable public TestDecrBy(RedisFixture redisFixture) : base(redisFixture) { } + [Fact] public void TestDefaultDecrBy() { @@ -19,7 +20,7 @@ public void TestDefaultDecrBy() db.Execute("FLUSHALL"); var ts = db.TS(); Assert.True(ts.DecrBy(key, -value) > 0); - Assert.Equal(value, ts.Get(key).Val); + Assert.Equal(value, ts.Get(key)!.Val); } [Fact] @@ -30,7 +31,7 @@ public void TestStarDecrBy() db.Execute("FLUSHALL"); var ts = db.TS(); Assert.True(ts.DecrBy(key, -value, timestamp: "*") > 0); - Assert.Equal(value, ts.Get(key).Val); + Assert.Equal(value, ts.Get(key)!.Val); } [Fact] @@ -46,6 +47,7 @@ public void TestDecrByTimeStamp() } [Fact] + [Obsolete] public void TestDefaultDecrByWithRetentionTime() { double value = 5.5; @@ -54,12 +56,13 @@ public void TestDefaultDecrByWithRetentionTime() db.Execute("FLUSHALL"); var ts = db.TS(); Assert.True(ts.DecrBy(key, -value, retentionTime: retentionTime) > 0); - Assert.Equal(value, ts.Get(key).Val); + Assert.Equal(value, ts.Get(key)!.Val); TimeSeriesInformation info = ts.Info(key); Assert.Equal(retentionTime, info.RetentionTime); } [Fact] + [Obsolete] public void TestDefaultDecrByWithLabels() { double value = 5.5; @@ -69,7 +72,7 @@ public void TestDefaultDecrByWithLabels() var ts = db.TS(); var labels = new List { label }; Assert.True(ts.DecrBy(key, -value, labels: labels) > 0); - Assert.Equal(value, ts.Get(key).Val); + Assert.Equal(value, ts.Get(key)!.Val); TimeSeriesInformation info = ts.Info(key); Assert.Equal(labels, info.Labels); } @@ -82,7 +85,7 @@ public void TestDefaultDecrByWithUncompressed() db.Execute("FLUSHALL"); var ts = db.TS(); Assert.True(ts.DecrBy(key, -value, uncompressed: true) > 0); - Assert.Equal(value, ts.Get(key).Val); + Assert.Equal(value, ts.Get(key)!.Val); } [Fact] diff --git a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestDecrByAsync.cs b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestDecrByAsync.cs index 87a29974..219ebe64 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestDecrByAsync.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestDecrByAsync.cs @@ -20,7 +20,7 @@ public async Task TestDefaultDecrBy() Assert.True(await ts.DecrByAsync(key, -value) > 0); var result = await ts.GetAsync(key); - Assert.Equal(value, result.Val); + Assert.Equal(value, result!.Val); } [Fact] @@ -34,7 +34,7 @@ public async Task TestStarDecrBy() Assert.True(await ts.DecrByAsync(key, -value, timestamp: "*") > 0); var result = await ts.GetAsync(key); - Assert.Equal(value, result.Val); + Assert.Equal(value, result!.Val); } [Fact] @@ -51,6 +51,7 @@ public async Task TestDecrByTimeStamp() } [Fact] + [Obsolete] public async Task TestDefaultDecrByWithRetentionTime() { var key = CreateKeyName(); @@ -62,13 +63,14 @@ public async Task TestDefaultDecrByWithRetentionTime() Assert.True(await ts.DecrByAsync(key, -value, retentionTime: retentionTime) > 0); var result = await ts.GetAsync(key); - Assert.Equal(value, result.Val); + Assert.Equal(value, result!.Val); var info = await ts.InfoAsync(key); Assert.Equal(retentionTime, info.RetentionTime); } [Fact] + [Obsolete] public async Task TestDefaultDecrByWithLabels() { var key = CreateKeyName(); @@ -81,7 +83,7 @@ public async Task TestDefaultDecrByWithLabels() Assert.True(await ts.DecrByAsync(key, -value, labels: labels) > 0); var result = await ts.GetAsync(key); - Assert.Equal(value, result.Val); + Assert.Equal(value, result!.Val); var info = await ts.InfoAsync(key); Assert.Equal(labels, info.Labels); @@ -98,7 +100,7 @@ public async Task TestDefaultDecrByWithUncompressed() Assert.True(await ts.DecrByAsync(key, -value, uncompressed: true) > 0); var result = await ts.GetAsync(key); - Assert.Equal(value, result.Val); + Assert.Equal(value, result!.Val); } [Fact] diff --git a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestDel.cs b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestDel.cs index 42c22a75..b4b6134b 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestDel.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestDel.cs @@ -12,6 +12,7 @@ public class TestDel : AbstractNRedisStackTest, IDisposable public TestDel(RedisFixture redisFixture) : base(redisFixture) { } + private List CreateData(ITimeSeriesCommands ts, int timeBucket) //TODO: check this { var tuples = new List(); diff --git a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestGet.cs b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestGet.cs index dd5f9d39..7f8edf0a 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestGet.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestGet.cs @@ -12,6 +12,7 @@ public class TestGet : AbstractNRedisStackTest, IDisposable public TestGet(RedisFixture redisFixture) : base(redisFixture) { } + [Fact] public void TestGetNotExists() { @@ -42,7 +43,7 @@ public void TestAddAndGet() var ts = db.TS(); ts.Create(key); ts.Add(key, now, 1.1); - TimeSeriesTuple actual = ts.Get(key); + TimeSeriesTuple actual = ts.Get(key)!; Assert.Equal(expected, actual); } } diff --git a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestIncrBy.cs b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestIncrBy.cs index f46db56f..af1d35bf 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestIncrBy.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestIncrBy.cs @@ -11,6 +11,7 @@ public class TestIncrBy : AbstractNRedisStackTest, IDisposable public TestIncrBy(RedisFixture redisFixture) : base(redisFixture) { } + [Fact] public void TestDefaultIncrBy() { @@ -19,7 +20,7 @@ public void TestDefaultIncrBy() db.Execute("FLUSHALL"); var ts = db.TS(); Assert.True(ts.IncrBy(key, value) > 0); - Assert.Equal(value, ts.Get(key).Val); + Assert.Equal(value, ts.Get(key)!.Val); } [Fact] @@ -30,7 +31,7 @@ public void TestStarIncrBy() db.Execute("FLUSHALL"); var ts = db.TS(); Assert.True(ts.IncrBy(key, value, timestamp: "*") > 0); - Assert.Equal(value, ts.Get(key).Val); + Assert.Equal(value, ts.Get(key)!.Val); } [Fact] @@ -46,6 +47,7 @@ public void TestIncrByTimeStamp() } [Fact] + [Obsolete] public void TestDefaultIncrByWithRetentionTime() { double value = 5.5; @@ -54,12 +56,13 @@ public void TestDefaultIncrByWithRetentionTime() db.Execute("FLUSHALL"); var ts = db.TS(); Assert.True(ts.IncrBy(key, value, retentionTime: retentionTime) > 0); - Assert.Equal(value, ts.Get(key).Val); + Assert.Equal(value, ts.Get(key)!.Val); TimeSeriesInformation info = ts.Info(key); Assert.Equal(retentionTime, info.RetentionTime); } [Fact] + [Obsolete] public void TestDefaultIncrByWithLabels() { double value = 5.5; @@ -69,7 +72,7 @@ public void TestDefaultIncrByWithLabels() var ts = db.TS(); var labels = new List { label }; Assert.True(ts.IncrBy(key, value, labels: labels) > 0); - Assert.Equal(value, ts.Get(key).Val); + Assert.Equal(value, ts.Get(key)!.Val); TimeSeriesInformation info = ts.Info(key); Assert.Equal(labels, info.Labels); } @@ -82,7 +85,7 @@ public void TestDefaultIncrByWithUncompressed() db.Execute("FLUSHALL"); var ts = db.TS(); Assert.True(ts.IncrBy(key, value, uncompressed: true) > 0); - Assert.Equal(value, ts.Get(key).Val); + Assert.Equal(value, ts.Get(key)!.Val); } [Fact] diff --git a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestIncrByAsync.cs b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestIncrByAsync.cs index 2ca85069..1c02440e 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestIncrByAsync.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestIncrByAsync.cs @@ -20,7 +20,7 @@ public async Task TestDefaultIncrBy() Assert.True(await ts.IncrByAsync(key, value) > 0); var result = await ts.GetAsync(key); - Assert.Equal(value, result.Val); + Assert.Equal(value, result!.Val); } [Fact] @@ -34,7 +34,7 @@ public async Task TestStarIncrBy() Assert.True(await ts.IncrByAsync(key, value, timestamp: "*") > 0); var result = await ts.GetAsync(key); - Assert.Equal(value, result.Val); + Assert.Equal(value, result!.Val); } [Fact] @@ -51,6 +51,7 @@ public async Task TestIncrByTimeStamp() } [Fact] + [Obsolete] public async Task TestDefaultIncrByWithRetentionTime() { var key = CreateKeyName(); @@ -62,13 +63,14 @@ public async Task TestDefaultIncrByWithRetentionTime() Assert.True(await ts.IncrByAsync(key, value, retentionTime: retentionTime) > 0); var result = await ts.GetAsync(key); - Assert.Equal(value, result.Val); + Assert.Equal(value, result!.Val); var info = await ts.InfoAsync(key); Assert.Equal(retentionTime, info.RetentionTime); } [Fact] + [Obsolete] public async Task TestDefaultIncrByWithLabels() { var key = CreateKeyName(); @@ -81,7 +83,7 @@ public async Task TestDefaultIncrByWithLabels() Assert.True(await ts.IncrByAsync(key, value, labels: labels) > 0); var result = await ts.GetAsync(key); - Assert.Equal(value, result.Val); + Assert.Equal(value, result!.Val); var info = await ts.InfoAsync(key); Assert.Equal(labels, info.Labels); @@ -98,7 +100,7 @@ public async Task TestDefaultIncrByWithUncompressed() Assert.True(await ts.IncrByAsync(key, value, uncompressed: true) > 0); var result = await ts.GetAsync(key); - Assert.Equal(value, result.Val); + Assert.Equal(value, result!.Val); } [Fact] diff --git a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestMADD.cs b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestMADD.cs index cba16e34..4acf5547 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestMADD.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestMADD.cs @@ -14,6 +14,7 @@ public class TestMADD : AbstractNRedisStackTest, IDisposable public TestMADD(RedisFixture redisFixture) : base(redisFixture) { } [SkipIfRedis(Is.OSSCluster)] + [Obsolete] public void TestStarMADD() { @@ -37,7 +38,7 @@ public void TestStarMADD() foreach (var key in keys) { TimeSeriesInformation info = ts.Info(key); - Assert.True(info.FirstTimeStamp > 0); + Assert.True(info.FirstTimeStamp! > 0); Assert.Equal(info.FirstTimeStamp, info.LastTimeStamp); } } diff --git a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestMAddAsync.cs b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestMAddAsync.cs index 78ef509b..5bc4b04a 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestMAddAsync.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestMAddAsync.cs @@ -12,6 +12,7 @@ public TestMAddAsync(RedisFixture redisFixture) : base(redisFixture) { } [SkipIfRedis(Is.OSSCluster)] + [Obsolete] public async Task TestStarMADD() { var keys = CreateKeyNames(2); @@ -37,7 +38,7 @@ public async Task TestStarMADD() foreach (var key in keys) { TimeSeriesInformation info = await ts.InfoAsync(key); - Assert.True(info.FirstTimeStamp > 0); + Assert.True(info.FirstTimeStamp! > 0); Assert.Equal(info.FirstTimeStamp, info.LastTimeStamp); } } diff --git a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestRange.cs b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestRange.cs index ba9af54b..342f6fb2 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestRange.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestRange.cs @@ -12,6 +12,7 @@ public class TestRange : AbstractNRedisStackTest, IDisposable public TestRange(RedisFixture redisFixture) : base(redisFixture) { } + private List CreateData(ITimeSeriesCommands ts, int timeBucket) { var tuples = new List(); diff --git a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestRules.cs b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestRules.cs index fe30f5cd..82ff0183 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestRules.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestRules.cs @@ -33,6 +33,7 @@ public TestRules(RedisFixture redisFixture) : base(redisFixture) } [SkipIfRedis(Is.OSSCluster)] + [Obsolete] public void TestRulesAdditionDeletion() { IDatabase db = redisFixture.Redis.GetDatabase(); diff --git a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestRulesAsync.cs b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestRulesAsync.cs index e024bec8..b7cb6455 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestRulesAsync.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TestAPI/TestRulesAsync.cs @@ -11,6 +11,7 @@ public class TestRulesAsync : AbstractNRedisStackTest public TestRulesAsync(RedisFixture redisFixture) : base(redisFixture) { } [SkipIfRedis(Is.OSSCluster)] + [Obsolete] public async Task TestRulesAdditionDeletion() { var key = CreateKeyName(); diff --git a/tests/NRedisStack.Tests/TimeSeries/TestDataTypes/TestTimeSeriesInformation.cs b/tests/NRedisStack.Tests/TimeSeries/TestDataTypes/TestTimeSeriesInformation.cs index f4432c16..e3e43daa 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TestDataTypes/TestTimeSeriesInformation.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TestDataTypes/TestTimeSeriesInformation.cs @@ -13,6 +13,7 @@ public class TestInformation : AbstractNRedisStackTest public TestInformation(NRedisStack.Tests.RedisFixture redisFixture) : base(redisFixture) { } [Fact] + [Obsolete] public void TestInformationSync() { string key = CreateKeyName(); @@ -28,19 +29,20 @@ public void TestInformationSync() Assert.Equal(4184, info.MemoryUsage); Assert.Equal(0, info.RetentionTime); Assert.Equal(1, info.ChunkCount); - Assert.Equal(null, info.DuplicatePolicy); + Assert.Null(info.DuplicatePolicy); Assert.Null(info.KeySelfName); Assert.Null(info.Chunks); Assert.Equal(4184, infoDebug.MemoryUsage); Assert.Equal(0, infoDebug.RetentionTime); Assert.Equal(1, infoDebug.ChunkCount); - Assert.Equal(null, infoDebug.DuplicatePolicy); + Assert.Null(infoDebug.DuplicatePolicy); Assert.Equal(infoDebug.KeySelfName, key); - Assert.Equal(infoDebug.Chunks.Count, 1); + Assert.Equal(1, infoDebug.Chunks!.Count); } [Fact] + [Obsolete] public async Task TestInformationAsync() { string key = CreateKeyName(); @@ -56,16 +58,16 @@ public async Task TestInformationAsync() Assert.Equal(4184, info.MemoryUsage); Assert.Equal(0, info.RetentionTime); Assert.Equal(1, info.ChunkCount); - Assert.Equal(null, info.DuplicatePolicy); + Assert.Null(info.DuplicatePolicy); Assert.Null(info.KeySelfName); Assert.Null(info.Chunks); Assert.Equal(4184, infoDebug.MemoryUsage); Assert.Equal(0, infoDebug.RetentionTime); Assert.Equal(1, infoDebug.ChunkCount); - Assert.Equal(null, infoDebug.DuplicatePolicy); + Assert.Null(infoDebug.DuplicatePolicy); Assert.Equal(infoDebug.KeySelfName, key); - Assert.Equal(infoDebug.Chunks.Count, 1); + Assert.Equal(1, infoDebug.Chunks!.Count); } } } \ No newline at end of file diff --git a/tests/NRedisStack.Tests/TimeSeries/TimeSeriesTests.cs b/tests/NRedisStack.Tests/TimeSeries/TimeSeriesTests.cs index 6874fa83..cf7615a8 100644 --- a/tests/NRedisStack.Tests/TimeSeries/TimeSeriesTests.cs +++ b/tests/NRedisStack.Tests/TimeSeries/TimeSeriesTests.cs @@ -7,7 +7,7 @@ namespace NRedisStack.Tests.TimeSeries; public class TimeSeriesTests : AbstractNRedisStackTest, IDisposable { - private readonly string key = "TIME_SERIES_TESTS"; + // private readonly string key = "TIME_SERIES_TESTS"; public TimeSeriesTests(RedisFixture redisFixture) : base(redisFixture) { } // [Fact] diff --git a/tests/NRedisStack.Tests/TopK/TopKTests.cs b/tests/NRedisStack.Tests/TopK/TopKTests.cs index cb5714e1..6c91c9c2 100644 --- a/tests/NRedisStack.Tests/TopK/TopKTests.cs +++ b/tests/NRedisStack.Tests/TopK/TopKTests.cs @@ -21,7 +21,7 @@ public void CreateTopKFilter() topk.Reserve(key, 30, 2000, 7, 0.925); var res = topk.Add(key, "bb", "cc"); - Assert.True(res[0].IsNull && res[1].IsNull); + Assert.True(res![0].IsNull && res[1].IsNull); Assert.Equal(topk.Query(key, "bb", "gg", "cc"), new bool[] { true, false, true }); Assert.False(topk.Query(key, "notExists")); @@ -29,23 +29,23 @@ public void CreateTopKFilter() Assert.Equal(topk.Count(key, "bb", "gg", "cc"), new long[] { 1, 0, 1 }); var res2 = topk.List(key); - Assert.Equal(res2[0].ToString(), "bb"); - Assert.Equal(res2[1].ToString(), "cc"); + Assert.Equal("bb", res2[0].ToString()); + Assert.Equal("cc", res2[1].ToString()); var tuple = new Tuple("ff", 10); var del = topk.IncrBy(key, tuple); Assert.True(topk.IncrBy(key, tuple)[0].IsNull); res2 = topk.List(key); - Assert.Equal(res2[0].ToString(), "ff"); - Assert.Equal(res2[1].ToString(), "bb"); - Assert.Equal(res2[2].ToString(), "cc"); + Assert.Equal("ff", res2[0].ToString()); + Assert.Equal("bb", res2[1].ToString()); + Assert.Equal("cc", res2[2].ToString()); var info = topk.Info(key); - Assert.Equal(info.Decay, 0.925); - Assert.Equal(info.Depth, 7); - Assert.Equal(info.K, 30); - Assert.Equal(info.Width, 2000); + Assert.Equal(0.925, info.Decay); + Assert.Equal(7, info.Depth); + Assert.Equal(30, info.K); + Assert.Equal(2000, info.Width); } [Fact] @@ -58,7 +58,7 @@ public async Task CreateTopKFilterAsync() await topk.ReserveAsync(key, 30, 2000, 7, 0.925); var res = await topk.AddAsync(key, "bb", "cc"); - Assert.True(res[0].IsNull && res[1].IsNull); + Assert.True(res![0].IsNull && res[1].IsNull); Assert.Equal(await topk.QueryAsync(key, "bb", "gg", "cc"), new bool[] { true, false, true }); Assert.False(await topk.QueryAsync(key, "notExists")); @@ -66,22 +66,22 @@ public async Task CreateTopKFilterAsync() Assert.Equal(await topk.CountAsync(key, "bb", "gg", "cc"), new long[] { 1, 0, 1 }); var res2 = await topk.ListAsync(key); - Assert.Equal(res2[0].ToString(), "bb"); - Assert.Equal(res2[1].ToString(), "cc"); + Assert.Equal("bb", res2[0].ToString()); + Assert.Equal("cc", res2[1].ToString()); var tuple = new Tuple("ff", 10); Assert.True((await topk.IncrByAsync(key, tuple))[0].IsNull); res2 = await topk.ListAsync(key); - Assert.Equal(res2[0].ToString(), "ff"); - Assert.Equal(res2[1].ToString(), "bb"); - Assert.Equal(res2[2].ToString(), "cc"); + Assert.Equal("ff", res2[0].ToString()); + Assert.Equal("bb", res2[1].ToString()); + Assert.Equal("cc", res2[2].ToString()); var info = await topk.InfoAsync(key); - Assert.Equal(info.Decay, 0.925); - Assert.Equal(info.Depth, 7); - Assert.Equal(info.K, 30); - Assert.Equal(info.Width, 2000); + Assert.Equal(0.925, info.Decay); + Assert.Equal(7, info.Depth); + Assert.Equal(30, info.K); + Assert.Equal(2000, info.Width); } [Fact] diff --git a/tests/NRedisStack.Tests/TransactionsTests.cs b/tests/NRedisStack.Tests/TransactionsTests.cs index db893206..0422dca4 100644 --- a/tests/NRedisStack.Tests/TransactionsTests.cs +++ b/tests/NRedisStack.Tests/TransactionsTests.cs @@ -11,8 +11,9 @@ public class TransactionTests : AbstractNRedisStackTest, IDisposable private readonly string key = "TRX_TESTS"; public TransactionTests(RedisFixture redisFixture) : base(redisFixture) { } + [Fact] - public async Task TestJsonTransaction() + public void TestJsonTransaction() { IDatabase db = redisFixture.Redis.GetDatabase(); db.Execute("FLUSHALL"); @@ -28,29 +29,30 @@ public async Task TestJsonTransaction() } [SkipIfRedis(Comparison.GreaterThanOrEqual, "7.1.242")] + [Obsolete] public async Task TestModulsTransaction() { IDatabase db = redisFixture.Redis.GetDatabase(); db.Execute("FLUSHALL"); var tran = new Transaction(db); - tran.Bf.ReserveAsync("bf-key", 0.001, 100); - tran.Bf.AddAsync("bf-key", "1"); - tran.Cms.InitByDimAsync("cms-key", 100, 5); - tran.Cf.ReserveAsync("cf-key", 100); - tran.Graph.QueryAsync("graph-key", "CREATE ({name:'shachar',age:23})"); - tran.Json.SetAsync("json-key", "$", "{}"); - tran.Ft.CreateAsync("ft-key", new FTCreateParams(), new Schema().AddTextField("txt")); - tran.Tdigest.CreateAsync("tdigest-key", 100); - tran.Ts.CreateAsync("ts-key", 100); - tran.TopK.ReserveAsync("topk-key", 100, 100, 100); + await tran.Bf.ReserveAsync("bf-key", 0.001, 100); + await tran.Bf.AddAsync("bf-key", "1"); + await tran.Cms.InitByDimAsync("cms-key", 100, 5); + await tran.Cf.ReserveAsync("cf-key", 100); + await tran.Graph.QueryAsync("graph-key", "CREATE ({name:'shachar',age:23})"); + await tran.Json.SetAsync("json-key", "$", "{}"); + await tran.Ft.CreateAsync("ft-key", new FTCreateParams(), new Schema().AddTextField("txt")); + await tran.Tdigest.CreateAsync("tdigest-key", 100); + await tran.Ts.CreateAsync("ts-key", 100); + await tran.TopK.ReserveAsync("topk-key", 100, 100, 100); Assert.False(db.KeyExists("bf-key")); Assert.False(db.KeyExists("cms-key")); Assert.False(db.KeyExists("cf-key")); Assert.False(db.KeyExists("graph-key")); Assert.False(db.KeyExists("json-key")); - Assert.Equal(0, db.FT()._List().Length); + Assert.Empty(db.FT()._List()); Assert.False(db.KeyExists("tdigest-key")); Assert.False(db.KeyExists("ts-key")); Assert.False(db.KeyExists("topk-key")); @@ -79,27 +81,28 @@ public async Task TestModulsTransaction() } [SkipIfRedis(Is.OSSCluster)] + [Obsolete] public async Task TestModulsTransactionWithoutGraph() { IDatabase db = redisFixture.Redis.GetDatabase(); db.Execute("FLUSHALL"); var tran = new Transaction(db); - tran.Bf.ReserveAsync("bf-key", 0.001, 100); - tran.Bf.AddAsync("bf-key", "1"); - tran.Cms.InitByDimAsync("cms-key", 100, 5); - tran.Cf.ReserveAsync("cf-key", 100); - tran.Json.SetAsync("json-key", "$", "{}"); - tran.Ft.CreateAsync("ft-key", new FTCreateParams(), new Schema().AddTextField("txt")); - tran.Tdigest.CreateAsync("tdigest-key", 100); - tran.Ts.CreateAsync("ts-key", 100); - tran.TopK.ReserveAsync("topk-key", 100, 100, 100); + await tran.Bf.ReserveAsync("bf-key", 0.001, 100); + await tran.Bf.AddAsync("bf-key", "1"); + await tran.Cms.InitByDimAsync("cms-key", 100, 5); + await tran.Cf.ReserveAsync("cf-key", 100); + await tran.Json.SetAsync("json-key", "$", "{}"); + await tran.Ft.CreateAsync("ft-key", new FTCreateParams(), new Schema().AddTextField("txt")); + await tran.Tdigest.CreateAsync("tdigest-key", 100); + await tran.Ts.CreateAsync("ts-key", 100); + await tran.TopK.ReserveAsync("topk-key", 100, 100, 100); Assert.False(db.KeyExists("bf-key")); Assert.False(db.KeyExists("cms-key")); Assert.False(db.KeyExists("cf-key")); Assert.False(db.KeyExists("json-key")); - Assert.Equal(0, db.FT()._List().Length); + Assert.Empty(db.FT()._List()); Assert.False(db.KeyExists("tdigest-key")); Assert.False(db.KeyExists("ts-key")); Assert.False(db.KeyExists("topk-key"));