...

Source file src/github.com/redis/go-redis/v9/doctests/query_agg_test.go

Documentation: github.com/redis/go-redis/v9/doctests

     1  // EXAMPLE: query_agg
     2  // HIDE_START
     3  package example_commands_test
     4  
     5  import (
     6  	"context"
     7  	"fmt"
     8  	"sort"
     9  
    10  	"github.com/redis/go-redis/v9"
    11  )
    12  
    13  func ExampleClient_query_agg() {
    14  	ctx := context.Background()
    15  
    16  	rdb := redis.NewClient(&redis.Options{
    17  		Addr:     "localhost:6379",
    18  		Password: "", // no password docs
    19  		DB:       0,  // use default DB
    20  		Protocol: 2,
    21  	})
    22  	// HIDE_END
    23  	// REMOVE_START
    24  	// start with fresh database
    25  	rdb.FlushDB(ctx)
    26  	rdb.FTDropIndex(ctx, "idx:bicycle")
    27  	rdb.FTDropIndex(ctx, "idx:email")
    28  	// REMOVE_END
    29  
    30  	_, err := rdb.FTCreate(ctx, "idx:bicycle",
    31  		&redis.FTCreateOptions{
    32  			OnJSON: true,
    33  			Prefix: []interface{}{"bicycle:"},
    34  		},
    35  		&redis.FieldSchema{
    36  			FieldName: "$.brand",
    37  			As:        "brand",
    38  			FieldType: redis.SearchFieldTypeText,
    39  		},
    40  		&redis.FieldSchema{
    41  			FieldName: "$.model",
    42  			As:        "model",
    43  			FieldType: redis.SearchFieldTypeText,
    44  		},
    45  		&redis.FieldSchema{
    46  			FieldName: "$.description",
    47  			As:        "description",
    48  			FieldType: redis.SearchFieldTypeText,
    49  		},
    50  		&redis.FieldSchema{
    51  			FieldName: "$.price",
    52  			As:        "price",
    53  			FieldType: redis.SearchFieldTypeNumeric,
    54  		},
    55  		&redis.FieldSchema{
    56  			FieldName: "$.condition",
    57  			As:        "condition",
    58  			FieldType: redis.SearchFieldTypeTag,
    59  		},
    60  	).Result()
    61  
    62  	if err != nil {
    63  		panic(err)
    64  	}
    65  
    66  	exampleJsons := []map[string]interface{}{
    67  		{
    68  			"pickup_zone": "POLYGON((-74.0610 40.7578, -73.9510 40.7578, -73.9510 40.6678, " +
    69  				"-74.0610 40.6678, -74.0610 40.7578))",
    70  			"store_location": "-74.0060,40.7128",
    71  			"brand":          "Velorim",
    72  			"model":          "Jigger",
    73  			"price":          270,
    74  			"description": "Small and powerful, the Jigger is the best ride for the smallest of tikes! " +
    75  				"This is the tiniest kids’ pedal bike on the market available without a coaster brake, the Jigger " +
    76  				"is the vehicle of choice for the rare tenacious little rider raring to go.",
    77  			"condition": "new",
    78  		},
    79  		{
    80  			"pickup_zone": "POLYGON((-118.2887 34.0972, -118.1987 34.0972, -118.1987 33.9872, " +
    81  				"-118.2887 33.9872, -118.2887 34.0972))",
    82  			"store_location": "-118.2437,34.0522",
    83  			"brand":          "Bicyk",
    84  			"model":          "Hillcraft",
    85  			"price":          1200,
    86  			"description": "Kids want to ride with as little weight as possible. Especially " +
    87  				"on an incline! They may be at the age when a 27.5'' wheel bike is just too clumsy coming " +
    88  				"off a 24'' bike. The Hillcraft 26 is just the solution they need!",
    89  			"condition": "used",
    90  		},
    91  		{
    92  			"pickup_zone": "POLYGON((-87.6848 41.9331, -87.5748 41.9331, -87.5748 41.8231, " +
    93  				"-87.6848 41.8231, -87.6848 41.9331))",
    94  			"store_location": "-87.6298,41.8781",
    95  			"brand":          "Nord",
    96  			"model":          "Chook air 5",
    97  			"price":          815,
    98  			"description": "The Chook Air 5  gives kids aged six years and older a durable " +
    99  				"and uberlight mountain bike for their first experience on tracks and easy cruising through " +
   100  				"forests and fields. The lower  top tube makes it easy to mount and dismount in any " +
   101  				"situation, giving your kids greater safety on the trails.",
   102  			"condition": "used",
   103  		},
   104  		{
   105  			"pickup_zone": "POLYGON((-80.2433 25.8067, -80.1333 25.8067, -80.1333 25.6967, " +
   106  				"-80.2433 25.6967, -80.2433 25.8067))",
   107  			"store_location": "-80.1918,25.7617",
   108  			"brand":          "Eva",
   109  			"model":          "Eva 291",
   110  			"price":          3400,
   111  			"description": "The sister company to Nord, Eva launched in 2005 as the first " +
   112  				"and only women-dedicated bicycle brand. Designed by women for women, allEva bikes " +
   113  				"are optimized for the feminine physique using analytics from a body metrics database. " +
   114  				"If you like 29ers, try the Eva 291. It’s a brand new bike for 2022.. This " +
   115  				"full-suspension, cross-country ride has been designed for velocity. The 291 has " +
   116  				"100mm of front and rear travel, a superlight aluminum frame and fast-rolling " +
   117  				"29-inch wheels. Yippee!",
   118  			"condition": "used",
   119  		},
   120  		{
   121  			"pickup_zone": "POLYGON((-122.4644 37.8199, -122.3544 37.8199, -122.3544 37.7099, " +
   122  				"-122.4644 37.7099, -122.4644 37.8199))",
   123  			"store_location": "-122.4194,37.7749",
   124  			"brand":          "Noka Bikes",
   125  			"model":          "Kahuna",
   126  			"price":          3200,
   127  			"description": "Whether you want to try your hand at XC racing or are looking " +
   128  				"for a lively trail bike that's just as inspiring on the climbs as it is over rougher " +
   129  				"ground, the Wilder is one heck of a bike built specifically for short women. Both the " +
   130  				"frames and components have been tweaked to include a women’s saddle, different bars " +
   131  				"and unique colourway.",
   132  			"condition": "used",
   133  		},
   134  		{
   135  			"pickup_zone": "POLYGON((-0.1778 51.5524, 0.0822 51.5524, 0.0822 51.4024, " +
   136  				"-0.1778 51.4024, -0.1778 51.5524))",
   137  			"store_location": "-0.1278,51.5074",
   138  			"brand":          "Breakout",
   139  			"model":          "XBN 2.1 Alloy",
   140  			"price":          810,
   141  			"description": "The XBN 2.1 Alloy is our entry-level road bike – but that’s " +
   142  				"not to say that it’s a basic machine. With an internal weld aluminium frame, a full " +
   143  				"carbon fork, and the slick-shifting Claris gears from Shimano’s, this is a bike which " +
   144  				"doesn’t break the bank and delivers craved performance.",
   145  			"condition": "new",
   146  		},
   147  		{
   148  			"pickup_zone": "POLYGON((2.1767 48.9016, 2.5267 48.9016, 2.5267 48.5516, " +
   149  				"2.1767 48.5516, 2.1767 48.9016))",
   150  			"store_location": "2.3522,48.8566",
   151  			"brand":          "ScramBikes",
   152  			"model":          "WattBike",
   153  			"price":          2300,
   154  			"description": "The WattBike is the best e-bike for people who still " +
   155  				"feel young at heart. It has a Bafang 1000W mid-drive system and a 48V 17.5AH " +
   156  				"Samsung Lithium-Ion battery, allowing you to ride for more than 60 miles on one " +
   157  				"charge. It’s great for tackling hilly terrain or if you just fancy a more " +
   158  				"leisurely ride. With three working modes, you can choose between E-bike, " +
   159  				"assisted bicycle, and normal bike modes.",
   160  			"condition": "new",
   161  		},
   162  		{
   163  			"pickup_zone": "POLYGON((13.3260 52.5700, 13.6550 52.5700, 13.6550 52.2700, " +
   164  				"13.3260 52.2700, 13.3260 52.5700))",
   165  			"store_location": "13.4050,52.5200",
   166  			"brand":          "Peaknetic",
   167  			"model":          "Secto",
   168  			"price":          430,
   169  			"description": "If you struggle with stiff fingers or a kinked neck or " +
   170  				"back after a few minutes on the road, this lightweight, aluminum bike alleviates " +
   171  				"those issues and allows you to enjoy the ride. From the ergonomic grips to the " +
   172  				"lumbar-supporting seat position, the Roll Low-Entry offers incredible comfort. " +
   173  				"The rear-inclined seat tube facilitates stability by allowing you to put a foot " +
   174  				"on the ground to balance at a stop, and the low step-over frame makes it " +
   175  				"accessible for all ability and mobility levels. The saddle is very soft, with " +
   176  				"a wide back to support your hip joints and a cutout in the center to redistribute " +
   177  				"that pressure. Rim brakes deliver satisfactory braking control, and the wide tires " +
   178  				"provide a smooth, stable ride on paved roads and gravel. Rack and fender mounts " +
   179  				"facilitate setting up the Roll Low-Entry as your preferred commuter, and the " +
   180  				"BMX-like handlebar offers space for mounting a flashlight, bell, or phone holder.",
   181  			"condition": "new",
   182  		},
   183  		{
   184  			"pickup_zone": "POLYGON((1.9450 41.4301, 2.4018 41.4301, 2.4018 41.1987, " +
   185  				"1.9450 41.1987, 1.9450 41.4301))",
   186  			"store_location": "2.1734, 41.3851",
   187  			"brand":          "nHill",
   188  			"model":          "Summit",
   189  			"price":          1200,
   190  			"description": "This budget mountain bike from nHill performs well both " +
   191  				"on bike paths and on the trail. The fork with 100mm of travel absorbs rough " +
   192  				"terrain. Fat Kenda Booster tires give you grip in corners and on wet trails. " +
   193  				"The Shimano Tourney drivetrain offered enough gears for finding a comfortable " +
   194  				"pace to ride uphill, and the Tektro hydraulic disc brakes break smoothly. " +
   195  				"Whether you want an affordable bike that you can take to work, but also take " +
   196  				"trail in mountains on the weekends or you’re just after a stable, comfortable " +
   197  				"ride for the bike path, the Summit gives a good value for money.",
   198  			"condition": "new",
   199  		},
   200  		{
   201  			"pickup_zone": "POLYGON((12.4464 42.1028, 12.5464 42.1028, " +
   202  				"12.5464 41.7028, 12.4464 41.7028, 12.4464 42.1028))",
   203  			"store_location": "12.4964,41.9028",
   204  			"model":          "ThrillCycle",
   205  			"brand":          "BikeShind",
   206  			"price":          815,
   207  			"description": "An artsy,  retro-inspired bicycle that’s as " +
   208  				"functional as it is pretty: The ThrillCycle steel frame offers a smooth ride. " +
   209  				"A 9-speed drivetrain has enough gears for coasting in the city, but we wouldn’t " +
   210  				"suggest taking it to the mountains. Fenders protect you from mud, and a rear " +
   211  				"basket lets you transport groceries, flowers and books. The ThrillCycle comes " +
   212  				"with a limited lifetime warranty, so this little guy will last you long " +
   213  				"past graduation.",
   214  			"condition": "refurbished",
   215  		},
   216  	}
   217  
   218  	for i, json := range exampleJsons {
   219  		_, err := rdb.JSONSet(ctx, fmt.Sprintf("bicycle:%v", i), "$", json).Result()
   220  
   221  		if err != nil {
   222  			panic(err)
   223  		}
   224  	}
   225  
   226  	// STEP_START agg1
   227  	res1, err := rdb.FTAggregateWithArgs(ctx,
   228  		"idx:bicycle",
   229  		"@condition:{new}",
   230  		&redis.FTAggregateOptions{
   231  			Apply: []redis.FTAggregateApply{
   232  				{
   233  					Field: "@price - (@price * 0.1)",
   234  					As:    "discounted",
   235  				},
   236  			},
   237  			Load: []redis.FTAggregateLoad{
   238  				{Field: "__key"},
   239  				{Field: "price"},
   240  			},
   241  		},
   242  	).Result()
   243  
   244  	if err != nil {
   245  		panic(err)
   246  	}
   247  
   248  	fmt.Println(len(res1.Rows)) // >>> 5
   249  
   250  	sort.Slice(res1.Rows, func(i, j int) bool {
   251  		return res1.Rows[i].Fields["__key"].(string) <
   252  			res1.Rows[j].Fields["__key"].(string)
   253  	})
   254  
   255  	for _, row := range res1.Rows {
   256  		fmt.Printf(
   257  			"__key=%v, discounted=%v, price=%v\n",
   258  			row.Fields["__key"],
   259  			row.Fields["discounted"],
   260  			row.Fields["price"],
   261  		)
   262  	}
   263  	// >>> __key=bicycle:0, discounted=243, price=270
   264  	// >>> __key=bicycle:5, discounted=729, price=810
   265  	// >>> __key=bicycle:6, discounted=2070, price=2300
   266  	// >>> __key=bicycle:7, discounted=387, price=430
   267  	// >>> __key=bicycle:8, discounted=1080, price=1200
   268  	// STEP_END
   269  
   270  	// STEP_START agg2
   271  	res2, err := rdb.FTAggregateWithArgs(ctx,
   272  		"idx:bicycle", "*",
   273  		&redis.FTAggregateOptions{
   274  			Load: []redis.FTAggregateLoad{
   275  				{Field: "price"},
   276  			},
   277  			Apply: []redis.FTAggregateApply{
   278  				{
   279  					Field: "@price<1000",
   280  					As:    "price_category",
   281  				},
   282  			},
   283  			GroupBy: []redis.FTAggregateGroupBy{
   284  				{
   285  					Fields: []interface{}{"@condition"},
   286  					Reduce: []redis.FTAggregateReducer{
   287  						{
   288  							Reducer: redis.SearchSum,
   289  							Args:    []interface{}{"@price_category"},
   290  							As:      "num_affordable",
   291  						},
   292  					},
   293  				},
   294  			},
   295  		},
   296  	).Result()
   297  
   298  	if err != nil {
   299  		panic(err)
   300  	}
   301  
   302  	fmt.Println(len(res2.Rows)) // >>> 3
   303  
   304  	sort.Slice(res2.Rows, func(i, j int) bool {
   305  		return res2.Rows[i].Fields["condition"].(string) <
   306  			res2.Rows[j].Fields["condition"].(string)
   307  	})
   308  
   309  	for _, row := range res2.Rows {
   310  		fmt.Printf(
   311  			"condition=%v, num_affordable=%v\n",
   312  			row.Fields["condition"],
   313  			row.Fields["num_affordable"],
   314  		)
   315  	}
   316  	// >>> condition=new, num_affordable=3
   317  	// >>> condition=refurbished, num_affordable=1
   318  	// >>> condition=used, num_affordable=1
   319  	// STEP_END
   320  
   321  	// STEP_START agg3
   322  
   323  	res3, err := rdb.FTAggregateWithArgs(ctx,
   324  		"idx:bicycle", "*",
   325  		&redis.FTAggregateOptions{
   326  			Apply: []redis.FTAggregateApply{
   327  				{
   328  					Field: "'bicycle'",
   329  					As:    "type",
   330  				},
   331  			},
   332  			GroupBy: []redis.FTAggregateGroupBy{
   333  				{
   334  					Fields: []interface{}{"@type"},
   335  					Reduce: []redis.FTAggregateReducer{
   336  						{
   337  							Reducer: redis.SearchCount,
   338  							As:      "num_total",
   339  						},
   340  					},
   341  				},
   342  			},
   343  		},
   344  	).Result()
   345  
   346  	if err != nil {
   347  		panic(err)
   348  	}
   349  
   350  	fmt.Println(len(res3.Rows)) // >>> 1
   351  
   352  	for _, row := range res3.Rows {
   353  		fmt.Printf(
   354  			"type=%v, num_total=%v\n",
   355  			row.Fields["type"],
   356  			row.Fields["num_total"],
   357  		)
   358  	}
   359  	// type=bicycle, num_total=10
   360  	// STEP_END
   361  
   362  	// STEP_START agg4
   363  	res4, err := rdb.FTAggregateWithArgs(ctx,
   364  		"idx:bicycle", "*",
   365  		&redis.FTAggregateOptions{
   366  			Load: []redis.FTAggregateLoad{
   367  				{Field: "__key"},
   368  			},
   369  			GroupBy: []redis.FTAggregateGroupBy{
   370  				{
   371  					Fields: []interface{}{"@condition"},
   372  					Reduce: []redis.FTAggregateReducer{
   373  						{
   374  							Reducer: redis.SearchToList,
   375  							Args:    []interface{}{"__key"},
   376  							As:      "bicycles",
   377  						},
   378  					},
   379  				},
   380  			},
   381  		},
   382  	).Result()
   383  
   384  	if err != nil {
   385  		panic(err)
   386  	}
   387  
   388  	fmt.Println(len(res4.Rows)) // >>> 3
   389  
   390  	sort.Slice(res4.Rows, func(i, j int) bool {
   391  		return res4.Rows[i].Fields["condition"].(string) <
   392  			res4.Rows[j].Fields["condition"].(string)
   393  	})
   394  
   395  	for _, row := range res4.Rows {
   396  		rowBikes := row.Fields["bicycles"].([]interface{})
   397  		bikes := make([]string, len(rowBikes))
   398  
   399  		for i, rowBike := range rowBikes {
   400  			bikes[i] = rowBike.(string)
   401  		}
   402  
   403  		sort.Slice(bikes, func(i, j int) bool {
   404  			return bikes[i] < bikes[j]
   405  		})
   406  
   407  		fmt.Printf(
   408  			"condition=%v, bicycles=%v\n",
   409  			row.Fields["condition"],
   410  			bikes,
   411  		)
   412  	}
   413  	// >>> condition=new, bicycles=[bicycle:0 bicycle:5 bicycle:6 bicycle:7 bicycle:8]
   414  	// >>> condition=refurbished, bicycles=[bicycle:9]
   415  	// >>> condition=used, bicycles=[bicycle:1 bicycle:2 bicycle:3 bicycle:4]
   416  	// STEP_END
   417  
   418  	// Output:
   419  	// 5
   420  	// __key=bicycle:0, discounted=243, price=270
   421  	// __key=bicycle:5, discounted=729, price=810
   422  	// __key=bicycle:6, discounted=2070, price=2300
   423  	// __key=bicycle:7, discounted=387, price=430
   424  	// __key=bicycle:8, discounted=1080, price=1200
   425  	// 3
   426  	// condition=new, num_affordable=3
   427  	// condition=refurbished, num_affordable=1
   428  	// condition=used, num_affordable=1
   429  	// 1
   430  	// type=bicycle, num_total=10
   431  	// 3
   432  	// condition=new, bicycles=[bicycle:0 bicycle:5 bicycle:6 bicycle:7 bicycle:8]
   433  	// condition=refurbished, bicycles=[bicycle:9]
   434  	// condition=used, bicycles=[bicycle:1 bicycle:2 bicycle:3 bicycle:4]
   435  }
   436  

View as plain text