diff --git a/.github/workflows/spellcheck.yml b/.github/workflows/spellcheck.yml index 977f8c5c1..95cfdfaa0 100644 --- a/.github/workflows/spellcheck.yml +++ b/.github/workflows/spellcheck.yml @@ -8,7 +8,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 - name: Check Spelling - uses: rojopolis/spellcheck-github-actions@0.45.0 + uses: rojopolis/spellcheck-github-actions@0.46.0 with: config_path: .github/spellcheck-settings.yml task_name: Markdown diff --git a/doctests/geo_index_test.go b/doctests/geo_index_test.go new file mode 100644 index 000000000..9c38ba9d3 --- /dev/null +++ b/doctests/geo_index_test.go @@ -0,0 +1,206 @@ +// EXAMPLE: geoindex +// HIDE_START +package example_commands_test + +import ( + "context" + "fmt" + + "github.com/redis/go-redis/v9" +) + +// HIDE_END + +func ExampleClient_geoindex() { + ctx := context.Background() + + rdb := redis.NewClient(&redis.Options{ + Addr: "localhost:6379", + Password: "", // no password docs + DB: 0, // use default DB + Protocol: 2, + }) + // REMOVE_START + rdb.FTDropIndex(ctx, "productidx") + rdb.FTDropIndex(ctx, "geomidx") + rdb.Del(ctx, "product:46885", "product:46886", "shape:1", "shape:2", "shape:3", "shape:4") + // REMOVE_END + + // STEP_START create_geo_idx + geoCreateResult, err := rdb.FTCreate(ctx, + "productidx", + &redis.FTCreateOptions{ + OnJSON: true, + Prefix: []interface{}{"product:"}, + }, + &redis.FieldSchema{ + FieldName: "$.location", + As: "location", + FieldType: redis.SearchFieldTypeGeo, + }, + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(geoCreateResult) // >>> OK + // STEP_END + + // STEP_START add_geo_json + prd46885 := map[string]interface{}{ + "description": "Navy Blue Slippers", + "price": 45.99, + "city": "Denver", + "location": "-104.991531, 39.742043", + } + + gjResult1, err := rdb.JSONSet(ctx, "product:46885", "$", prd46885).Result() + + if err != nil { + panic(err) + } + + fmt.Println(gjResult1) // >>> OK + + prd46886 := map[string]interface{}{ + "description": "Bright Green Socks", + "price": 25.50, + "city": "Fort Collins", + "location": "-105.0618814,40.5150098", + } + + gjResult2, err := rdb.JSONSet(ctx, "product:46886", "$", prd46886).Result() + + if err != nil { + panic(err) + } + + fmt.Println(gjResult2) // >>> OK + // STEP_END + + // STEP_START geo_query + geoQueryResult, err := rdb.FTSearch(ctx, "productidx", + "@location:[-104.800644 38.846127 100 mi]", + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(geoQueryResult) + // >>> {1 [{product:46885... + // STEP_END + + // STEP_START create_gshape_idx + geomCreateResult, err := rdb.FTCreate(ctx, "geomidx", + &redis.FTCreateOptions{ + OnJSON: true, + Prefix: []interface{}{"shape:"}, + }, + &redis.FieldSchema{ + FieldName: "$.name", + As: "name", + FieldType: redis.SearchFieldTypeText, + }, + &redis.FieldSchema{ + FieldName: "$.geom", + As: "geom", + FieldType: redis.SearchFieldTypeGeoShape, + GeoShapeFieldType: "FLAT", + }, + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(geomCreateResult) // >>> OK + // STEP_END + + // STEP_START add_gshape_json + shape1 := map[string]interface{}{ + "name": "Green Square", + "geom": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))", + } + + gmjResult1, err := rdb.JSONSet(ctx, "shape:1", "$", shape1).Result() + + if err != nil { + panic(err) + } + + fmt.Println(gmjResult1) // >>> OK + + shape2 := map[string]interface{}{ + "name": "Red Rectangle", + "geom": "POLYGON ((2 2.5, 2 3.5, 3.5 3.5, 3.5 2.5, 2 2.5))", + } + + gmjResult2, err := rdb.JSONSet(ctx, "shape:2", "$", shape2).Result() + + if err != nil { + panic(err) + } + + fmt.Println(gmjResult2) // >>> OK + + shape3 := map[string]interface{}{ + "name": "Blue Triangle", + "geom": "POLYGON ((3.5 1, 3.75 2, 4 1, 3.5 1))", + } + + gmjResult3, err := rdb.JSONSet(ctx, "shape:3", "$", shape3).Result() + + if err != nil { + panic(err) + } + + fmt.Println(gmjResult3) // >>> OK + + shape4 := map[string]interface{}{ + "name": "Purple Point", + "geom": "POINT (2 2)", + } + + gmjResult4, err := rdb.JSONSet(ctx, "shape:4", "$", shape4).Result() + + if err != nil { + panic(err) + } + + fmt.Println(gmjResult4) // >>> OK + // STEP_END + + // STEP_START gshape_query + geomQueryResult, err := rdb.FTSearchWithArgs(ctx, "geomidx", + "(-@name:(Green Square) @geom:[WITHIN $qshape])", + &redis.FTSearchOptions{ + Params: map[string]interface{}{ + "qshape": "POLYGON ((1 1, 1 3, 3 3, 3 1, 1 1))", + }, + DialectVersion: 4, + Limit: 1, + }, + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(geomQueryResult) + // >>> {1 [{shape:4... + // STEP_END + + // Output: + // OK + // OK + // OK + // {1 [{product:46885 map[$:{"city":"Denver","description":"Navy Blue Slippers","location":"-104.991531, 39.742043","price":45.99}]}]} + // OK + // OK + // OK + // OK + // OK + // {1 [{shape:4 map[$:[{"geom":"POINT (2 2)","name":"Purple Point"}]]}]} +} diff --git a/doctests/list_tutorial_test.go b/doctests/list_tutorial_test.go index 908469ce0..bec1e1643 100644 --- a/doctests/list_tutorial_test.go +++ b/doctests/list_tutorial_test.go @@ -388,7 +388,7 @@ func ExampleClient_ltrim() { // REMOVE_END // STEP_START ltrim - res27, err := rdb.LPush(ctx, "bikes:repairs", "bike:1", "bike:2", "bike:3", "bike:4", "bike:5").Result() + res27, err := rdb.RPush(ctx, "bikes:repairs", "bike:1", "bike:2", "bike:3", "bike:4", "bike:5").Result() if err != nil { panic(err) @@ -410,13 +410,13 @@ func ExampleClient_ltrim() { panic(err) } - fmt.Println(res29) // >>> [bike:5 bike:4 bike:3] + fmt.Println(res29) // >>> [bike:1 bike:2 bike:3] // STEP_END // Output: // 5 // OK - // [bike:5 bike:4 bike:3] + // [bike:1 bike:2 bike:3] } func ExampleClient_ltrim_end_of_list() { diff --git a/doctests/query_em_test.go b/doctests/query_em_test.go new file mode 100644 index 000000000..d4267df4f --- /dev/null +++ b/doctests/query_em_test.go @@ -0,0 +1,363 @@ +// EXAMPLE: query_em +// HIDE_START +package example_commands_test + +import ( + "context" + "fmt" + + "github.com/redis/go-redis/v9" +) + +func ExampleClient_query_em() { + ctx := context.Background() + + rdb := redis.NewClient(&redis.Options{ + Addr: "localhost:6379", + Password: "", // no password docs + DB: 0, // use default DB + Protocol: 2, + }) + + // HIDE_END + // REMOVE_START + rdb.FTDropIndex(ctx, "idx:bicycle") + rdb.FTDropIndex(ctx, "idx:email") + // REMOVE_END + + _, err := rdb.FTCreate(ctx, "idx:bicycle", + &redis.FTCreateOptions{ + OnJSON: true, + Prefix: []interface{}{"bicycle:"}, + }, + &redis.FieldSchema{ + FieldName: "$.brand", + As: "brand", + FieldType: redis.SearchFieldTypeText, + }, + &redis.FieldSchema{ + FieldName: "$.model", + As: "model", + FieldType: redis.SearchFieldTypeText, + }, + &redis.FieldSchema{ + FieldName: "$.description", + As: "description", + FieldType: redis.SearchFieldTypeText, + }, + &redis.FieldSchema{ + FieldName: "$.price", + As: "price", + FieldType: redis.SearchFieldTypeNumeric, + }, + &redis.FieldSchema{ + FieldName: "$.condition", + As: "condition", + FieldType: redis.SearchFieldTypeTag, + }, + ).Result() + + if err != nil { + panic(err) + } + + exampleJsons := []map[string]interface{}{ + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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 i, json := range exampleJsons { + _, err := rdb.JSONSet(ctx, fmt.Sprintf("bicycle:%v", i), "$", json).Result() + + if err != nil { + panic(err) + } + } + + // STEP_START em1 + res1, err := rdb.FTSearch(ctx, + "idx:bicycle", "@price:[270 270]", + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(res1.Total) // >>> 1 + + for _, doc := range res1.Docs { + fmt.Println(doc.ID) + } + // >>> bicycle:0 + + res2, err := rdb.FTSearchWithArgs(ctx, + "idx:bicycle", + "*", + &redis.FTSearchOptions{ + Filters: []redis.FTSearchFilter{ + { + FieldName: "price", + Min: 270, + Max: 270, + }, + }, + }, + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(res2.Total) // >>> 1 + + for _, doc := range res2.Docs { + fmt.Println(doc.ID) + } + // >>> bicycle:0 + // STEP_END + + // STEP_START em2 + res3, err := rdb.FTSearch(ctx, + "idx:bicycle", "@condition:{new}", + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(res3.Total) // >>> 5 + + for _, doc := range res3.Docs { + fmt.Println(doc.ID) + } + // >>> bicycle:5 + // >>> bicycle:0 + // >>> bicycle:6 + // >>> bicycle:7 + // >>> bicycle:8 + // STEP_END + + // STEP_START em3 + res4, err := rdb.FTCreate(ctx, + "idx:email", + &redis.FTCreateOptions{ + OnJSON: true, + Prefix: []interface{}{"key:"}, + }, + &redis.FieldSchema{ + FieldName: "$.email", + As: "email", + FieldType: redis.SearchFieldTypeTag, + }, + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(res4) // >>> OK + + res5, err := rdb.JSONSet(ctx, "key:1", "$", + map[string]interface{}{ + "email": "test@redis.com", + }, + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(res5) // >>> OK + + res6, err := rdb.FTSearch(ctx, "idx:email", + "@email:{test\\@redis\\.com}", + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(res6.Total) // >>> 1 + // STEP_END + + // STEP_START em4 + res7, err := rdb.FTSearch(ctx, + "idx:bicycle", "@description:\"rough terrain\"", + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(res7.Total) // >>> 1 + + for _, doc := range res7.Docs { + fmt.Println(doc.ID) + } + // >>> bicycle:8 + // STEP_END + + // Output: + // 1 + // bicycle:0 + // 1 + // bicycle:0 + // 5 + // bicycle:5 + // bicycle:0 + // bicycle:6 + // bicycle:7 + // bicycle:8 + // OK + // OK + // 1 + // 1 + // bicycle:8 +} diff --git a/doctests/query_ft_test.go b/doctests/query_ft_test.go new file mode 100644 index 000000000..095230f73 --- /dev/null +++ b/doctests/query_ft_test.go @@ -0,0 +1,331 @@ +// EXAMPLE: query_ft +// HIDE_START +package example_commands_test + +import ( + "context" + "fmt" + "sort" + + "github.com/redis/go-redis/v9" +) + +func ExampleClient_query_ft() { + ctx := context.Background() + + rdb := redis.NewClient(&redis.Options{ + Addr: "localhost:6379", + Password: "", // no password docs + DB: 0, // use default DB + Protocol: 2, + }) + // HIDE_END + // REMOVE_START + rdb.FTDropIndex(ctx, "idx:bicycle") + rdb.FTDropIndex(ctx, "idx:email") + // REMOVE_END + + _, err := rdb.FTCreate(ctx, "idx:bicycle", + &redis.FTCreateOptions{ + OnJSON: true, + Prefix: []interface{}{"bicycle:"}, + }, + &redis.FieldSchema{ + FieldName: "$.brand", + As: "brand", + FieldType: redis.SearchFieldTypeText, + }, + &redis.FieldSchema{ + FieldName: "$.model", + As: "model", + FieldType: redis.SearchFieldTypeText, + }, + &redis.FieldSchema{ + FieldName: "$.description", + As: "description", + FieldType: redis.SearchFieldTypeText, + }, + &redis.FieldSchema{ + FieldName: "$.price", + As: "price", + FieldType: redis.SearchFieldTypeNumeric, + }, + &redis.FieldSchema{ + FieldName: "$.condition", + As: "condition", + FieldType: redis.SearchFieldTypeTag, + }, + ).Result() + + if err != nil { + panic(err) + } + + exampleJsons := []map[string]interface{}{ + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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 i, json := range exampleJsons { + _, err := rdb.JSONSet(ctx, fmt.Sprintf("bicycle:%v", i), "$", json).Result() + + if err != nil { + panic(err) + } + } + + // STEP_START ft1 + res1, err := rdb.FTSearch(ctx, + "idx:bicycle", "@description: kids", + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(res1.Total) // >>> 2 + + sort.Slice(res1.Docs, func(i, j int) bool { + return res1.Docs[i].ID < res1.Docs[j].ID + }) + + for _, doc := range res1.Docs { + fmt.Println(doc.ID) + } + // >>> bicycle:1 + // >>> bicycle:2 + // STEP_END + + // STEP_START ft2 + res2, err := rdb.FTSearch(ctx, + "idx:bicycle", "@model: ka*", + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(res2.Total) // >>> 1 + + for _, doc := range res2.Docs { + fmt.Println(doc.ID) + } + // >>> bicycle:4 + // STEP_END + + // STEP_START ft3 + res3, err := rdb.FTSearch(ctx, + "idx:bicycle", "@brand: *bikes", + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(res3.Total) // >>> 2 + + sort.Slice(res3.Docs, func(i, j int) bool { + return res3.Docs[i].ID < res3.Docs[j].ID + }) + for _, doc := range res3.Docs { + fmt.Println(doc.ID) + } + // >>> bicycle:4 + // >>> bicycle:6 + // STEP_END + + // STEP_START ft4 + res4, err := rdb.FTSearch(ctx, + "idx:bicycle", "%optamized%", + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(res4.Total) // >>> 1 + + for _, doc := range res4.Docs { + fmt.Println(doc.ID) + } + // >>> bicycle:3 + // STEP_END + + // STEP_START ft5 + res5, err := rdb.FTSearch(ctx, + "idx:bicycle", "%%optamised%%", + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(res5.Total) // >>> 1 + + for _, doc := range res5.Docs { + fmt.Println(doc.ID) + } + // >>> bicycle:3 + // STEP_END + + // Output: + // 2 + // bicycle:1 + // bicycle:2 + // 1 + // bicycle:4 + // 2 + // bicycle:4 + // bicycle:6 + // 1 + // bicycle:3 + // 1 + // bicycle:3 +} diff --git a/doctests/query_geo_test.go b/doctests/query_geo_test.go new file mode 100644 index 000000000..7e880aead --- /dev/null +++ b/doctests/query_geo_test.go @@ -0,0 +1,327 @@ +// EXAMPLE: query_geo +// HIDE_START +package example_commands_test + +import ( + "context" + "fmt" + "sort" + + "github.com/redis/go-redis/v9" +) + +func ExampleClient_query_geo() { + ctx := context.Background() + + rdb := redis.NewClient(&redis.Options{ + Addr: "localhost:6379", + Password: "", // no password docs + DB: 0, // use default DB + Protocol: 2, + }) + // HIDE_END + // REMOVE_START + rdb.FTDropIndex(ctx, "idx:bicycle") + // REMOVE_END + + _, err := rdb.FTCreate(ctx, "idx:bicycle", + &redis.FTCreateOptions{ + OnJSON: true, + Prefix: []interface{}{"bicycle:"}, + }, + &redis.FieldSchema{ + FieldName: "$.brand", + As: "brand", + FieldType: redis.SearchFieldTypeText, + }, + &redis.FieldSchema{ + FieldName: "$.model", + As: "model", + FieldType: redis.SearchFieldTypeText, + }, + &redis.FieldSchema{ + FieldName: "$.description", + As: "description", + FieldType: redis.SearchFieldTypeText, + }, + &redis.FieldSchema{ + FieldName: "$.price", + As: "price", + FieldType: redis.SearchFieldTypeNumeric, + }, + &redis.FieldSchema{ + FieldName: "$.condition", + As: "condition", + FieldType: redis.SearchFieldTypeTag, + }, + &redis.FieldSchema{ + FieldName: "$.store_location", + As: "store_location", + FieldType: redis.SearchFieldTypeGeo, + }, + &redis.FieldSchema{ + FieldName: "$.pickup_zone", + As: "pickup_zone", + FieldType: redis.SearchFieldTypeGeoShape, + GeoShapeFieldType: "FLAT", + }, + ).Result() + + if err != nil { + panic(err) + } + + exampleJsons := []map[string]interface{}{ + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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", + }, + { + "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 i, json := range exampleJsons { + _, err := rdb.JSONSet(ctx, fmt.Sprintf("bicycle:%v", i), "$", json).Result() + + if err != nil { + panic(err) + } + } + + // STEP_START geo1 + res1, err := rdb.FTSearchWithArgs(ctx, + "idx:bicycle", "@store_location:[$lon $lat $radius $units]", + &redis.FTSearchOptions{ + Params: map[string]interface{}{ + "lon": -0.1778, + "lat": 51.5524, + "radius": 20, + "units": "mi", + }, + DialectVersion: 2, + }, + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(res1.Total) // >>> 1 + + for _, doc := range res1.Docs { + fmt.Println(doc.ID) + } + // >>> bicycle:5 + // STEP_END + + // STEP_START geo2 + res2, err := rdb.FTSearchWithArgs(ctx, + "idx:bicycle", + "@pickup_zone:[CONTAINS $bike]", + &redis.FTSearchOptions{ + Params: map[string]interface{}{ + "bike": "POINT(-0.1278 51.5074)", + }, + DialectVersion: 3, + }, + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(res2.Total) // >>> 1 + + for _, doc := range res2.Docs { + fmt.Println(doc.ID) + } + // >>> bicycle:5 + // STEP_END + + // STEP_START geo3 + res3, err := rdb.FTSearchWithArgs(ctx, + "idx:bicycle", + "@pickup_zone:[WITHIN $europe]", + &redis.FTSearchOptions{ + Params: map[string]interface{}{ + "europe": "POLYGON((-25 35, 40 35, 40 70, -25 70, -25 35))", + }, + DialectVersion: 3, + }, + ).Result() + + if err != nil { + panic(err) + } + + fmt.Println(res3.Total) // >>> 5 + + sort.Slice(res3.Docs, func(i, j int) bool { + return res3.Docs[i].ID < res3.Docs[j].ID + }) + + for _, doc := range res3.Docs { + fmt.Println(doc.ID) + } + // >>> bicycle:5 + // >>> bicycle:6 + // >>> bicycle:7 + // >>> bicycle:8 + // >>> bicycle:9 + // STEP_END + + // Output: + // 1 + // bicycle:5 + // 1 + // bicycle:5 + // 5 + // bicycle:5 + // bicycle:6 + // bicycle:7 + // bicycle:8 + // bicycle:9 +} diff --git a/search_commands.go b/search_commands.go index 1312a78f0..df12bb3f9 100644 --- a/search_commands.go +++ b/search_commands.go @@ -240,13 +240,20 @@ type FTAggregateWithCursor struct { } type FTAggregateOptions struct { - Verbatim bool - LoadAll bool - Load []FTAggregateLoad - Timeout int - GroupBy []FTAggregateGroupBy - SortBy []FTAggregateSortBy - SortByMax int + Verbatim bool + LoadAll bool + Load []FTAggregateLoad + Timeout int + GroupBy []FTAggregateGroupBy + SortBy []FTAggregateSortBy + SortByMax int + // Scorer is used to set scoring function, if not set passed, a default will be used. + // The default scorer depends on the Redis version: + // - `BM25` for Redis >= 8 + // - `TFIDF` for Redis < 8 + Scorer string + // AddScores is available in Redis CE 8 + AddScores bool Apply []FTAggregateApply LimitOffset int Limit int @@ -490,6 +497,15 @@ func FTAggregateQuery(query string, options *FTAggregateOptions) AggregateQuery if options.Verbatim { queryArgs = append(queryArgs, "VERBATIM") } + + if options.Scorer != "" { + queryArgs = append(queryArgs, "SCORER", options.Scorer) + } + + if options.AddScores { + queryArgs = append(queryArgs, "ADDSCORES") + } + if options.LoadAll && options.Load != nil { panic("FT.AGGREGATE: LOADALL and LOAD are mutually exclusive") } @@ -505,9 +521,18 @@ func FTAggregateQuery(query string, options *FTAggregateOptions) AggregateQuery } } } + if options.Timeout > 0 { queryArgs = append(queryArgs, "TIMEOUT", options.Timeout) } + + for _, apply := range options.Apply { + queryArgs = append(queryArgs, "APPLY", apply.Field) + if apply.As != "" { + queryArgs = append(queryArgs, "AS", apply.As) + } + } + if options.GroupBy != nil { for _, groupBy := range options.GroupBy { queryArgs = append(queryArgs, "GROUPBY", len(groupBy.Fields)) @@ -549,12 +574,6 @@ func FTAggregateQuery(query string, options *FTAggregateOptions) AggregateQuery if options.SortByMax > 0 { queryArgs = append(queryArgs, "MAX", options.SortByMax) } - for _, apply := range options.Apply { - queryArgs = append(queryArgs, "APPLY", apply.Field) - if apply.As != "" { - queryArgs = append(queryArgs, "AS", apply.As) - } - } if options.LimitOffset > 0 { queryArgs = append(queryArgs, "LIMIT", options.LimitOffset) } @@ -581,6 +600,7 @@ func FTAggregateQuery(query string, options *FTAggregateOptions) AggregateQuery queryArgs = append(queryArgs, key, value) } } + if options.DialectVersion > 0 { queryArgs = append(queryArgs, "DIALECT", options.DialectVersion) } @@ -661,11 +681,12 @@ func (cmd *AggregateCmd) readReply(rd *proto.Reader) (err error) { data, err := rd.ReadSlice() if err != nil { cmd.err = err - return nil + return err } cmd.val, err = ProcessAggregateResult(data) if err != nil { cmd.err = err + return err } return nil } @@ -681,6 +702,12 @@ func (c cmdable) FTAggregateWithArgs(ctx context.Context, index string, query st if options.Verbatim { args = append(args, "VERBATIM") } + if options.Scorer != "" { + args = append(args, "SCORER", options.Scorer) + } + if options.AddScores { + args = append(args, "ADDSCORES") + } if options.LoadAll && options.Load != nil { panic("FT.AGGREGATE: LOADALL and LOAD are mutually exclusive") } @@ -699,6 +726,12 @@ func (c cmdable) FTAggregateWithArgs(ctx context.Context, index string, query st if options.Timeout > 0 { args = append(args, "TIMEOUT", options.Timeout) } + for _, apply := range options.Apply { + args = append(args, "APPLY", apply.Field) + if apply.As != "" { + args = append(args, "AS", apply.As) + } + } if options.GroupBy != nil { for _, groupBy := range options.GroupBy { args = append(args, "GROUPBY", len(groupBy.Fields)) @@ -740,12 +773,6 @@ func (c cmdable) FTAggregateWithArgs(ctx context.Context, index string, query st if options.SortByMax > 0 { args = append(args, "MAX", options.SortByMax) } - for _, apply := range options.Apply { - args = append(args, "APPLY", apply.Field) - if apply.As != "" { - args = append(args, "AS", apply.As) - } - } if options.LimitOffset > 0 { args = append(args, "LIMIT", options.LimitOffset) } @@ -1693,7 +1720,8 @@ func (cmd *FTSearchCmd) readReply(rd *proto.Reader) (err error) { // FTSearch - Executes a search query on an index. // The 'index' parameter specifies the index to search, and the 'query' parameter specifies the search query. -// For more information, please refer to the Redis documentation: +// For more information, please refer to the Redis documentation about [FT.SEARCH]. +// // [FT.SEARCH]: (https://redis.io/commands/ft.search/) func (c cmdable) FTSearch(ctx context.Context, index string, query string) *FTSearchCmd { args := []interface{}{"FT.SEARCH", index, query} @@ -1704,6 +1732,12 @@ func (c cmdable) FTSearch(ctx context.Context, index string, query string) *FTSe type SearchQuery []interface{} +// FTSearchQuery - Executes a search query on an index with additional options. +// The 'index' parameter specifies the index to search, the 'query' parameter specifies the search query, +// and the 'options' parameter specifies additional options for the search. +// For more information, please refer to the Redis documentation about [FT.SEARCH]. +// +// [FT.SEARCH]: (https://redis.io/commands/ft.search/) func FTSearchQuery(query string, options *FTSearchOptions) SearchQuery { queryArgs := []interface{}{query} if options != nil { @@ -1816,7 +1850,8 @@ func FTSearchQuery(query string, options *FTSearchOptions) SearchQuery { // FTSearchWithArgs - Executes a search query on an index with additional options. // The 'index' parameter specifies the index to search, the 'query' parameter specifies the search query, // and the 'options' parameter specifies additional options for the search. -// For more information, please refer to the Redis documentation: +// For more information, please refer to the Redis documentation about [FT.SEARCH]. +// // [FT.SEARCH]: (https://redis.io/commands/ft.search/) func (c cmdable) FTSearchWithArgs(ctx context.Context, index string, query string, options *FTSearchOptions) *FTSearchCmd { args := []interface{}{"FT.SEARCH", index, query} @@ -1908,7 +1943,7 @@ func (c cmdable) FTSearchWithArgs(ctx context.Context, index string, query strin } } if options.SortByWithCount { - args = append(args, "WITHCOUT") + args = append(args, "WITHCOUNT") } } if options.LimitOffset >= 0 && options.Limit > 0 { diff --git a/search_test.go b/search_test.go index a409fc78a..e4e552152 100644 --- a/search_test.go +++ b/search_test.go @@ -2,6 +2,8 @@ package redis_test import ( "context" + "fmt" + "strconv" "time" . "github.com/bsm/ginkgo/v2" @@ -127,8 +129,11 @@ var _ = Describe("RediSearch commands Resp 2", Label("search"), func() { res3, err := client.FTSearchWithArgs(ctx, "num", "foo", &redis.FTSearchOptions{NoContent: true, SortBy: []redis.FTSearchSortBy{sortBy2}, SortByWithCount: true}).Result() Expect(err).NotTo(HaveOccurred()) - Expect(res3.Total).To(BeEquivalentTo(int64(0))) + Expect(res3.Total).To(BeEquivalentTo(int64(3))) + res4, err := client.FTSearchWithArgs(ctx, "num", "notpresentf00", &redis.FTSearchOptions{NoContent: true, SortBy: []redis.FTSearchSortBy{sortBy2}, SortByWithCount: true}).Result() + Expect(err).NotTo(HaveOccurred()) + Expect(res4.Total).To(BeEquivalentTo(int64(0))) }) It("should FTCreate and FTSearch example", Label("search", "ftcreate", "ftsearch"), func() { @@ -640,6 +645,100 @@ var _ = Describe("RediSearch commands Resp 2", Label("search"), func() { Expect(res.Rows[0].Fields["t2"]).To(BeEquivalentTo("world")) }) + It("should FTAggregate with scorer and addscores", Label("search", "ftaggregate", "NonRedisEnterprise"), func() { + SkipBeforeRedisMajor(8, "ADDSCORES is available in Redis CE 8") + title := &redis.FieldSchema{FieldName: "title", FieldType: redis.SearchFieldTypeText, Sortable: false} + description := &redis.FieldSchema{FieldName: "description", FieldType: redis.SearchFieldTypeText, Sortable: false} + val, err := client.FTCreate(ctx, "idx1", &redis.FTCreateOptions{OnHash: true, Prefix: []interface{}{"product:"}}, title, description).Result() + Expect(err).NotTo(HaveOccurred()) + Expect(val).To(BeEquivalentTo("OK")) + WaitForIndexing(client, "idx1") + + client.HSet(ctx, "product:1", "title", "New Gaming Laptop", "description", "this is not a desktop") + client.HSet(ctx, "product:2", "title", "Super Old Not Gaming Laptop", "description", "this laptop is not a new laptop but it is a laptop") + client.HSet(ctx, "product:3", "title", "Office PC", "description", "office desktop pc") + + options := &redis.FTAggregateOptions{ + AddScores: true, + Scorer: "BM25", + SortBy: []redis.FTAggregateSortBy{{ + FieldName: "@__score", + Desc: true, + }}, + } + + res, err := client.FTAggregateWithArgs(ctx, "idx1", "laptop", options).Result() + Expect(err).NotTo(HaveOccurred()) + Expect(res).ToNot(BeNil()) + Expect(len(res.Rows)).To(BeEquivalentTo(2)) + score1, err := strconv.ParseFloat(fmt.Sprintf("%s", res.Rows[0].Fields["__score"]), 64) + Expect(err).NotTo(HaveOccurred()) + score2, err := strconv.ParseFloat(fmt.Sprintf("%s", res.Rows[1].Fields["__score"]), 64) + Expect(err).NotTo(HaveOccurred()) + Expect(score1).To(BeNumerically(">", score2)) + + optionsDM := &redis.FTAggregateOptions{ + AddScores: true, + Scorer: "DISMAX", + SortBy: []redis.FTAggregateSortBy{{ + FieldName: "@__score", + Desc: true, + }}, + } + + resDM, err := client.FTAggregateWithArgs(ctx, "idx1", "laptop", optionsDM).Result() + Expect(err).NotTo(HaveOccurred()) + Expect(resDM).ToNot(BeNil()) + Expect(len(resDM.Rows)).To(BeEquivalentTo(2)) + score1DM, err := strconv.ParseFloat(fmt.Sprintf("%s", resDM.Rows[0].Fields["__score"]), 64) + Expect(err).NotTo(HaveOccurred()) + score2DM, err := strconv.ParseFloat(fmt.Sprintf("%s", resDM.Rows[1].Fields["__score"]), 64) + Expect(err).NotTo(HaveOccurred()) + Expect(score1DM).To(BeNumerically(">", score2DM)) + + Expect(score1DM).To(BeEquivalentTo(float64(4))) + Expect(score2DM).To(BeEquivalentTo(float64(1))) + Expect(score1).NotTo(BeEquivalentTo(score1DM)) + Expect(score2).NotTo(BeEquivalentTo(score2DM)) + }) + + It("should FTAggregate apply and groupby", Label("search", "ftaggregate"), func() { + text1 := &redis.FieldSchema{FieldName: "PrimaryKey", FieldType: redis.SearchFieldTypeText, Sortable: true} + num1 := &redis.FieldSchema{FieldName: "CreatedDateTimeUTC", FieldType: redis.SearchFieldTypeNumeric, Sortable: true} + val, err := client.FTCreate(ctx, "idx1", &redis.FTCreateOptions{}, text1, num1).Result() + Expect(err).NotTo(HaveOccurred()) + Expect(val).To(BeEquivalentTo("OK")) + WaitForIndexing(client, "idx1") + + // 6 feb + client.HSet(ctx, "doc1", "PrimaryKey", "9::362330", "CreatedDateTimeUTC", "1738823999") + + // 12 feb + client.HSet(ctx, "doc2", "PrimaryKey", "9::362329", "CreatedDateTimeUTC", "1739342399") + client.HSet(ctx, "doc3", "PrimaryKey", "9::362329", "CreatedDateTimeUTC", "1739353199") + + reducer := redis.FTAggregateReducer{Reducer: redis.SearchCount, As: "perDay"} + + options := &redis.FTAggregateOptions{ + Apply: []redis.FTAggregateApply{{Field: "floor(@CreatedDateTimeUTC /(60*60*24))", As: "TimestampAsDay"}}, + GroupBy: []redis.FTAggregateGroupBy{{ + Fields: []interface{}{"@TimestampAsDay"}, + Reduce: []redis.FTAggregateReducer{reducer}, + }}, + SortBy: []redis.FTAggregateSortBy{{ + FieldName: "@perDay", + Desc: true, + }}, + } + + res, err := client.FTAggregateWithArgs(ctx, "idx1", "*", options).Result() + Expect(err).NotTo(HaveOccurred()) + Expect(res).ToNot(BeNil()) + Expect(len(res.Rows)).To(BeEquivalentTo(2)) + Expect(res.Rows[0].Fields["perDay"]).To(BeEquivalentTo("2")) + Expect(res.Rows[1].Fields["perDay"]).To(BeEquivalentTo("1")) + }) + It("should FTAggregate apply", Label("search", "ftaggregate"), func() { text1 := &redis.FieldSchema{FieldName: "PrimaryKey", FieldType: redis.SearchFieldTypeText, Sortable: true} num1 := &redis.FieldSchema{FieldName: "CreatedDateTimeUTC", FieldType: redis.SearchFieldTypeNumeric, Sortable: true} @@ -684,7 +783,6 @@ var _ = Describe("RediSearch commands Resp 2", Label("search"), func() { Expect(res.Rows[0].Fields["age"]).To(BeEquivalentTo("19")) Expect(res.Rows[1].Fields["age"]).To(BeEquivalentTo("25")) } - }) It("should FTSearch SkipInitialScan", Label("search", "ftsearch"), func() {