...

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

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

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

View as plain text