Skip to content

Commit 7f93841

Browse files
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
1 parent cb6d685 commit 7f93841

File tree

1 file changed

+327
-0
lines changed

1 file changed

+327
-0
lines changed

tests/Doc/QueryAggExample.cs

Lines changed: 327 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,327 @@
1+
// EXAMPLE: query_agg
2+
// HIDE_START
3+
4+
using NRedisStack.RedisStackCommands;
5+
using NRedisStack.Search;
6+
using NRedisStack.Search.Aggregation;
7+
using NRedisStack.Search.Literals.Enums;
8+
using NRedisStack.Tests;
9+
using StackExchange.Redis;
10+
11+
// HIDE_END
12+
13+
// REMOVE_START
14+
namespace Doc;
15+
[Collection("DocsTests")]
16+
// REMOVE_END
17+
18+
// HIDE_START
19+
public class QueryAggExample
20+
{
21+
22+
[SkipIfRedis(Is.OSSCluster)]
23+
public void run()
24+
{
25+
var muxer = ConnectionMultiplexer.Connect("localhost:6379");
26+
var db = muxer.GetDatabase();
27+
//REMOVE_START
28+
// Clear any keys here before using them in tests.
29+
try { db.FT().DropIndex("idx:bicycle"); } catch { }
30+
//REMOVE_END
31+
32+
Schema bikeSchema = new Schema()
33+
.AddTagField(new FieldName("$.condition", "condition"))
34+
.AddNumericField(new FieldName("$.price", "price"));
35+
36+
FTCreateParams bikeParams = new FTCreateParams()
37+
.AddPrefix("bicycle:")
38+
.On(IndexDataType.JSON);
39+
40+
db.FT().Create("idx:bicycle", bikeParams, bikeSchema);
41+
42+
var bicycles = new object[] {
43+
new
44+
{
45+
pickup_zone = "POLYGON((-74.0610 40.7578, -73.9510 40.7578, -73.9510 40.6678, -74.0610 40.6678, -74.0610 40.7578))",
46+
store_location = "-74.0060,40.7128",
47+
brand = "Velorim",
48+
model = "Jigger",
49+
price = 270,
50+
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.",
51+
condition = "new"
52+
},
53+
new
54+
{
55+
pickup_zone = "POLYGON((-118.2887 34.0972, -118.1987 34.0972, -118.1987 33.9872, -118.2887 33.9872, -118.2887 34.0972))",
56+
store_location = "-118.2437,34.0522",
57+
brand = "Bicyk",
58+
model = "Hillcraft",
59+
price = 1200,
60+
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!",
61+
condition = "used"
62+
},
63+
new
64+
{
65+
pickup_zone = "POLYGON((-87.6848 41.9331, -87.5748 41.9331, -87.5748 41.8231, -87.6848 41.8231, -87.6848 41.9331))",
66+
store_location = "-87.6298,41.8781",
67+
brand = "Nord",
68+
model = "Chook air 5",
69+
price = 815,
70+
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.",
71+
condition = "used"
72+
},
73+
new
74+
{
75+
pickup_zone = "POLYGON((-80.2433 25.8067, -80.1333 25.8067, -80.1333 25.6967, -80.2433 25.6967, -80.2433 25.8067))",
76+
store_location = "-80.1918,25.7617",
77+
brand = "Eva",
78+
model = "Eva 291",
79+
price = 3400,
80+
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!",
81+
condition = "used"
82+
},
83+
new
84+
{
85+
pickup_zone = "POLYGON((-122.4644 37.8199, -122.3544 37.8199, -122.3544 37.7099, -122.4644 37.7099, -122.4644 37.8199))",
86+
store_location = "-122.4194,37.7749",
87+
brand = "Noka Bikes",
88+
model = "Kahuna",
89+
price = 3200,
90+
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.",
91+
condition = "used"
92+
},
93+
new
94+
{
95+
pickup_zone = "POLYGON((-0.1778 51.5524, 0.0822 51.5524, 0.0822 51.4024, -0.1778 51.4024, -0.1778 51.5524))",
96+
store_location = "-0.1278,51.5074",
97+
brand = "Breakout",
98+
model = "XBN 2.1 Alloy",
99+
price = 810,
100+
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.",
101+
condition = "new"
102+
},
103+
new
104+
{
105+
pickup_zone = "POLYGON((2.1767 48.9016, 2.5267 48.9016, 2.5267 48.5516, 2.1767 48.5516, 2.1767 48.9016))",
106+
store_location = "2.3522,48.8566",
107+
brand = "ScramBikes",
108+
model = "WattBike",
109+
price = 2300,
110+
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.",
111+
condition = "new"
112+
},
113+
new
114+
{
115+
pickup_zone = "POLYGON((13.3260 52.5700, 13.6550 52.5700, 13.6550 52.2700, 13.3260 52.2700, 13.3260 52.5700))",
116+
store_location = "13.4050,52.5200",
117+
brand = "Peaknetic",
118+
model = "Secto",
119+
price = 430,
120+
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.",
121+
condition = "new"
122+
},
123+
new
124+
{
125+
pickup_zone = "POLYGON((1.9450 41.4301, 2.4018 41.4301, 2.4018 41.1987, 1.9450 41.1987, 1.9450 41.4301))",
126+
store_location = "2.1734, 41.3851",
127+
brand = "nHill",
128+
model = "Summit",
129+
price = 1200,
130+
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.",
131+
condition = "new"
132+
},
133+
new
134+
{
135+
pickup_zone = "POLYGON((12.4464 42.1028, 12.5464 42.1028, 12.5464 41.7028, 12.4464 41.7028, 12.4464 42.1028))",
136+
store_location = "12.4964,41.9028",
137+
model = "ThrillCycle",
138+
brand = "BikeShind",
139+
price = 815,
140+
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.",
141+
condition = "refurbished"
142+
}
143+
};
144+
145+
for (var i = 0; i < bicycles.Length; i++)
146+
{
147+
db.JSON().Set($"bicycle:{i}", "$", bicycles[i]);
148+
}
149+
// HIDE_END
150+
151+
152+
// STEP_START agg1
153+
AggregationResult res1 = db.FT().Aggregate(
154+
"idx:bicycle",
155+
new AggregationRequest("@condition:{new}")
156+
.Load(new FieldName("__key"), new FieldName("price"))
157+
.Apply("@price - (@price * 0.1)", "discounted")
158+
);
159+
Console.WriteLine(res1.TotalResults); // >>> 5
160+
161+
for (int i = 0; i < res1.TotalResults; i++)
162+
{
163+
Row res1Row = res1.GetRow(i);
164+
165+
Console.WriteLine(
166+
$"Key: {res1Row["__key"]}, Price: {res1Row["price"]}, Discounted: {res1Row["discounted"]}"
167+
);
168+
}
169+
// >>> Key: bicycle:0, Price: 270, Discounted: 243
170+
// >>> Key: bicycle:5, Price: 810, Discounted: 729
171+
// >>> Key: bicycle:6, Price: 2300, Discounted: 2070
172+
// >>> Key: bicycle:7, Price: 430, Discounted: 387
173+
// >>> Key: bicycle:8, Price: 1200, Discounted: 1080
174+
// STEP_END
175+
176+
// Tests for 'agg1' step.
177+
// REMOVE_START
178+
Assert.Equal(5, res1.TotalResults);
179+
180+
for (int i = 0; i < 5; i++)
181+
{
182+
Row test1Row = res1.GetRow(i);
183+
184+
switch (test1Row["__key"])
185+
{
186+
case "bicycle:0":
187+
Assert.Equal(
188+
"Key: bicycle:0, Price: 270, Discounted: 243",
189+
$"Key: {test1Row["__key"]}, Price: {test1Row["price"]}, Discounted: {test1Row["discounted"]}"
190+
);
191+
break;
192+
193+
case "bicycle:5":
194+
Assert.Equal(
195+
"Key: bicycle:5, Price: 810, Discounted: 729",
196+
$"Key: {test1Row["__key"]}, Price: {test1Row["price"]}, Discounted: {test1Row["discounted"]}"
197+
);
198+
break;
199+
200+
case "bicycle:6":
201+
Assert.Equal(
202+
"Key: bicycle:6, Price: 2300, Discounted: 2070",
203+
$"Key: {test1Row["__key"]}, Price: {test1Row["price"]}, Discounted: {test1Row["discounted"]}"
204+
);
205+
break;
206+
207+
case "bicycle:7":
208+
Assert.Equal(
209+
"Key: bicycle:7, Price: 430, Discounted: 387",
210+
$"Key: {test1Row["__key"]}, Price: {test1Row["price"]}, Discounted: {test1Row["discounted"]}"
211+
);
212+
break;
213+
214+
case "bicycle:8":
215+
Assert.Equal(
216+
"Key: bicycle:8, Price: 1200, Discounted: 1080",
217+
$"Key: {test1Row["__key"]}, Price: {test1Row["price"]}, Discounted: {test1Row["discounted"]}"
218+
);
219+
break;
220+
}
221+
}
222+
223+
// REMOVE_END
224+
225+
226+
// STEP_START agg2
227+
AggregationResult res2 = db.FT().Aggregate(
228+
"idx:bicycle",
229+
new AggregationRequest("*")
230+
.Load(new FieldName("price"))
231+
.Apply("@price<1000", "price_category")
232+
.GroupBy(
233+
"@condition",
234+
Reducers.Sum("@price_category").As("num_affordable")
235+
)
236+
);
237+
Console.WriteLine(res2.TotalResults); // >>> 3
238+
239+
for (int i = 0; i < res2.TotalResults; i++)
240+
{
241+
Row res2Row = res2.GetRow(i);
242+
243+
Console.WriteLine(
244+
$"Condition: {res2Row["condition"]}, Num affordable: {res2Row["num_affordable"]}"
245+
);
246+
}
247+
// >>> Condition: refurbished, Num affordable: 1
248+
// >>> Condition: used, Num affordable: 1
249+
// >>> Condition: new, Num affordable: 3
250+
// STEP_END
251+
252+
// Tests for 'agg2' step.
253+
// REMOVE_START
254+
Assert.Equal(3, res2.TotalResults);
255+
256+
for (int i = 0; i < 3; i++)
257+
{
258+
Row test2Row = res2.GetRow(i);
259+
switch (test2Row["condition"])
260+
{
261+
case "refurbished":
262+
Assert.Equal(
263+
"Condition: refurbished, Num affordable: 1",
264+
$"Condition: {test2Row["condition"]}, Num affordable: {test2Row["num_affordable"]}"
265+
);
266+
break;
267+
268+
case "used":
269+
Assert.Equal(
270+
"Condition: used, Num affordable: 1",
271+
$"Condition: {test2Row["condition"]}, Num affordable: {test2Row["num_affordable"]}"
272+
);
273+
break;
274+
275+
case "new":
276+
Assert.Equal(
277+
"Condition: new, Num affordable: 3",
278+
$"Condition: {test2Row["condition"]}, Num affordable: {test2Row["num_affordable"]}"
279+
);
280+
break;
281+
}
282+
}
283+
// REMOVE_END
284+
285+
286+
// STEP_START agg3
287+
AggregationResult res3 = db.FT().Aggregate(
288+
"idx:bicycle",
289+
new AggregationRequest("*")
290+
.Apply("'bicycle'", "type")
291+
.GroupBy("@type", Reducers.Count().As("num_total"))
292+
);
293+
Console.WriteLine(res3.TotalResults); // >>> 1
294+
295+
Row res3Row = res3.GetRow(0);
296+
Console.WriteLine($"Type: {res3Row["type"]}, Num total: {res3Row["num_total"]}");
297+
// >>> Type: bicycle, Num total: 10
298+
// STEP_END
299+
300+
// Tests for 'agg3' step.
301+
// REMOVE_START
302+
Assert.Equal(1, res3.TotalResults);
303+
304+
Assert.Equal(
305+
"Type: bicycle, Num total: 10",
306+
$"Type: {res3Row["type"]}, Num total: {res3Row["num_total"]}"
307+
);
308+
// REMOVE_END
309+
310+
311+
// STEP_START agg4
312+
313+
// Not supported in NRedisStack.
314+
315+
// STEP_END
316+
317+
// Tests for 'agg4' step.
318+
// REMOVE_START
319+
320+
// REMOVE_END
321+
322+
323+
// HIDE_START
324+
}
325+
}
326+
// HIDE_END
327+

0 commit comments

Comments
 (0)