Search code examples
goredisgo-redisft.search

go-redis FTSearch returns empty result


I'm able to create an index and load data using go-redis. Also, I'm able to search but only via CLI. That means the index is created properly and is searchable. It returns the correct results.

But when I try to search the data programmatically, it returns:

redis: 2024/07/26 19:27:10 pool.go:368: Conn has unread data
{Total:0 Docs:[]}

I'm using the following example: https://github.com/redis/go-redis/blob/master/search_test.go#L128-L138

Code used for reference:

// Create index
_, err := client.FTCreate(ctx, "txt", &redis.FTCreateOptions{}, &redis.FieldSchema{FieldName: "txt", FieldType: redis.SearchFieldTypeText}).Result()

// Add data
client.HSet(ctx, "doc1", "txt", "foo baz")
client.HSet(ctx, "doc2", "txt", "foo bar")

// Search
res, err := client.FTSearchWithArgs(ctx, "txt", "foo ~bar", &redis.FTSearchOptions{WithScores: true, Limit: 50}).Result()
if err != nil {
    fmt.Printf("\nerr: %v", err)
}

The same goes for client.JSONSet. Can anyone help me understand what's going wrong here?


Solution

  • Change the protocol to 2 when creating the client - the following code works:

    package main
    
    import (
        "context"
        "fmt"
        "github.com/redis/go-redis/v9"
    )
    
    var ctx = context.Background()
    
    func main() {
        var client *redis.Client
    
        client = redis.NewClient(&redis.Options{
            Addr:     "localhost:6379",
            Protocol: 2, // this right here
        })
    
        _, err := client.FTCreate(ctx, "txt", &redis.FTCreateOptions{}, &redis.FieldSchema{FieldName: "txt", FieldType: redis.SearchFieldTypeText}).Result()
        if err != nil {
            fmt.Printf("\nerr: %v", err)
        }
    
        // Add data
        client.HSet(ctx, "doc1", "txt", "foo baz")
        client.HSet(ctx, "doc2", "txt", "foo bar")
    
        // Search
        res, err := client.FTSearchWithArgs(ctx, "txt", "foo ~bar", &redis.FTSearchOptions{WithScores: true, Limit: 50}).Result()
        if err != nil {
            fmt.Printf("\nerr: %v", err)
        } else {
            fmt.Printf("\nRetrieved :%d documents", len(res.Docs))
        }
    }
    
    

    It looks like there's something wrong with how the go redis client is reading the results when it's interfacing with Redis over RESP3 which is the default for the redis go client.