...

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

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

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

View as plain text