...

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

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

     1  // EXAMPLE: go_home_json
     2  // HIDE_START
     3  package example_commands_test
     4  
     5  // HIDE_END
     6  // STEP_START import
     7  import (
     8  	"context"
     9  	"fmt"
    10  	"sort"
    11  
    12  	"github.com/redis/go-redis/v9"
    13  )
    14  
    15  // STEP_END
    16  
    17  func ExampleClient_search_json() {
    18  	// STEP_START connect
    19  	ctx := context.Background()
    20  
    21  	rdb := redis.NewClient(&redis.Options{
    22  		Addr:     "localhost:6379",
    23  		Password: "", // no password docs
    24  		DB:       0,  // use default DB
    25  		Protocol: 2,
    26  	})
    27  	// STEP_END
    28  	// REMOVE_START
    29  	// make sure we are working with fresh database
    30  	rdb.FlushDB(ctx)
    31  	rdb.Del(ctx, "user:1", "user:2", "user:3")
    32  	rdb.FTDropIndex(ctx, "idx:users")
    33  	// REMOVE_END
    34  
    35  	// STEP_START create_data
    36  	user1 := map[string]interface{}{
    37  		"name":  "Paul John",
    38  		"email": "paul.john@example.com",
    39  		"age":   42,
    40  		"city":  "London",
    41  	}
    42  
    43  	user2 := map[string]interface{}{
    44  		"name":  "Eden Zamir",
    45  		"email": "eden.zamir@example.com",
    46  		"age":   29,
    47  		"city":  "Tel Aviv",
    48  	}
    49  
    50  	user3 := map[string]interface{}{
    51  		"name":  "Paul Zamir",
    52  		"email": "paul.zamir@example.com",
    53  		"age":   35,
    54  		"city":  "Tel Aviv",
    55  	}
    56  	// STEP_END
    57  
    58  	// STEP_START make_index
    59  	_, err := rdb.FTCreate(
    60  		ctx,
    61  		"idx:users",
    62  		// Options:
    63  		&redis.FTCreateOptions{
    64  			OnJSON: true,
    65  			Prefix: []interface{}{"user:"},
    66  		},
    67  		// Index schema fields:
    68  		&redis.FieldSchema{
    69  			FieldName: "$.name",
    70  			As:        "name",
    71  			FieldType: redis.SearchFieldTypeText,
    72  		},
    73  		&redis.FieldSchema{
    74  			FieldName: "$.city",
    75  			As:        "city",
    76  			FieldType: redis.SearchFieldTypeTag,
    77  		},
    78  		&redis.FieldSchema{
    79  			FieldName: "$.age",
    80  			As:        "age",
    81  			FieldType: redis.SearchFieldTypeNumeric,
    82  		},
    83  	).Result()
    84  
    85  	if err != nil {
    86  		panic(err)
    87  	}
    88  	// STEP_END
    89  
    90  	// STEP_START add_data
    91  	_, err = rdb.JSONSet(ctx, "user:1", "$", user1).Result()
    92  
    93  	if err != nil {
    94  		panic(err)
    95  	}
    96  
    97  	_, err = rdb.JSONSet(ctx, "user:2", "$", user2).Result()
    98  
    99  	if err != nil {
   100  		panic(err)
   101  	}
   102  
   103  	_, err = rdb.JSONSet(ctx, "user:3", "$", user3).Result()
   104  
   105  	if err != nil {
   106  		panic(err)
   107  	}
   108  	// STEP_END
   109  
   110  	// STEP_START query1
   111  	findPaulResult, err := rdb.FTSearch(
   112  		ctx,
   113  		"idx:users",
   114  		"Paul @age:[30 40]",
   115  	).Result()
   116  
   117  	if err != nil {
   118  		panic(err)
   119  	}
   120  
   121  	fmt.Println(findPaulResult)
   122  	// >>> {1 [{user:3 <nil> <nil> <nil> map[$:{"age":35,"city":"Tel Aviv"...
   123  	// STEP_END
   124  
   125  	// STEP_START query2
   126  	citiesResult, err := rdb.FTSearchWithArgs(
   127  		ctx,
   128  		"idx:users",
   129  		"Paul",
   130  		&redis.FTSearchOptions{
   131  			Return: []redis.FTSearchReturn{
   132  				{
   133  					FieldName: "$.city",
   134  					As:        "city",
   135  				},
   136  			},
   137  		},
   138  	).Result()
   139  
   140  	if err != nil {
   141  		panic(err)
   142  	}
   143  
   144  	sort.Slice(citiesResult.Docs, func(i, j int) bool {
   145  		return citiesResult.Docs[i].Fields["city"] < citiesResult.Docs[j].Fields["city"]
   146  	})
   147  
   148  	for _, result := range citiesResult.Docs {
   149  		fmt.Println(result.Fields["city"])
   150  	}
   151  	// >>> London
   152  	// >>> Tel Aviv
   153  	// STEP_END
   154  
   155  	// STEP_START query2count_only
   156  	citiesResult2, err := rdb.FTSearchWithArgs(
   157  		ctx,
   158  		"idx:users",
   159  		"Paul",
   160  		&redis.FTSearchOptions{
   161  			Return: []redis.FTSearchReturn{
   162  				{
   163  					FieldName: "$.city",
   164  					As:        "city",
   165  				},
   166  			},
   167  			CountOnly: true,
   168  		},
   169  	).Result()
   170  
   171  	if err != nil {
   172  		panic(err)
   173  	}
   174  
   175  	// The `Total` field has the correct number of docs found
   176  	// by the query but the `Docs` slice is empty.
   177  	fmt.Println(len(citiesResult2.Docs)) // >>> 0
   178  	fmt.Println(citiesResult2.Total)     // >>> 2
   179  	// STEP_END
   180  
   181  	// STEP_START query3
   182  	aggOptions := redis.FTAggregateOptions{
   183  		GroupBy: []redis.FTAggregateGroupBy{
   184  			{
   185  				Fields: []interface{}{"@city"},
   186  				Reduce: []redis.FTAggregateReducer{
   187  					{
   188  						Reducer: redis.SearchCount,
   189  						As:      "count",
   190  					},
   191  				},
   192  			},
   193  		},
   194  	}
   195  
   196  	aggResult, err := rdb.FTAggregateWithArgs(
   197  		ctx,
   198  		"idx:users",
   199  		"*",
   200  		&aggOptions,
   201  	).Result()
   202  
   203  	if err != nil {
   204  		panic(err)
   205  	}
   206  
   207  	sort.Slice(aggResult.Rows, func(i, j int) bool {
   208  		return aggResult.Rows[i].Fields["city"].(string) <
   209  			aggResult.Rows[j].Fields["city"].(string)
   210  	})
   211  
   212  	for _, row := range aggResult.Rows {
   213  		fmt.Printf("%v - %v\n",
   214  			row.Fields["city"], row.Fields["count"],
   215  		)
   216  	}
   217  	// >>> City: London - 1
   218  	// >>> City: Tel Aviv - 2
   219  	// STEP_END
   220  
   221  	// Output:
   222  	// {1 [{user:3 <nil> <nil> <nil> map[$:{"age":35,"city":"Tel Aviv","email":"paul.zamir@example.com","name":"Paul Zamir"}] <nil>}]}
   223  	// London
   224  	// Tel Aviv
   225  	// 0
   226  	// 2
   227  	// London - 1
   228  	// Tel Aviv - 2
   229  }
   230  
   231  func ExampleClient_search_hash() {
   232  	ctx := context.Background()
   233  
   234  	rdb := redis.NewClient(&redis.Options{
   235  		Addr:     "localhost:6379",
   236  		Password: "", // no password docs
   237  		DB:       0,  // use default DB
   238  		Protocol: 2,
   239  	})
   240  
   241  	// REMOVE_START
   242  	rdb.Del(ctx, "huser:1", "huser:2", "huser:3")
   243  	rdb.FTDropIndex(ctx, "hash-idx:users")
   244  	// REMOVE_END
   245  
   246  	// STEP_START make_hash_index
   247  	_, err := rdb.FTCreate(
   248  		ctx,
   249  		"hash-idx:users",
   250  		// Options:
   251  		&redis.FTCreateOptions{
   252  			OnHash: true,
   253  			Prefix: []interface{}{"huser:"},
   254  		},
   255  		// Index schema fields:
   256  		&redis.FieldSchema{
   257  			FieldName: "name",
   258  			FieldType: redis.SearchFieldTypeText,
   259  		},
   260  		&redis.FieldSchema{
   261  			FieldName: "city",
   262  			FieldType: redis.SearchFieldTypeTag,
   263  		},
   264  		&redis.FieldSchema{
   265  			FieldName: "age",
   266  			FieldType: redis.SearchFieldTypeNumeric,
   267  		},
   268  	).Result()
   269  
   270  	if err != nil {
   271  		panic(err)
   272  	}
   273  	// STEP_END
   274  
   275  	user1 := map[string]interface{}{
   276  		"name":  "Paul John",
   277  		"email": "paul.john@example.com",
   278  		"age":   42,
   279  		"city":  "London",
   280  	}
   281  
   282  	user2 := map[string]interface{}{
   283  		"name":  "Eden Zamir",
   284  		"email": "eden.zamir@example.com",
   285  		"age":   29,
   286  		"city":  "Tel Aviv",
   287  	}
   288  
   289  	user3 := map[string]interface{}{
   290  		"name":  "Paul Zamir",
   291  		"email": "paul.zamir@example.com",
   292  		"age":   35,
   293  		"city":  "Tel Aviv",
   294  	}
   295  
   296  	// STEP_START add_hash_data
   297  	_, err = rdb.HSet(ctx, "huser:1", user1).Result()
   298  
   299  	if err != nil {
   300  		panic(err)
   301  	}
   302  
   303  	_, err = rdb.HSet(ctx, "huser:2", user2).Result()
   304  
   305  	if err != nil {
   306  		panic(err)
   307  	}
   308  
   309  	_, err = rdb.HSet(ctx, "huser:3", user3).Result()
   310  
   311  	if err != nil {
   312  		panic(err)
   313  	}
   314  	// STEP_END
   315  
   316  	// STEP_START query1_hash
   317  	findPaulHashResult, err := rdb.FTSearch(
   318  		ctx,
   319  		"hash-idx:users",
   320  		"Paul @age:[30 40]",
   321  	).Result()
   322  
   323  	if err != nil {
   324  		panic(err)
   325  	}
   326  
   327  	fmt.Println(findPaulHashResult)
   328  	// >>> {1 [{huser:3 <nil> <nil> <nil> map[age:35 city:Tel Aviv...
   329  	// STEP_END
   330  
   331  	// Output:
   332  	// {1 [{huser:3 <nil> <nil> <nil> map[age:35 city:Tel Aviv email:paul.zamir@example.com name:Paul Zamir] <nil>}]}
   333  }
   334  

View as plain text