From e7565683dccac6159e227fb0c9cb44845be1b522 Mon Sep 17 00:00:00 2001 From: andy-stark-redis <164213578+andy-stark-redis@users.noreply.github.com> Date: Thu, 26 Sep 2024 08:24:14 +0100 Subject: [PATCH 1/8] DOC-4251 full text search examples (#339) --- tests/Doc/QueryFtExample.cs | 274 ++++++++++++++++++++++++++++++++++++ 1 file changed, 274 insertions(+) create mode 100644 tests/Doc/QueryFtExample.cs diff --git a/tests/Doc/QueryFtExample.cs b/tests/Doc/QueryFtExample.cs new file mode 100644 index 00000000..bc7f544b --- /dev/null +++ b/tests/Doc/QueryFtExample.cs @@ -0,0 +1,274 @@ +// EXAMPLE: query_ft +// HIDE_START + +using NRedisStack.RedisStackCommands; +using NRedisStack.Search; +using NRedisStack.Search.Literals.Enums; +using NRedisStack.Tests; +using StackExchange.Redis; + +// HIDE_END + +// REMOVE_START +namespace Doc; +[Collection("DocsTests")] +// REMOVE_END + +// HIDE_START +public class QueryFtExample +{ + + [SkipIfRedis(Is.OSSCluster)] + public void run() + { + var muxer = ConnectionMultiplexer.Connect("localhost:6379"); + var db = muxer.GetDatabase(); + //REMOVE_START + // Clear any keys here before using them in tests. + try { db.FT().DropIndex("idx:bicycle", true); } catch { } + //REMOVE_END + + Schema bikeSchema = new Schema() + .AddTextField(new FieldName("$.brand", "brand")) + .AddTextField(new FieldName("$.model", "model")) + .AddTextField(new FieldName("$.description", "description")); + + FTCreateParams bikeParams = new FTCreateParams() + .AddPrefix("bicycle:") + .On(IndexDataType.JSON); + + db.FT().Create("idx:bicycle", bikeParams, bikeSchema); + + var bicycles = new object[] + { + new + { + brand = "Velorim", + model = "Jigger", + price = 270, + 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 " + + "choice for the rare tenacious little rider " + + "raring to go.", + condition = "used" + }, + new + { + brand = "Bicyk", + model = "Hillcraft", + price = 1200, + description = "Kids want to ride with as little weight as possible." + + " Especially on an incline! They may be at the age " + + "when a 27.5 inch wheel bike is just too clumsy coming " + + "off a 24 inch bike. The Hillcraft 26 is just the solution" + + " they need!", + condition = "used", + }, + new + { + brand = "Nord", + model = "Chook air 5", + price = 815, + description = "The Chook Air 5 gives kids aged six years and older " + + "a durable and uberlight mountain bike for their first" + + " experience on tracks and easy cruising through forests" + + " and fields. The lower top tube makes it easy to mount" + + " and dismount in any situation, giving your kids greater" + + " safety on the trails.", + condition = "used", + }, + new + { + brand = "Eva", + model = "Eva 291", + price = 3400, + description = "The sister company to Nord, Eva launched in 2005 as the" + + " first and only women-dedicated bicycle brand. Designed" + + " by women for women, allEva bikes are optimized for the" + + " feminine physique using analytics from a body metrics" + + " database. If you like 29ers, try the Eva 291. It’s a " + + "brand new bike for 2022.. This full-suspension, " + + "cross-country ride has been designed for velocity. The" + + " 291 has 100mm of front and rear travel, a superlight " + + "aluminum frame and fast-rolling 29-inch wheels. Yippee!", + condition = "used", + }, + new + { + brand = "Noka Bikes", + model = "Kahuna", + price = 3200, + description = "Whether you want to try your hand at XC racing or are " + + "looking for a lively trail bike that's just as inspiring" + + " on the climbs as it is over rougher ground, the Wilder" + + " is one heck of a bike built specifically for short women." + + " Both the frames and components have been tweaked to " + + "include a women’s saddle, different bars and unique " + + "colourway.", + condition = "used", + }, + new + { + brand = "Breakout", + model = "XBN 2.1 Alloy", + price = 810, + description = "The XBN 2.1 Alloy is our entry-level road bike – but that’s" + + " not to say that it’s a basic machine. With an internal " + + "weld aluminium frame, a full carbon fork, and the slick-shifting" + + " Claris gears from Shimano’s, this is a bike which doesn’t" + + " break the bank and delivers craved performance.", + condition = "new", + }, + new + { + brand = "ScramBikes", + model = "WattBike", + price = 2300, + description = "The WattBike is the best e-bike for people who still feel young" + + " at heart. It has a Bafang 1000W mid-drive system and a 48V" + + " 17.5AH Samsung Lithium-Ion battery, allowing you to ride for" + + " more than 60 miles on one charge. It’s great for tackling hilly" + + " terrain or if you just fancy a more leisurely ride. With three" + + " working modes, you can choose between E-bike, assisted bicycle," + + " and normal bike modes.", + condition = "new", + }, + new + { + brand = "Peaknetic", + model = "Secto", + price = 430, + description = "If you struggle with stiff fingers or a kinked neck or back after" + + " a few minutes on the road, this lightweight, aluminum bike" + + " alleviates those issues and allows you to enjoy the ride. From" + + " the ergonomic grips to the lumbar-supporting seat position, the" + + " Roll Low-Entry offers incredible comfort. The rear-inclined seat" + + " tube facilitates stability by allowing you to put a foot on the" + + " ground to balance at a stop, and the low step-over frame makes it" + + " accessible for all ability and mobility levels. The saddle is" + + " very soft, with a wide back to support your hip joints and a" + + " cutout in the center to redistribute that pressure. Rim brakes" + + " deliver satisfactory braking control, and the wide tires provide" + + " a smooth, stable ride on paved roads and gravel. Rack and fender" + + " mounts facilitate setting up the Roll Low-Entry as your preferred" + + " commuter, and the BMX-like handlebar offers space for mounting a" + + " flashlight, bell, or phone holder.", + condition = "new", + }, + new + { + brand = "nHill", + model = "Summit", + price = 1200, + description = "This budget mountain bike from nHill performs well both on bike" + + " paths and on the trail. The fork with 100mm of travel absorbs" + + " rough terrain. Fat Kenda Booster tires give you grip in corners" + + " and on wet trails. The Shimano Tourney drivetrain offered enough" + + " gears for finding a comfortable pace to ride uphill, and the" + + " Tektro hydraulic disc brakes break smoothly. Whether you want an" + + " affordable bike that you can take to work, but also take trail in" + + " mountains on the weekends or you’re just after a stable," + + " comfortable ride for the bike path, the Summit gives a good value" + + " for money.", + condition = "new", + }, + new + { + model = "ThrillCycle", + brand = "BikeShind", + price = 815, + description = "An artsy, retro-inspired bicycle that’s as functional as it is" + + " pretty: The ThrillCycle steel frame offers a smooth ride. A" + + " 9-speed drivetrain has enough gears for coasting in the city, but" + + " we wouldn’t suggest taking it to the mountains. Fenders protect" + + " you from mud, and a rear basket lets you transport groceries," + + " flowers and books. The ThrillCycle comes with a limited lifetime" + + " warranty, so this little guy will last you long past graduation.", + condition = "refurbished", + }, + }; + + for (var i = 0; i < bicycles.Length; i++) + { + db.JSON().Set($"bicycle:{i}", "$", bicycles[i]); + } + // HIDE_END + + + // STEP_START ft1 + SearchResult res1 = db.FT().Search( + "idx:bicycle", + new Query("@description: kids") + ); + Console.WriteLine(res1); // >>> 2 + // STEP_END + + // Tests for 'ft1' step. + // REMOVE_START + Assert.Equal(2, res1.TotalResults); + // REMOVE_END + + + // STEP_START ft2 + SearchResult res2 = db.FT().Search( + "idx:bicycle", + new Query("@model: ka*") + ); + Console.WriteLine(res2.TotalResults); // >>> 1 + // STEP_END + + // Tests for 'ft2' step. + // REMOVE_START + Assert.Equal(1, res2.TotalResults); + // REMOVE_END + + + // STEP_START ft3 + SearchResult res3 = db.FT().Search( + "idx:bicycle", + new Query("@brand: *bikes") + ); + Console.WriteLine(res3.TotalResults); // >>> 2 + // STEP_END + + // Tests for 'ft3' step. + // REMOVE_START + Assert.Equal(2, res3.TotalResults); + // REMOVE_END + + + // STEP_START ft4 + SearchResult res4 = db.FT().Search( + "idx:bicycle", + new Query("%optamized%") + ); + Console.WriteLine(res4.TotalResults); // >>> 1 + // STEP_END + + // Tests for 'ft4' step. + // REMOVE_START + Assert.Equal(1, res4.TotalResults); + // REMOVE_END + + + // STEP_START ft5 + SearchResult res5 = db.FT().Search( + "idx:bicycle", + new Query("%%optamised%%") + ); + Console.WriteLine(res5.TotalResults); // >>> 1 + // STEP_END + + // Tests for 'ft5' step. + // REMOVE_START + Assert.Equal(1, res5.TotalResults); + // REMOVE_END + + + // HIDE_START + } +} +// HIDE_END + From cb6d6850304bce0c315696ed42162e9da8bf3413 Mon Sep 17 00:00:00 2001 From: andy-stark-redis <164213578+andy-stark-redis@users.noreply.github.com> Date: Fri, 27 Sep 2024 14:21:23 +0100 Subject: [PATCH 2/8] DOC-4243 added range query examples (#338) * DOC-4243 added range query examples * DOC-4243 implemented PR feedback * DOC-4243 reinstated filter example using infinity --- tests/Doc/QueryRangeExample.cs | 273 +++++++++++++++++++++++++++++++++ 1 file changed, 273 insertions(+) create mode 100644 tests/Doc/QueryRangeExample.cs diff --git a/tests/Doc/QueryRangeExample.cs b/tests/Doc/QueryRangeExample.cs new file mode 100644 index 00000000..44755930 --- /dev/null +++ b/tests/Doc/QueryRangeExample.cs @@ -0,0 +1,273 @@ +// EXAMPLE: query_range +// HIDE_START + +using NRedisStack.RedisStackCommands; +using NRedisStack.Search; +using NRedisStack.Search.Literals.Enums; +using NRedisStack.Tests; +using StackExchange.Redis; + +// HIDE_END + +// REMOVE_START +namespace Doc; +[Collection("DocsTests")] +// REMOVE_END + +// HIDE_START +public class QueryRangeExample +{ + + [SkipIfRedis(Is.OSSCluster)] + public void run() + { + var muxer = ConnectionMultiplexer.Connect("localhost:6379"); + var db = muxer.GetDatabase(); + //REMOVE_START + // Clear any keys here before using them in tests. + try { db.FT().DropIndex("idx:bicycle", dd: true); } catch { } + //REMOVE_END + + Schema bikeSchema = new Schema() + .AddTextField(new FieldName("$.description", "description")) + .AddNumericField(new FieldName("$.price", "price")) + .AddTagField(new FieldName("$.condition", "condition")); + + FTCreateParams bikeParams = new FTCreateParams() + .AddPrefix("bicycle:") + .On(IndexDataType.JSON); + + db.FT().Create("idx:bicycle", bikeParams, bikeSchema); + + var bicycles = new object[] + { + new + { + brand = "Velorim", + model = "Jigger", + price = 270, + 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 " + + "choice for the rare tenacious little rider " + + "raring to go.", + condition = "used" + }, + new + { + brand = "Bicyk", + model = "Hillcraft", + price = 1200, + description = "Kids want to ride with as little weight as possible." + + " Especially on an incline! They may be at the age " + + "when a 27.5 inch wheel bike is just too clumsy coming " + + "off a 24 inch bike. The Hillcraft 26 is just the solution" + + " they need!", + condition = "used", + }, + new + { + brand = "Nord", + model = "Chook air 5", + price = 815, + description = "The Chook Air 5 gives kids aged six years and older " + + "a durable and uberlight mountain bike for their first" + + " experience on tracks and easy cruising through forests" + + " and fields. The lower top tube makes it easy to mount" + + " and dismount in any situation, giving your kids greater" + + " safety on the trails.", + condition = "used", + }, + new + { + brand = "Eva", + model = "Eva 291", + price = 3400, + description = "The sister company to Nord, Eva launched in 2005 as the" + + " first and only women-dedicated bicycle brand. Designed" + + " by women for women, allEva bikes are optimized for the" + + " feminine physique using analytics from a body metrics" + + " database. If you like 29ers, try the Eva 291. It’s a " + + "brand new bike for 2022.. This full-suspension, " + + "cross-country ride has been designed for velocity. The" + + " 291 has 100mm of front and rear travel, a superlight " + + "aluminum frame and fast-rolling 29-inch wheels. Yippee!", + condition = "used", + }, + new + { + brand = "Noka Bikes", + model = "Kahuna", + price = 3200, + description = "Whether you want to try your hand at XC racing or are " + + "looking for a lively trail bike that's just as inspiring" + + " on the climbs as it is over rougher ground, the Wilder" + + " is one heck of a bike built specifically for short women." + + " Both the frames and components have been tweaked to " + + "include a women’s saddle, different bars and unique " + + "colourway.", + condition = "used", + }, + new + { + brand = "Breakout", + model = "XBN 2.1 Alloy", + price = 810, + description = "The XBN 2.1 Alloy is our entry-level road bike – but that’s" + + " not to say that it’s a basic machine. With an internal " + + "weld aluminium frame, a full carbon fork, and the slick-shifting" + + " Claris gears from Shimano’s, this is a bike which doesn’t" + + " break the bank and delivers craved performance.", + condition = "new", + }, + new + { + brand = "ScramBikes", + model = "WattBike", + price = 2300, + description = "The WattBike is the best e-bike for people who still feel young" + + " at heart. It has a Bafang 1000W mid-drive system and a 48V" + + " 17.5AH Samsung Lithium-Ion battery, allowing you to ride for" + + " more than 60 miles on one charge. It’s great for tackling hilly" + + " terrain or if you just fancy a more leisurely ride. With three" + + " working modes, you can choose between E-bike, assisted bicycle," + + " and normal bike modes.", + condition = "new", + }, + new + { + brand = "Peaknetic", + model = "Secto", + price = 430, + description = "If you struggle with stiff fingers or a kinked neck or back after" + + " a few minutes on the road, this lightweight, aluminum bike" + + " alleviates those issues and allows you to enjoy the ride. From" + + " the ergonomic grips to the lumbar-supporting seat position, the" + + " Roll Low-Entry offers incredible comfort. The rear-inclined seat" + + " tube facilitates stability by allowing you to put a foot on the" + + " ground to balance at a stop, and the low step-over frame makes it" + + " accessible for all ability and mobility levels. The saddle is" + + " very soft, with a wide back to support your hip joints and a" + + " cutout in the center to redistribute that pressure. Rim brakes" + + " deliver satisfactory braking control, and the wide tires provide" + + " a smooth, stable ride on paved roads and gravel. Rack and fender" + + " mounts facilitate setting up the Roll Low-Entry as your preferred" + + " commuter, and the BMX-like handlebar offers space for mounting a" + + " flashlight, bell, or phone holder.", + condition = "new", + }, + new + { + brand = "nHill", + model = "Summit", + price = 1200, + description = "This budget mountain bike from nHill performs well both on bike" + + " paths and on the trail. The fork with 100mm of travel absorbs" + + " rough terrain. Fat Kenda Booster tires give you grip in corners" + + " and on wet trails. The Shimano Tourney drivetrain offered enough" + + " gears for finding a comfortable pace to ride uphill, and the" + + " Tektro hydraulic disc brakes break smoothly. Whether you want an" + + " affordable bike that you can take to work, but also take trail in" + + " mountains on the weekends or you’re just after a stable," + + " comfortable ride for the bike path, the Summit gives a good value" + + " for money.", + condition = "new", + }, + new + { + model = "ThrillCycle", + brand = "BikeShind", + price = 815, + description = "An artsy, retro-inspired bicycle that’s as functional as it is" + + " pretty: The ThrillCycle steel frame offers a smooth ride. A" + + " 9-speed drivetrain has enough gears for coasting in the city, but" + + " we wouldn’t suggest taking it to the mountains. Fenders protect" + + " you from mud, and a rear basket lets you transport groceries," + + " flowers and books. The ThrillCycle comes with a limited lifetime" + + " warranty, so this little guy will last you long past graduation.", + condition = "refurbished", + }, + }; + + for (var i = 0; i < bicycles.Length; i++) + { + db.JSON().Set($"bicycle:{i}", "$", bicycles[i]); + } + // HIDE_END + + + // STEP_START range1 + SearchResult res1 = db.FT().Search( + "idx:bicycle", + new Query("@price:[500 1000]") + ); + Console.WriteLine(res1.TotalResults); // >>> 3 + // STEP_END + + // Tests for 'range1' step. + // REMOVE_START + Assert.Equal(3, res1.TotalResults); + // REMOVE_END + + + // STEP_START range2 + SearchResult res2 = db.FT().Search( + "idx:bicycle", + new Query().AddFilter( + new Query.NumericFilter("price", 500, 1000) + ) + ); + Console.WriteLine(res2.TotalResults); // >>> 3 + // STEP_END + + // Tests for 'range2' step. + // REMOVE_START + Assert.Equal(3, res2.TotalResults); + // REMOVE_END + + + // STEP_START range3 + SearchResult res3 = db.FT().Search( + "idx:bicycle", + new Query("*").AddFilter(new Query.NumericFilter( + "price", 1000, true, Double.PositiveInfinity, false + ) + ) + ); + Console.WriteLine(res3.TotalResults); // >>> 5 + // STEP_END + + // Tests for 'range3' step. + // REMOVE_START + Assert.Equal(5, res3.TotalResults); + // REMOVE_END + + + // STEP_START range4 + SearchResult res4 = db.FT().Search( + "idx:bicycle", + new Query("@price:[-inf 2000]") + .SetSortBy("price") + .Limit(0, 5) + ); + Console.WriteLine(res4.TotalResults); // >>> 7 + Console.WriteLine($"Prices: {string.Join(", ", res4.Documents.Select(d => d["price"]))}"); + // >>> Prices: 270, 430, 810, 815, 815 + // STEP_END + + // Tests for 'range4' step. + // REMOVE_START + Assert.Equal(7, res4.TotalResults); + Assert.Equal( + "Prices: 270, 430, 810, 815, 815", + $"Prices: {string.Join(", ", res4.Documents.Select(d => d["price"]))}" + ); + // REMOVE_END + + + // HIDE_START + } +} +// HIDE_END + From 7f93841015cf6ebc4e39c13d251cbd707383a7ef Mon Sep 17 00:00:00 2001 From: andy-stark-redis <164213578+andy-stark-redis@users.noreply.github.com> Date: Fri, 27 Sep 2024 23:09:43 +0100 Subject: [PATCH 3/8] DOC-4295 added aggregate query examples (#341) * DOC-4295 added aggregate query examples * DOC-4295 added try-catch around dropIndex call * DOC-4295 fixed non-deterministic tests * DOC-4295 replaced dodgy agg4 example for examination * DOC-4295 reinstated missing example message --- tests/Doc/QueryAggExample.cs | 327 +++++++++++++++++++++++++++++++++++ 1 file changed, 327 insertions(+) create mode 100644 tests/Doc/QueryAggExample.cs diff --git a/tests/Doc/QueryAggExample.cs b/tests/Doc/QueryAggExample.cs new file mode 100644 index 00000000..ec5f696d --- /dev/null +++ b/tests/Doc/QueryAggExample.cs @@ -0,0 +1,327 @@ +// EXAMPLE: query_agg +// HIDE_START + +using NRedisStack.RedisStackCommands; +using NRedisStack.Search; +using NRedisStack.Search.Aggregation; +using NRedisStack.Search.Literals.Enums; +using NRedisStack.Tests; +using StackExchange.Redis; + +// HIDE_END + +// REMOVE_START +namespace Doc; +[Collection("DocsTests")] +// REMOVE_END + +// HIDE_START +public class QueryAggExample +{ + + [SkipIfRedis(Is.OSSCluster)] + public void run() + { + var muxer = ConnectionMultiplexer.Connect("localhost:6379"); + var db = muxer.GetDatabase(); + //REMOVE_START + // Clear any keys here before using them in tests. + try { db.FT().DropIndex("idx:bicycle"); } catch { } + //REMOVE_END + + Schema bikeSchema = new Schema() + .AddTagField(new FieldName("$.condition", "condition")) + .AddNumericField(new FieldName("$.price", "price")); + + FTCreateParams bikeParams = new FTCreateParams() + .AddPrefix("bicycle:") + .On(IndexDataType.JSON); + + db.FT().Create("idx:bicycle", bikeParams, bikeSchema); + + var bicycles = new object[] { + new + { + pickup_zone = "POLYGON((-74.0610 40.7578, -73.9510 40.7578, -73.9510 40.6678, -74.0610 40.6678, -74.0610 40.7578))", + store_location = "-74.0060,40.7128", + brand = "Velorim", + model = "Jigger", + price = 270, + 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 choice for the rare tenacious little rider raring to go.", + condition = "new" + }, + new + { + pickup_zone = "POLYGON((-118.2887 34.0972, -118.1987 34.0972, -118.1987 33.9872, -118.2887 33.9872, -118.2887 34.0972))", + store_location = "-118.2437,34.0522", + brand = "Bicyk", + model = "Hillcraft", + price = 1200, + description = "Kids want to ride with as little weight as possible. Especially on an incline! They may be at the age when a 27.5\" wheel bike is just too clumsy coming off a 24\" bike. The Hillcraft 26 is just the solution they need!", + condition = "used" + }, + new + { + pickup_zone = "POLYGON((-87.6848 41.9331, -87.5748 41.9331, -87.5748 41.8231, -87.6848 41.8231, -87.6848 41.9331))", + store_location = "-87.6298,41.8781", + brand = "Nord", + model = "Chook air 5", + price = 815, + description = "The Chook Air 5 gives kids aged six years and older a durable and uberlight mountain bike for their first experience on tracks and easy cruising through forests and fields. The lower top tube makes it easy to mount and dismount in any situation, giving your kids greater safety on the trails.", + condition = "used" + }, + new + { + pickup_zone = "POLYGON((-80.2433 25.8067, -80.1333 25.8067, -80.1333 25.6967, -80.2433 25.6967, -80.2433 25.8067))", + store_location = "-80.1918,25.7617", + brand = "Eva", + model = "Eva 291", + price = 3400, + description = "The sister company to Nord, Eva launched in 2005 as the first and only women-dedicated bicycle brand. Designed by women for women, allEva bikes are optimized for the feminine physique using analytics from a body metrics database. If you like 29ers, try the Eva 291. It’s a brand new bike for 2022.. This full-suspension, cross-country ride has been designed for velocity. The 291 has 100mm of front and rear travel, a superlight aluminum frame and fast-rolling 29-inch wheels. Yippee!", + condition = "used" + }, + new + { + pickup_zone = "POLYGON((-122.4644 37.8199, -122.3544 37.8199, -122.3544 37.7099, -122.4644 37.7099, -122.4644 37.8199))", + store_location = "-122.4194,37.7749", + brand = "Noka Bikes", + model = "Kahuna", + price = 3200, + description = "Whether you want to try your hand at XC racing or are looking for a lively trail bike that's just as inspiring on the climbs as it is over rougher ground, the Wilder is one heck of a bike built specifically for short women. Both the frames and components have been tweaked to include a women’s saddle, different bars and unique colourway.", + condition = "used" + }, + new + { + pickup_zone = "POLYGON((-0.1778 51.5524, 0.0822 51.5524, 0.0822 51.4024, -0.1778 51.4024, -0.1778 51.5524))", + store_location = "-0.1278,51.5074", + brand = "Breakout", + model = "XBN 2.1 Alloy", + price = 810, + description = "The XBN 2.1 Alloy is our entry-level road bike – but that’s not to say that it’s a basic machine. With an internal weld aluminium frame, a full carbon fork, and the slick-shifting Claris gears from Shimano’s, this is a bike which doesn’t break the bank and delivers craved performance.", + condition = "new" + }, + new + { + pickup_zone = "POLYGON((2.1767 48.9016, 2.5267 48.9016, 2.5267 48.5516, 2.1767 48.5516, 2.1767 48.9016))", + store_location = "2.3522,48.8566", + brand = "ScramBikes", + model = "WattBike", + price = 2300, + description = "The WattBike is the best e-bike for people who still feel young at heart. It has a Bafang 1000W mid-drive system and a 48V 17.5AH Samsung Lithium-Ion battery, allowing you to ride for more than 60 miles on one charge. It’s great for tackling hilly terrain or if you just fancy a more leisurely ride. With three working modes, you can choose between E-bike, assisted bicycle, and normal bike modes.", + condition = "new" + }, + new + { + pickup_zone = "POLYGON((13.3260 52.5700, 13.6550 52.5700, 13.6550 52.2700, 13.3260 52.2700, 13.3260 52.5700))", + store_location = "13.4050,52.5200", + brand = "Peaknetic", + model = "Secto", + price = 430, + description = "If you struggle with stiff fingers or a kinked neck or back after a few minutes on the road, this lightweight, aluminum bike alleviates those issues and allows you to enjoy the ride. From the ergonomic grips to the lumbar-supporting seat position, the Roll Low-Entry offers incredible comfort. The rear-inclined seat tube facilitates stability by allowing you to put a foot on the ground to balance at a stop, and the low step-over frame makes it accessible for all ability and mobility levels. The saddle is very soft, with a wide back to support your hip joints and a cutout in the center to redistribute that pressure. Rim brakes deliver satisfactory braking control, and the wide tires provide a smooth, stable ride on paved roads and gravel. Rack and fender mounts facilitate setting up the Roll Low-Entry as your preferred commuter, and the BMX-like handlebar offers space for mounting a flashlight, bell, or phone holder.", + condition = "new" + }, + new + { + pickup_zone = "POLYGON((1.9450 41.4301, 2.4018 41.4301, 2.4018 41.1987, 1.9450 41.1987, 1.9450 41.4301))", + store_location = "2.1734, 41.3851", + brand = "nHill", + model = "Summit", + price = 1200, + description = "This budget mountain bike from nHill performs well both on bike paths and on the trail. The fork with 100mm of travel absorbs rough terrain. Fat Kenda Booster tires give you grip in corners and on wet trails. The Shimano Tourney drivetrain offered enough gears for finding a comfortable pace to ride uphill, and the Tektro hydraulic disc brakes break smoothly. Whether you want an affordable bike that you can take to work, but also take trail in mountains on the weekends or you’re just after a stable, comfortable ride for the bike path, the Summit gives a good value for money.", + condition = "new" + }, + new + { + pickup_zone = "POLYGON((12.4464 42.1028, 12.5464 42.1028, 12.5464 41.7028, 12.4464 41.7028, 12.4464 42.1028))", + store_location = "12.4964,41.9028", + model = "ThrillCycle", + brand = "BikeShind", + price = 815, + description = "An artsy, retro-inspired bicycle that’s as functional as it is pretty: The ThrillCycle steel frame offers a smooth ride. A 9-speed drivetrain has enough gears for coasting in the city, but we wouldn’t suggest taking it to the mountains. Fenders protect you from mud, and a rear basket lets you transport groceries, flowers and books. The ThrillCycle comes with a limited lifetime warranty, so this little guy will last you long past graduation.", + condition = "refurbished" + } + }; + + for (var i = 0; i < bicycles.Length; i++) + { + db.JSON().Set($"bicycle:{i}", "$", bicycles[i]); + } + // HIDE_END + + + // STEP_START agg1 + AggregationResult res1 = db.FT().Aggregate( + "idx:bicycle", + new AggregationRequest("@condition:{new}") + .Load(new FieldName("__key"), new FieldName("price")) + .Apply("@price - (@price * 0.1)", "discounted") + ); + Console.WriteLine(res1.TotalResults); // >>> 5 + + for (int i = 0; i < res1.TotalResults; i++) + { + Row res1Row = res1.GetRow(i); + + Console.WriteLine( + $"Key: {res1Row["__key"]}, Price: {res1Row["price"]}, Discounted: {res1Row["discounted"]}" + ); + } + // >>> Key: bicycle:0, Price: 270, Discounted: 243 + // >>> Key: bicycle:5, Price: 810, Discounted: 729 + // >>> Key: bicycle:6, Price: 2300, Discounted: 2070 + // >>> Key: bicycle:7, Price: 430, Discounted: 387 + // >>> Key: bicycle:8, Price: 1200, Discounted: 1080 + // STEP_END + + // Tests for 'agg1' step. + // REMOVE_START + Assert.Equal(5, res1.TotalResults); + + for (int i = 0; i < 5; i++) + { + Row test1Row = res1.GetRow(i); + + switch (test1Row["__key"]) + { + case "bicycle:0": + Assert.Equal( + "Key: bicycle:0, Price: 270, Discounted: 243", + $"Key: {test1Row["__key"]}, Price: {test1Row["price"]}, Discounted: {test1Row["discounted"]}" + ); + break; + + case "bicycle:5": + Assert.Equal( + "Key: bicycle:5, Price: 810, Discounted: 729", + $"Key: {test1Row["__key"]}, Price: {test1Row["price"]}, Discounted: {test1Row["discounted"]}" + ); + break; + + case "bicycle:6": + Assert.Equal( + "Key: bicycle:6, Price: 2300, Discounted: 2070", + $"Key: {test1Row["__key"]}, Price: {test1Row["price"]}, Discounted: {test1Row["discounted"]}" + ); + break; + + case "bicycle:7": + Assert.Equal( + "Key: bicycle:7, Price: 430, Discounted: 387", + $"Key: {test1Row["__key"]}, Price: {test1Row["price"]}, Discounted: {test1Row["discounted"]}" + ); + break; + + case "bicycle:8": + Assert.Equal( + "Key: bicycle:8, Price: 1200, Discounted: 1080", + $"Key: {test1Row["__key"]}, Price: {test1Row["price"]}, Discounted: {test1Row["discounted"]}" + ); + break; + } + } + + // REMOVE_END + + + // STEP_START agg2 + AggregationResult res2 = db.FT().Aggregate( + "idx:bicycle", + new AggregationRequest("*") + .Load(new FieldName("price")) + .Apply("@price<1000", "price_category") + .GroupBy( + "@condition", + Reducers.Sum("@price_category").As("num_affordable") + ) + ); + Console.WriteLine(res2.TotalResults); // >>> 3 + + for (int i = 0; i < res2.TotalResults; i++) + { + Row res2Row = res2.GetRow(i); + + Console.WriteLine( + $"Condition: {res2Row["condition"]}, Num affordable: {res2Row["num_affordable"]}" + ); + } + // >>> Condition: refurbished, Num affordable: 1 + // >>> Condition: used, Num affordable: 1 + // >>> Condition: new, Num affordable: 3 + // STEP_END + + // Tests for 'agg2' step. + // REMOVE_START + Assert.Equal(3, res2.TotalResults); + + for (int i = 0; i < 3; i++) + { + Row test2Row = res2.GetRow(i); + switch (test2Row["condition"]) + { + case "refurbished": + Assert.Equal( + "Condition: refurbished, Num affordable: 1", + $"Condition: {test2Row["condition"]}, Num affordable: {test2Row["num_affordable"]}" + ); + break; + + case "used": + Assert.Equal( + "Condition: used, Num affordable: 1", + $"Condition: {test2Row["condition"]}, Num affordable: {test2Row["num_affordable"]}" + ); + break; + + case "new": + Assert.Equal( + "Condition: new, Num affordable: 3", + $"Condition: {test2Row["condition"]}, Num affordable: {test2Row["num_affordable"]}" + ); + break; + } + } + // REMOVE_END + + + // STEP_START agg3 + AggregationResult res3 = db.FT().Aggregate( + "idx:bicycle", + new AggregationRequest("*") + .Apply("'bicycle'", "type") + .GroupBy("@type", Reducers.Count().As("num_total")) + ); + Console.WriteLine(res3.TotalResults); // >>> 1 + + Row res3Row = res3.GetRow(0); + Console.WriteLine($"Type: {res3Row["type"]}, Num total: {res3Row["num_total"]}"); + // >>> Type: bicycle, Num total: 10 + // STEP_END + + // Tests for 'agg3' step. + // REMOVE_START + Assert.Equal(1, res3.TotalResults); + + Assert.Equal( + "Type: bicycle, Num total: 10", + $"Type: {res3Row["type"]}, Num total: {res3Row["num_total"]}" + ); + // REMOVE_END + + + // STEP_START agg4 + + // Not supported in NRedisStack. + + // STEP_END + + // Tests for 'agg4' step. + // REMOVE_START + + // REMOVE_END + + + // HIDE_START + } +} +// HIDE_END + From 0a8bdfae97c5a18ca178e00bc387f3981d7c5790 Mon Sep 17 00:00:00 2001 From: andy-stark-redis <164213578+andy-stark-redis@users.noreply.github.com> Date: Mon, 30 Sep 2024 10:16:31 +0100 Subject: [PATCH 4/8] DOC-4201 added exact match query examples (#337) * DOC-4201 added exact match query examples * DOC-4201 dotnet format changes * DOC-4201 removed unused 'using' statements * DOC-4201 fixed email tag example --------- Co-authored-by: atakavci <58048133+atakavci@users.noreply.github.com> --- tests/Doc/QueryEmExample.cs | 284 ++++++++++++++++++++++++++++++++++++ 1 file changed, 284 insertions(+) create mode 100644 tests/Doc/QueryEmExample.cs diff --git a/tests/Doc/QueryEmExample.cs b/tests/Doc/QueryEmExample.cs new file mode 100644 index 00000000..590a212d --- /dev/null +++ b/tests/Doc/QueryEmExample.cs @@ -0,0 +1,284 @@ +// EXAMPLE: query_em +// HIDE_START + +using NRedisStack.RedisStackCommands; +using NRedisStack.Search; +using NRedisStack.Search.Literals.Enums; +using NRedisStack.Tests; +using StackExchange.Redis; + +// HIDE_END + +// REMOVE_START +namespace Doc; +[Collection("DocsTests")] +// REMOVE_END + +// HIDE_START +public class QueryEmExample +{ + + [SkipIfRedis(Is.OSSCluster)] + public void run() + { + var muxer = ConnectionMultiplexer.Connect("localhost:6379"); + var db = muxer.GetDatabase(); + //REMOVE_START + // Clear any keys here before using them in tests. + try { db.FT().DropIndex("idx:bicycle"); } catch { } + try { db.FT().DropIndex("idx:email"); } catch { } + //REMOVE_END + + FTCreateParams idxParams = new FTCreateParams() + .AddPrefix("bicycle:") + .On(IndexDataType.JSON); + + Schema bikeSchema = new Schema() + .AddTextField(new FieldName("$.description", "description")) + .AddNumericField(new FieldName("$.price", "price")) + .AddTagField(new FieldName("$.condition", "condition")); + + db.FT().Create("idx:bicycle", idxParams, bikeSchema); + + + var bicycles = new object[] + { + new + { + brand = "Velorim", + model = "Jigger", + price = 270, + 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 " + + "choice for the rare tenacious little rider " + + "raring to go.", + condition = "used" + }, + new + { + brand = "Bicyk", + model = "Hillcraft", + price = 1200, + description = "Kids want to ride with as little weight as possible." + + " Especially on an incline! They may be at the age " + + "when a 27.5 inch wheel bike is just too clumsy coming " + + "off a 24 inch bike. The Hillcraft 26 is just the solution" + + " they need!", + condition = "used", + }, + new + { + brand = "Nord", + model = "Chook air 5", + price = 815, + description = "The Chook Air 5 gives kids aged six years and older " + + "a durable and uberlight mountain bike for their first" + + " experience on tracks and easy cruising through forests" + + " and fields. The lower top tube makes it easy to mount" + + " and dismount in any situation, giving your kids greater" + + " safety on the trails.", + condition = "used", + }, + new + { + brand = "Eva", + model = "Eva 291", + price = 3400, + description = "The sister company to Nord, Eva launched in 2005 as the" + + " first and only women-dedicated bicycle brand. Designed" + + " by women for women, allEva bikes are optimized for the" + + " feminine physique using analytics from a body metrics" + + " database. If you like 29ers, try the Eva 291. It’s a " + + "brand new bike for 2022.. This full-suspension, " + + "cross-country ride has been designed for velocity. The" + + " 291 has 100mm of front and rear travel, a superlight " + + "aluminum frame and fast-rolling 29-inch wheels. Yippee!", + condition = "used", + }, + new + { + brand = "Noka Bikes", + model = "Kahuna", + price = 3200, + description = "Whether you want to try your hand at XC racing or are " + + "looking for a lively trail bike that's just as inspiring" + + " on the climbs as it is over rougher ground, the Wilder" + + " is one heck of a bike built specifically for short women." + + " Both the frames and components have been tweaked to " + + "include a women’s saddle, different bars and unique " + + "colourway.", + condition = "used", + }, + new + { + brand = "Breakout", + model = "XBN 2.1 Alloy", + price = 810, + description = "The XBN 2.1 Alloy is our entry-level road bike – but that’s" + + " not to say that it’s a basic machine. With an internal " + + "weld aluminium frame, a full carbon fork, and the slick-shifting" + + " Claris gears from Shimano’s, this is a bike which doesn’t" + + " break the bank and delivers craved performance.", + condition = "new", + }, + new + { + brand = "ScramBikes", + model = "WattBike", + price = 2300, + description = "The WattBike is the best e-bike for people who still feel young" + + " at heart. It has a Bafang 1000W mid-drive system and a 48V" + + " 17.5AH Samsung Lithium-Ion battery, allowing you to ride for" + + " more than 60 miles on one charge. It’s great for tackling hilly" + + " terrain or if you just fancy a more leisurely ride. With three" + + " working modes, you can choose between E-bike, assisted bicycle," + + " and normal bike modes.", + condition = "new", + }, + new + { + brand = "Peaknetic", + model = "Secto", + price = 430, + description = "If you struggle with stiff fingers or a kinked neck or back after" + + " a few minutes on the road, this lightweight, aluminum bike" + + " alleviates those issues and allows you to enjoy the ride. From" + + " the ergonomic grips to the lumbar-supporting seat position, the" + + " Roll Low-Entry offers incredible comfort. The rear-inclined seat" + + " tube facilitates stability by allowing you to put a foot on the" + + " ground to balance at a stop, and the low step-over frame makes it" + + " accessible for all ability and mobility levels. The saddle is" + + " very soft, with a wide back to support your hip joints and a" + + " cutout in the center to redistribute that pressure. Rim brakes" + + " deliver satisfactory braking control, and the wide tires provide" + + " a smooth, stable ride on paved roads and gravel. Rack and fender" + + " mounts facilitate setting up the Roll Low-Entry as your preferred" + + " commuter, and the BMX-like handlebar offers space for mounting a" + + " flashlight, bell, or phone holder.", + condition = "new", + }, + new + { + brand = "nHill", + model = "Summit", + price = 1200, + description = "This budget mountain bike from nHill performs well both on bike" + + " paths and on the trail. The fork with 100mm of travel absorbs" + + " rough terrain. Fat Kenda Booster tires give you grip in corners" + + " and on wet trails. The Shimano Tourney drivetrain offered enough" + + " gears for finding a comfortable pace to ride uphill, and the" + + " Tektro hydraulic disc brakes break smoothly. Whether you want an" + + " affordable bike that you can take to work, but also take trail in" + + " mountains on the weekends or you’re just after a stable," + + " comfortable ride for the bike path, the Summit gives a good value" + + " for money.", + condition = "new", + }, + new + { + model = "ThrillCycle", + brand = "BikeShind", + price = 815, + description = "An artsy, retro-inspired bicycle that’s as functional as it is" + + " pretty: The ThrillCycle steel frame offers a smooth ride. A" + + " 9-speed drivetrain has enough gears for coasting in the city, but" + + " we wouldn’t suggest taking it to the mountains. Fenders protect" + + " you from mud, and a rear basket lets you transport groceries," + + " flowers and books. The ThrillCycle comes with a limited lifetime" + + " warranty, so this little guy will last you long past graduation.", + condition = "refurbished", + }, + }; + + for (var i = 0; i < bicycles.Length; i++) + { + db.JSON().Set($"bicycle:{i}", "$", bicycles[i]); + } + // HIDE_END + + + // STEP_START em1 + SearchResult res1 = db.FT().Search( + "idx:bicycle", + new Query("@price:[270 270]") + ); + Console.WriteLine(res1.TotalResults); // >>> 1 + + SearchResult res2 = db.FT().Search( + "idx:bicycle", + new Query().AddFilter( + new Query.NumericFilter("price", 270, 270) + ) + ); + Console.WriteLine(res2.TotalResults); // >>> 1 + // STEP_END + + // Tests for 'em1' step. + // REMOVE_START + Assert.Equal(1, res1.TotalResults); + Assert.Equal(1, res2.TotalResults); + // REMOVE_END + + + // STEP_START em2 + SearchResult res3 = db.FT().Search( + "idx:bicycle", + new Query("@condition:{new}") + ); + Console.WriteLine(res3.TotalResults); // >>> 4 + // STEP_END + + // Tests for 'em2' step. + // REMOVE_START + Assert.Equal(4, res3.TotalResults); + // REMOVE_END + + + // STEP_START em3 + Schema emailSchema = new Schema() + .AddTagField(new FieldName("$.email", "email")); + + FTCreateParams emailParams = new FTCreateParams() + .AddPrefix("key:") + .On(IndexDataType.JSON); + + db.FT().Create("idx:email", emailParams, emailSchema); + + db.JSON().Set("key:1", "$", "{\"email\": \"test@redis.com\"}"); + + + SearchResult res4 = db.FT().Search( + "idx:email", + new Query("@email:{test\\@redis\\.com}").Dialect(2) + ); + Console.WriteLine(res4.TotalResults); // >>> 1 + // STEP_END + + // Tests for 'em3' step. + // REMOVE_START + db.FT().DropIndex("idx:email"); + Assert.Equal(1, res4.TotalResults); + // REMOVE_END + + + // STEP_START em4 + SearchResult res5 = db.FT().Search( + "idx:bicycle", + new Query("@description:\"rough terrain\"") + ); + Console.WriteLine(res5.TotalResults); // >>> 1 + // STEP_END + + // Tests for 'em4' step. + // REMOVE_START + Assert.Equal(1, res5.TotalResults); + // REMOVE_END + + + // HIDE_START + } +} +// HIDE_END + From 0171221a5911841084a6ba1655cd72e19cadea43 Mon Sep 17 00:00:00 2001 From: atakavci <58048133+atakavci@users.noreply.github.com> Date: Tue, 1 Oct 2024 13:31:08 +0300 Subject: [PATCH 5/8] Deprecate Triggers and Functions (#343) deprecate T&F --- src/NRedisStack/Gears/GearsCommandBuilder.cs | 5 + src/NRedisStack/Gears/GearsCommands.cs | 7 +- src/NRedisStack/Gears/GearsCommandsAsync.cs | 5 + tests/NRedisStack.Tests/Gears/GearsTests.cs | 210 ------------------- 4 files changed, 16 insertions(+), 211 deletions(-) delete mode 100644 tests/NRedisStack.Tests/Gears/GearsTests.cs diff --git a/src/NRedisStack/Gears/GearsCommandBuilder.cs b/src/NRedisStack/Gears/GearsCommandBuilder.cs index 5af745ba..8dec9026 100644 --- a/src/NRedisStack/Gears/GearsCommandBuilder.cs +++ b/src/NRedisStack/Gears/GearsCommandBuilder.cs @@ -3,8 +3,10 @@ namespace NRedisStack { + [Obsolete] public static class GearsCommandBuilder { + [Obsolete] public static SerializedCommand TFunctionLoad(string libraryCode, bool replace = false, string? config = null) { var args = new List() { GearsArgs.LOAD }; @@ -23,11 +25,13 @@ public static SerializedCommand TFunctionLoad(string libraryCode, bool replace = return new SerializedCommand(RG.TFUNCTION, args); } + [Obsolete] public static SerializedCommand TFunctionDelete(string libraryName) { return new SerializedCommand(RG.TFUNCTION, GearsArgs.DELETE, libraryName); } + [Obsolete] public static SerializedCommand TFunctionList(bool withCode = false, int verbose = 0, string? libraryName = null) { var args = new List() { GearsArgs.LIST }; @@ -55,6 +59,7 @@ public static SerializedCommand TFunctionList(bool withCode = false, int verbose return new SerializedCommand(RG.TFUNCTION, args); } + [Obsolete] public static SerializedCommand TFCall(string libraryName, string functionName, string[]? keys = null, string[]? args = null, bool async = false) { string command = async ? RG.TFCALLASYNC : RG.TFCALL; diff --git a/src/NRedisStack/Gears/GearsCommands.cs b/src/NRedisStack/Gears/GearsCommands.cs index b82a1eb2..4787fa86 100644 --- a/src/NRedisStack/Gears/GearsCommands.cs +++ b/src/NRedisStack/Gears/GearsCommands.cs @@ -1,7 +1,7 @@ using StackExchange.Redis; namespace NRedisStack { - + [Obsolete] public static class GearsCommands //: GearsCommandsAsync, IGearsCommands { @@ -17,6 +17,7 @@ public static class GearsCommands //: GearsCommandsAsync, IGearsCommands /// an optional argument, instructs RedisGears to replace the function if its already exists. /// if everything was done correctly, Error otherwise. /// //TODO: check this link when it's available + [Obsolete] public static bool TFunctionLoad(this IDatabase db, string libraryCode, bool replace = false, string? config = null) { return db.Execute(GearsCommandBuilder.TFunctionLoad(libraryCode, replace, config)).OKtoBoolean(); @@ -28,6 +29,7 @@ public static bool TFunctionLoad(this IDatabase db, string libraryCode, bool rep /// the name of the library to delete. /// if the library was deleted successfully, Error otherwise. /// //TODO: check this link when it's available + [Obsolete] public static bool TFunctionDelete(this IDatabase db, string libraryName) { return db.Execute(GearsCommandBuilder.TFunctionDelete(libraryName)).OKtoBoolean(); @@ -42,6 +44,7 @@ public static bool TFunctionDelete(this IDatabase db, string libraryName) /// multiple times to show multiple libraries in a single command) /// Information about the requested libraries. /// //TODO: check this link when it's available + [Obsolete] public static Dictionary[] TFunctionList(this IDatabase db, bool withCode = false, int verbose = 0, string? libraryName = null) { return db.Execute(GearsCommandBuilder.TFunctionList(withCode, verbose, libraryName)).ToDictionarys(); @@ -56,6 +59,7 @@ public static Dictionary[] TFunctionList(this IDatabase db, /// Additional argument to pass to the function. /// The return value from the sync & async function on error in case of failure. /// + [Obsolete] 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)); @@ -70,6 +74,7 @@ public static RedisResult TFCall_(this IDatabase db, string libraryName, string /// Additional argument to pass to the function. /// The return value from the sync & async function on error in case of failure. /// + [Obsolete] 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)); diff --git a/src/NRedisStack/Gears/GearsCommandsAsync.cs b/src/NRedisStack/Gears/GearsCommandsAsync.cs index 076d51bc..3963dfca 100644 --- a/src/NRedisStack/Gears/GearsCommandsAsync.cs +++ b/src/NRedisStack/Gears/GearsCommandsAsync.cs @@ -16,6 +16,7 @@ public static class GearsCommandsAsync //: IGearsCommandsAsync /// an optional argument, instructs RedisGears to replace the function if its already exists. /// if everything was done correctly, Error otherwise. /// //TODO: add link to the command when it's available + [Obsolete] public static async Task TFunctionLoadAsync(this IDatabase db, string libraryCode, string? config = null, bool replace = false) { return (await db.ExecuteAsync(GearsCommandBuilder.TFunctionLoad(libraryCode, replace, config))).OKtoBoolean(); @@ -27,6 +28,7 @@ public static async Task TFunctionLoadAsync(this IDatabase db, string libr /// the name of the library to delete. /// if the library was deleted successfully, Error otherwise. /// //TODO: add link to the command when it's available + [Obsolete] public static async Task TFunctionDeleteAsync(this IDatabase db, string libraryName) { return (await db.ExecuteAsync(GearsCommandBuilder.TFunctionDelete(libraryName))).OKtoBoolean(); @@ -41,6 +43,7 @@ public static async Task TFunctionDeleteAsync(this IDatabase db, string li /// multiple times to show multiple libraries in a single command) /// Information about the requested libraries. /// //TODO: add link to the command when it's available + [Obsolete] public static async Task[]> TFunctionListAsync(this IDatabase db, bool withCode = false, int verbose = 0, string? libraryName = null) { return (await db.ExecuteAsync(GearsCommandBuilder.TFunctionList(withCode, verbose, libraryName))).ToDictionarys(); @@ -55,6 +58,7 @@ public static async Task[]> TFunctionListAsync(t /// Additional argument to pass to the function. /// The return value from the sync & async function on error in case of failure. /// + [Obsolete] 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)); @@ -69,6 +73,7 @@ public async static Task TFCall_Async(this IDatabase db, string lib /// Additional argument to pass to the function. /// The return value from the sync & async function on error in case of failure. /// + [Obsolete] 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)); diff --git a/tests/NRedisStack.Tests/Gears/GearsTests.cs b/tests/NRedisStack.Tests/Gears/GearsTests.cs deleted file mode 100644 index 02a7c474..00000000 --- a/tests/NRedisStack.Tests/Gears/GearsTests.cs +++ /dev/null @@ -1,210 +0,0 @@ -using Xunit; -using StackExchange.Redis; - -namespace NRedisStack.Tests.Gears; - -public class GearsTests : AbstractNRedisStackTest, IDisposable -{ - // private readonly string key = "GEARS_TESTS"; - public GearsTests(RedisFixture redisFixture) : base(redisFixture) { } - - [SkipIfRedis(Is.Enterprise, Comparison.LessThan, "7.1.242")] - public void TestTFunctionLoadDelete() - { - IDatabase db = redisFixture.Redis.GetDatabase(); - if (!redisFixture.isEnterprise) - db.ExecuteBroadcast("REDISGEARS_2.REFRESHCLUSTER"); - db.Execute("FLUSHALL"); - Assert.True(db.TFunctionLoad(GenerateLibCode("lib"))); - Assert.True(db.TFunctionDelete("lib")); - } - - - [SkipIfRedis(Is.Enterprise, Comparison.LessThan, "7.1.242")] - public async Task TestTFunctionLoadDeleteAsync() - { - IDatabase db = redisFixture.Redis.GetDatabase(); - if (!redisFixture.isEnterprise) - db.ExecuteBroadcast("REDISGEARS_2.REFRESHCLUSTER"); - db.Execute("FLUSHALL"); - TryDeleteLib(db, "lib", "lib1", "lib2", "lib3"); - - Assert.True(await db.TFunctionLoadAsync(GenerateLibCode("lib"))); - Assert.True(await db.TFunctionDeleteAsync("lib")); - } - - [SkipIfRedis(Is.Enterprise, Comparison.LessThan, "7.1.242")] - public void TestTFunctionList() - { - IDatabase db = redisFixture.Redis.GetDatabase(); - if (!redisFixture.isEnterprise) - db.ExecuteBroadcast("REDISGEARS_2.REFRESHCLUSTER"); - db.Execute("FLUSHALL"); - TryDeleteLib(db, "lib", "lib1", "lib2", "lib3"); - - Assert.True(db.TFunctionLoad(GenerateLibCode("lib1"))); - Assert.True(db.TFunctionLoad(GenerateLibCode("lib2"))); - Assert.True(db.TFunctionLoad(GenerateLibCode("lib3"))); - - // test error throwing: - Assert.Throws(() => db.TFunctionList(verbose: 8)); - var functions = db.TFunctionList(verbose: 1); - Assert.Equal(3, functions.Length); - - HashSet expectedNames = new HashSet { "lib1", "lib2", "lib3" }; - HashSet actualNames = new HashSet{ - functions[0]["name"].ToString()!, - functions[1]["name"].ToString()!, - functions[2]["name"].ToString()! - }; - - Assert.Equal(expectedNames, actualNames); - - - Assert.True(db.TFunctionDelete("lib1")); - Assert.True(db.TFunctionDelete("lib2")); - Assert.True(db.TFunctionDelete("lib3")); - } - - [SkipIfRedis(Is.Enterprise, Comparison.LessThan, "7.1.242")] - public async Task TestTFunctionListAsync() - { - IDatabase db = redisFixture.Redis.GetDatabase(); - if (!redisFixture.isEnterprise) - db.ExecuteBroadcast("REDISGEARS_2.REFRESHCLUSTER"); - db.Execute("FLUSHALL"); - TryDeleteLib(db, "lib", "lib1", "lib2", "lib3"); - - Assert.True(await db.TFunctionLoadAsync(GenerateLibCode("lib1"))); - Assert.True(await db.TFunctionLoadAsync(GenerateLibCode("lib2"))); - Assert.True(await db.TFunctionLoadAsync(GenerateLibCode("lib3"))); - - var functions = await db.TFunctionListAsync(verbose: 1); - Assert.Equal(3, functions.Length); - - HashSet expectedNames = new HashSet { "lib1", "lib2", "lib3" }; - HashSet actualNames = new HashSet{ - functions[0]["name"].ToString()!, - functions[1]["name"].ToString()!, - functions[2]["name"].ToString()! - }; - - Assert.Equal(expectedNames, actualNames); - - - Assert.True(await db.TFunctionDeleteAsync("lib1")); - Assert.True(await db.TFunctionDeleteAsync("lib2")); - Assert.True(await db.TFunctionDeleteAsync("lib3")); - } - - [SkipIfRedis(Is.Enterprise, Comparison.LessThan, "7.1.242")] - public void TestTFCall() - { - IDatabase db = redisFixture.Redis.GetDatabase(); - if (!redisFixture.isEnterprise) - db.ExecuteBroadcast("REDISGEARS_2.REFRESHCLUSTER"); - db.Execute("FLUSHALL"); - TryDeleteLib(db, "lib", "lib1", "lib2", "lib3"); - - Assert.True(db.TFunctionLoad(GenerateLibCode("lib"))); - Assert.Equal("bar", db.TFCall_("lib", "foo").ToString()); - Assert.Equal("bar", db.TFCallAsync_("lib", "foo").ToString()); - - Assert.True(db.TFunctionDelete("lib")); - } - - [SkipIfRedis(Is.Enterprise, Comparison.LessThan, "7.1.242")] - public async Task TestTFCallAsync() - { - IDatabase db = redisFixture.Redis.GetDatabase(); - if (!redisFixture.isEnterprise) - db.ExecuteBroadcast("REDISGEARS_2.REFRESHCLUSTER"); - db.Execute("FLUSHALL"); - TryDeleteLib(db, "lib", "lib1", "lib2", "lib3"); - - Assert.True(await db.TFunctionLoadAsync(GenerateLibCode("lib"))); - Assert.Equal("bar", (await db.TFCall_Async("lib", "foo")).ToString()); - Assert.Equal("bar", (await db.TFCallAsync_Async("lib", "foo")).ToString()); - - Assert.True(await db.TFunctionDeleteAsync("lib")); - } - - [SkipIfRedis(Is.Enterprise, Comparison.LessThan, "7.1.242")] - public void TestGearsCommandBuilder() - { - // TFunctionLoad: - var buildCommand = GearsCommandBuilder - .TFunctionLoad(GenerateLibCode("lib"), - true, "config"); - var expected = new List - { - "LOAD", - "REPLACE", - "CONFIG", - "config", - GenerateLibCode("lib") - }; - Assert.Equal("TFUNCTION", buildCommand.Command); - Assert.Equal(expected, buildCommand.Args); - - // TFunctionDelete: - buildCommand = GearsCommandBuilder.TFunctionDelete("lib"); - expected = new List - { - "DELETE", - "lib" - }; - Assert.Equal("TFUNCTION", buildCommand.Command); - Assert.Equal(expected, buildCommand.Args); - - // TFunctionList: - buildCommand = GearsCommandBuilder.TFunctionList(true, 2, "lib"); - expected = new List - { - "LIST", - "WITHCODE", - "vv", - "LIBRARY", - "lib", - }; - Assert.Equal("TFUNCTION", buildCommand.Command); - Assert.Equal(expected, buildCommand.Args); - - // TFCall: - var buildSync = GearsCommandBuilder.TFCall("libName", "funcName", new string[] { "key1", "key2" }, new string[] { "arg1", "arg2" }, false); - var buildAsync = GearsCommandBuilder.TFCall("libName", "funcName", new string[] { "key1", "key2" }, new string[] { "arg1", "arg2" }, true); - - expected = new List - { - "libName.funcName", - 2, - "key1", - "key2", - "arg1", - "arg2" - }; - - Assert.Equal("TFCALL", buildSync.Command); - Assert.Equal(expected, buildSync.Args); - - Assert.Equal("TFCALLASYNC", buildAsync.Command); - Assert.Equal(expected, buildAsync.Args); - } - - private static void TryDeleteLib(IDatabase db, params string[] libNames) - { - foreach (var libName in libNames) - { - try - { - db.ExecuteBroadcast(GearsCommandBuilder.TFunctionDelete(libName)); - } - catch (RedisServerException) { } // ignore - } - } - - private static string GenerateLibCode(string libName) - { - return $"#!js api_version=1.0 name={libName}\n redis.registerFunction('foo', ()=>{{return 'bar'}})"; - } -} From 1f08fad70a6418250b9fda3de4a6423a972a0bd9 Mon Sep 17 00:00:00 2001 From: Igor Malinovskiy Date: Mon, 7 Oct 2024 08:55:57 +0200 Subject: [PATCH 6/8] Load Redis test endpoints from config file or env vars (#294) * Load Redis test endpoints from config file or env vars * Fix formatting * add IsTargetConnectionExist to help skipping some tests --------- Co-authored-by: atakavci <58048133+atakavci@users.noreply.github.com> Co-authored-by: atakavci --- .../Core Commands/CoreTests.cs | 4 +- tests/NRedisStack.Tests/RedisFixture.cs | 115 +++++++++++++----- 2 files changed, 87 insertions(+), 32 deletions(-) diff --git a/tests/NRedisStack.Tests/Core Commands/CoreTests.cs b/tests/NRedisStack.Tests/Core Commands/CoreTests.cs index 45856478..cf330786 100644 --- a/tests/NRedisStack.Tests/Core Commands/CoreTests.cs +++ b/tests/NRedisStack.Tests/Core Commands/CoreTests.cs @@ -231,7 +231,7 @@ public void TestBZMPopMultiplexerTimeout() var configurationOptions = new ConfigurationOptions(); configurationOptions.SyncTimeout = 1000; - using var redis = redisFixture.CustomRedis(configurationOptions, out _); + using var redis = redisFixture.GetConnectionById(configurationOptions, "standalone"); var db = redis.GetDatabase(null); db.Execute("FLUSHALL"); @@ -246,7 +246,7 @@ public async Task TestBZMPopMultiplexerTimeoutAsync() var configurationOptions = new ConfigurationOptions(); configurationOptions.SyncTimeout = 1000; - await using var redis = redisFixture.CustomRedis(configurationOptions, out _); + await using var redis = redisFixture.GetConnectionById(configurationOptions, "standalone"); var db = redis.GetDatabase(null); db.Execute("FLUSHALL"); diff --git a/tests/NRedisStack.Tests/RedisFixture.cs b/tests/NRedisStack.Tests/RedisFixture.cs index 81aca9ab..0a145e85 100644 --- a/tests/NRedisStack.Tests/RedisFixture.cs +++ b/tests/NRedisStack.Tests/RedisFixture.cs @@ -1,13 +1,54 @@ using StackExchange.Redis; +using System.Text.Json; namespace NRedisStack.Tests; +public class EndpointConfig +{ + public List? endpoints { get; set; } + + public bool tls { get; set; } + + public string? password { get; set; } + + public int? bdb_id { get; set; } + + public object? raw_endpoints { get; set; } + + public ConnectionMultiplexer CreateConnection(ConfigurationOptions configurationOptions) + { + configurationOptions.EndPoints.Clear(); + + foreach (var endpoint in endpoints!) + { + configurationOptions.EndPoints.Add(endpoint); + } + + if (password != null) + { + configurationOptions.Password = password; + } + + // TODO(imalinovskiy): Add support for TLS + // TODO(imalinovskiy): Add support for Discovery/Sentinel API + + return ConnectionMultiplexer.Connect(configurationOptions); + } +} + + public class RedisFixture : IDisposable { // Set the environment variable to specify your own alternate host and port: private readonly string redisStandalone = Environment.GetEnvironmentVariable("REDIS") ?? "localhost:6379"; private readonly string? redisCluster = Environment.GetEnvironmentVariable("REDIS_CLUSTER"); private readonly string? numRedisClusterNodesEnv = Environment.GetEnvironmentVariable("NUM_REDIS_CLUSTER_NODES"); + + private readonly string defaultEndpointId = Environment.GetEnvironmentVariable("REDIS_DEFAULT_ENDPOINT_ID") ?? "standalone"; + private readonly string? redisEndpointsPath = Environment.GetEnvironmentVariable("REDIS_ENDPOINTS_CONFIG_PATH"); + private Dictionary redisEndpoints = new(); + + public bool isEnterprise = Environment.GetEnvironmentVariable("IS_ENTERPRISE") == "true"; public bool isOSSCluster; @@ -18,7 +59,42 @@ public RedisFixture() AsyncTimeout = 10000, SyncTimeout = 10000 }; - Redis = Connect(clusterConfig, out isOSSCluster); + + if (redisEndpointsPath != null && File.Exists(redisEndpointsPath)) + { + string json = File.ReadAllText(redisEndpointsPath); + var parsedEndpoints = JsonSerializer.Deserialize>(json); + + redisEndpoints = parsedEndpoints ?? throw new Exception("Failed to parse the Redis endpoints configuration."); + } + else + { + redisEndpoints.Add("standalone", + new EndpointConfig { endpoints = new List { redisStandalone } }); + + if (redisCluster != null) + { + string[] parts = redisCluster!.Split(':'); + string host = parts[0]; + int startPort = int.Parse(parts[1]); + + var endpoints = new List(); + int numRedisClusterNodes = int.Parse(numRedisClusterNodesEnv!); + for (int i = 0; i < numRedisClusterNodes; i++) + { + endpoints.Add($"{host}:{startPort + i}"); + } + + redisEndpoints.Add("cluster", + new EndpointConfig { endpoints = endpoints }); + + // Set the default endpoint to the cluster to keep the tests consistent + defaultEndpointId = "cluster"; + isOSSCluster = true; + } + } + + Redis = GetConnectionById(clusterConfig, defaultEndpointId); } public void Dispose() @@ -28,39 +104,18 @@ public void Dispose() public ConnectionMultiplexer Redis { get; } - public ConnectionMultiplexer CustomRedis(ConfigurationOptions configurationOptions, out bool isOssCluster) + public ConnectionMultiplexer GetConnectionById(ConfigurationOptions configurationOptions, string id) { - return Connect(configurationOptions, out isOssCluster); - } - - private ConnectionMultiplexer Connect(ConfigurationOptions configurationOptions, out bool isOssCluster) - { - // Redis Cluster - if (redisCluster != null && numRedisClusterNodesEnv != null) + if (!redisEndpoints.ContainsKey(id)) { - // Split to host and port - string[] parts = redisCluster!.Split(':'); - string host = parts[0]; - int startPort = int.Parse(parts[1]); - - var endpoints = new EndPointCollection(); // TODO: check if needed - - configurationOptions.EndPoints.Clear(); - int numRedisClusterNodes = int.Parse(numRedisClusterNodesEnv!); - for (int i = 0; i < numRedisClusterNodes; i++) - { - configurationOptions.EndPoints.Add(host, startPort + i); - } - - isOssCluster = true; - return ConnectionMultiplexer.Connect(configurationOptions); + throw new Exception($"The connection with id '{id}' is not configured."); } - // Redis Standalone - configurationOptions.EndPoints.Clear(); - configurationOptions.EndPoints.Add($"{redisStandalone}"); + return redisEndpoints[id].CreateConnection(configurationOptions); + } - isOssCluster = false; - return ConnectionMultiplexer.Connect(configurationOptions); + public bool IsTargetConnectionExist(string id) + { + return redisEndpoints.ContainsKey(id); } } \ No newline at end of file From 73e7a6daefed30a2e958f692a5c44dd7d73f7f22 Mon Sep 17 00:00:00 2001 From: andy-stark-redis <164213578+andy-stark-redis@users.noreply.github.com> Date: Wed, 9 Oct 2024 10:02:46 +0100 Subject: [PATCH 7/8] DOC-4345 added testable version of home page JSON example (#345) * DOC-4345 added testable version of home page JSON example * DOC-4345 added try...catch around dropIndex call * DOC-4345 sorted results before assert checks * DOC-4345 removed test library import --- tests/Doc/HomeJsonExample.cs | 177 +++++++++++++++++++++++++++++++++++ 1 file changed, 177 insertions(+) create mode 100644 tests/Doc/HomeJsonExample.cs diff --git a/tests/Doc/HomeJsonExample.cs b/tests/Doc/HomeJsonExample.cs new file mode 100644 index 00000000..b404469d --- /dev/null +++ b/tests/Doc/HomeJsonExample.cs @@ -0,0 +1,177 @@ +// EXAMPLE: cs_home_json + +// STEP_START import +using NRedisStack.RedisStackCommands; +using NRedisStack.Search; +using NRedisStack.Search.Aggregation; +using NRedisStack.Search.Literals.Enums; +using StackExchange.Redis; +// STEP_END + +// REMOVE_START +using NRedisStack.Tests; + +namespace Doc; +[Collection("DocsTests")] +// REMOVE_END + +// HIDE_START +public class HomeJsonExample +{ + + [SkipIfRedis(Is.OSSCluster)] + public void run() + { + // STEP_START connect + var muxer = ConnectionMultiplexer.Connect("localhost:6379"); + var db = muxer.GetDatabase(); + // STEP_END + + //REMOVE_START + // Clear any keys here before using them in tests. + db.KeyDelete(new RedisKey[] { "user:1", "user:2", "user:3" }); + try { db.FT().DropIndex("idx:users"); } catch { } + //REMOVE_END + // HIDE_END + + // STEP_START create_data + var user1 = new + { + name = "Paul John", + email = "paul.john@example.com", + age = 42, + city = "London" + }; + + var user2 = new + { + name = "Eden Zamir", + email = "eden.zamir@example.com", + age = 29, + city = "Tel Aviv" + }; + + var user3 = new + { + name = "Paul Zamir", + email = "paul.zamir@example.com", + age = 35, + city = "Tel Aviv" + }; + // STEP_END + + // STEP_START make_index + var schema = new Schema() + .AddTextField(new FieldName("$.name", "name")) + .AddTagField(new FieldName("$.city", "city")) + .AddNumericField(new FieldName("$.age", "age")); + + bool indexCreated = db.FT().Create( + "idx:users", + new FTCreateParams() + .On(IndexDataType.JSON) + .Prefix("user:"), + schema + ); + // STEP_END + + // Tests for 'make_index' step. + // REMOVE_START + Assert.True(indexCreated); + // REMOVE_END + + + // STEP_START add_data + bool user1Set = db.JSON().Set("user:1", "$", user1); + bool user2Set = db.JSON().Set("user:2", "$", user2); + bool user3Set = db.JSON().Set("user:3", "$", user3); + // STEP_END + + // Tests for 'add_data' step. + // REMOVE_START + Assert.True(user1Set); + Assert.True(user2Set); + Assert.True(user3Set); + // REMOVE_END + + + // STEP_START query1 + SearchResult findPaulResult = db.FT().Search( + "idx:users", + new Query("Paul @age:[30 40]") + ); + Console.WriteLine(string.Join( + ", ", + findPaulResult.Documents.Select(x => x["json"]) + )); + // >>> {"name":"Paul Zamir","email":"paul.zamir@example.com", ... + // STEP_END + + // Tests for 'query1' step. + // REMOVE_START + Assert.Equal( + "{\"name\":\"Paul Zamir\",\"email\":\"paul.zamir@example.com\",\"age\":35,\"city\":\"Tel Aviv\"}", + string.Join(", ", findPaulResult.Documents.Select(x => x["json"])) + ); + // REMOVE_END + + + // STEP_START query2 + var citiesResult = db.FT().Search( + "idx:users", + new Query("Paul") + .ReturnFields(new FieldName("$.city", "city")) + ); + Console.WriteLine(string.Join( + ", ", + citiesResult.Documents.Select(x => x["city"]).OrderBy(x => x) + )); + // >>> London, Tel Aviv + // STEP_END + + // Tests for 'query2' step. + // REMOVE_START + Assert.Equal( + "London, Tel Aviv", + string.Join(", ", citiesResult.Documents.Select(x => x["city"]).OrderBy(x => x)) + ); + // REMOVE_END + + + // STEP_START query3 + AggregationRequest aggRequest = new AggregationRequest("*") + .GroupBy("@city", Reducers.Count().As("count")); + + AggregationResult aggResult = db.FT().Aggregate("idx:users", aggRequest); + IReadOnlyList> resultsList = + aggResult.GetResults(); + + for (var i = 0; i < resultsList.Count; i++) + { + Dictionary item = resultsList.ElementAt(i); + Console.WriteLine($"{item["city"]} - {item["count"]}"); + } + // >>> London - 1 + // >>> Tel Aviv - 2 + // STEP_END + + // Tests for 'query3' step. + // REMOVE_START + Assert.Equal(2, resultsList.Count); + + var sortedResults = resultsList.OrderBy(x => x["city"]); + Dictionary testItem = sortedResults.ElementAt(0); + Assert.Equal("London", testItem["city"]); + Assert.Equal(1, testItem["count"]); + + testItem = sortedResults.ElementAt(1); + Assert.Equal("Tel Aviv", testItem["city"]); + Assert.Equal(2, testItem["count"]); + // REMOVE_END + + + // HIDE_START + } +} +// HIDE_END + From dd11910e54564daeec643233a97714c122947bc0 Mon Sep 17 00:00:00 2001 From: atakavci <58048133+atakavci@users.noreply.github.com> Date: Thu, 7 Nov 2024 17:42:57 +0300 Subject: [PATCH 8/8] Fix for 'toList' reducer results empty (#346) * issue #342- fix for 'toList' reducer results empty * fix collection initializer --- src/NRedisStack/Search/AggregationResult.cs | 53 ++++++++++++++++--- src/NRedisStack/Search/Row.cs | 11 ++-- tests/NRedisStack.Tests/Search/SearchTests.cs | 23 +++++--- 3 files changed, 68 insertions(+), 19 deletions(-) diff --git a/src/NRedisStack/Search/AggregationResult.cs b/src/NRedisStack/Search/AggregationResult.cs index f3410c29..22f861a6 100644 --- a/src/NRedisStack/Search/AggregationResult.cs +++ b/src/NRedisStack/Search/AggregationResult.cs @@ -6,7 +6,9 @@ namespace NRedisStack.Search; public sealed class AggregationResult { public long TotalResults { get; } - private readonly Dictionary[] _results; + private readonly Dictionary[] _results; + private Dictionary[] _resultsAsRedisValues; + public long CursorId { get; } @@ -18,18 +20,23 @@ internal AggregationResult(RedisResult result, long cursorId = -1) // // the first element is always the number of results // TotalResults = (long)arr[0]; - _results = new Dictionary[arr.Length - 1]; + _results = new Dictionary[arr.Length - 1]; for (int i = 1; i < arr.Length; i++) { var raw = (RedisResult[])arr[i]!; - var cur = new Dictionary(); + var cur = new Dictionary(); for (int j = 0; j < raw.Length;) { var key = (string)raw[j++]!; var val = raw[j++]; if (val.Type == ResultType.MultiBulk) - continue; // TODO: handle multi-bulk (maybe change to object?) - cur.Add(key, (RedisValue)val); + { + cur.Add(key, ConvertMultiBulkToObject((RedisResult[])val!)); + } + else + { + cur.Add(key, (RedisValue)val); + } } _results[i - 1] = cur; @@ -52,17 +59,47 @@ private object ConvertMultiBulkToObject(IEnumerable multiBulkArray) { return multiBulkArray.Select(item => item.Type == ResultType.MultiBulk ? ConvertMultiBulkToObject((RedisResult[])item!) - : item) + : (RedisValue)item) .ToList(); } - public IReadOnlyList> GetResults() => _results; + /// + /// Gets the results as a read-only list of dictionaries with string keys and RedisValue values. + /// + /// + /// This method is deprecated and will be removed in future versions. + /// Please use instead. + /// + [Obsolete("This method is deprecated and will be removed in future versions. Please use 'GetRow' instead.")] + public IReadOnlyList> GetResults() + { + return getResultsAsRedisValues(); + } + /// + /// Gets the aggregation result at the specified index. + /// + /// The zero-based index of the aggregation result to retrieve. + /// + /// A dictionary containing the aggregation result as Redis values if the index is within bounds; + /// otherwise, null. + /// + [Obsolete("This method is deprecated and will be removed in future versions. Please use 'GetRow' instead.")] public Dictionary? this[int index] - => index >= _results.Length ? null : _results[index]; + => index >= getResultsAsRedisValues().Length ? null : getResultsAsRedisValues()[index]; public Row GetRow(int index) { return index >= _results.Length ? default : new Row(_results[index]); } + + private Dictionary[] getResultsAsRedisValues() + { + if (_resultsAsRedisValues == null) + _resultsAsRedisValues = _results.Select(dict => dict.ToDictionary( + kvp => kvp.Key, + kvp => kvp.Value is RedisValue value ? value : RedisValue.Null + )).ToArray(); + return _resultsAsRedisValues; + } } \ No newline at end of file diff --git a/src/NRedisStack/Search/Row.cs b/src/NRedisStack/Search/Row.cs index 0caac94e..07153f85 100644 --- a/src/NRedisStack/Search/Row.cs +++ b/src/NRedisStack/Search/Row.cs @@ -4,18 +4,19 @@ namespace NRedisStack.Search.Aggregation { public readonly struct Row { - private readonly Dictionary _fields; + private readonly Dictionary _fields; - internal Row(Dictionary fields) + internal Row(Dictionary fields) { _fields = fields; } public bool ContainsKey(string key) => _fields.ContainsKey(key); - public RedisValue this[string key] => _fields.TryGetValue(key, out var result) ? result : RedisValue.Null; + public RedisValue this[string key] => _fields.TryGetValue(key, out var result) ? (result is RedisValue ? (RedisValue)result : RedisValue.Null) : RedisValue.Null; + public object Get(string key) => _fields.TryGetValue(key, out var result) ? result : RedisValue.Null; 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; + public long GetLong(string key) => _fields.TryGetValue(key, out var result) ? (long)(RedisValue)result : default; + public double GetDouble(string key) => _fields.TryGetValue(key, out var result) ? (double)(RedisValue)result : default; } } \ No newline at end of file diff --git a/tests/NRedisStack.Tests/Search/SearchTests.cs b/tests/NRedisStack.Tests/Search/SearchTests.cs index b39bcb09..2ed10466 100644 --- a/tests/NRedisStack.Tests/Search/SearchTests.cs +++ b/tests/NRedisStack.Tests/Search/SearchTests.cs @@ -1256,7 +1256,9 @@ public void TestAggregationGroupBy() res = rawRes.GetRow(0); Assert.Equal("redis", res["parent"]); // TODO: complete this assert after handling multi bulk reply - //Assert.Equal((RedisValue[])res["__generated_aliastolisttitle"], { "RediSearch", "RedisAI", "RedisJson"}); + var expected = new List { "RediSearch", "RedisAI", "RedisJson" }; + var actual = (List)res.Get("__generated_aliastolisttitle"); + Assert.True(!expected.Except(actual).Any() && expected.Count == actual.Count); req = new AggregationRequest("redis").GroupBy( "@parent", Reducers.FirstValue("@title").As("first")); @@ -1269,11 +1271,20 @@ public void TestAggregationGroupBy() res = ft.Aggregate("idx", req).GetRow(0); 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); - // Assert.Equal(res[3][0] in ["RediSearch", "RedisAI", "RedisJson"]); - // req = new AggregationRequest("redis").GroupBy("@parent", redu - + actual = (List)res.Get("random"); + Assert.Equal(2, actual.Count); + List possibleValues = new List() { "RediSearch", "RedisAI", "RedisJson" }; + Assert.Contains(actual[0].ToString(), possibleValues); + Assert.Contains(actual[1].ToString(), possibleValues); + + req = new AggregationRequest("redis") + .Load(new FieldName("__key")) + .GroupBy("@parent", Reducers.ToList("__key").As("docs")); + + res = db.FT().Aggregate("idx", req).GetRow(0); + actual = (List)res.Get("docs"); + expected = new List { "ai", "search", "json" }; + Assert.True(!expected.Except(actual).Any() && expected.Count == actual.Count); }