go-search/engine/redis.go

75 lines
1.6 KiB
Go
Raw Normal View History

2020-04-11 15:25:53 +00:00
package engine
import (
"strings"
2020-04-12 23:09:15 +00:00
redis "github.com/go-redis/redis/v7"
2020-04-11 15:25:53 +00:00
)
// RedisClient is an idiomatic interface for the Redis client,
// adding few methods to interact with the file system.
type RedisClient struct {
conn *redis.Client
}
// NewRedisClient returns a Redis client
func NewRedisClient(addr, port, password string, db int) (*RedisClient, error) {
2020-04-11 15:25:53 +00:00
client := redis.NewClient(&redis.Options{
Addr: addr + ":" + port,
Password: password, // no password set
DB: db, // use default DB
2020-04-11 15:25:53 +00:00
})
err := client.Ping().Err()
if err != nil {
return nil, err
}
return &RedisClient{conn: client}, nil
}
// AddFile index a file
func (c *RedisClient) AddFile(file, content string) error {
for w, s := range Scan(content) {
if err := c.conn.ZAdd(file, &redis.Z{
Score: float64(s),
Member: strings.ToLower(w),
2020-04-12 00:15:24 +00:00
}).Err(); err != nil {
return err
}
2020-04-11 15:25:53 +00:00
}
2020-04-12 00:15:24 +00:00
return nil
}
// Get search for a key
func (c *RedisClient) Get(key string) ([]string, error) {
2020-04-14 10:45:51 +00:00
return c.conn.ZRevRangeByScore(key, &redis.ZRangeBy{
Min: "-inf",
Max: "+inf",
Offset: 0,
Count: -1,
}).Result()
2020-04-11 15:25:53 +00:00
}
2020-04-14 10:45:51 +00:00
// GetWordScoreFromFile get score of element
func (c *RedisClient) GetWordScoreFromFile(key, member string) float64 {
return c.conn.ZScore(key, member).Val()
2020-04-11 15:25:53 +00:00
}
// GetFiles returns a key value
func (c *RedisClient) GetFiles() (keys []string, err error) {
2020-04-14 10:45:51 +00:00
keys, _, err = c.conn.Scan(0, "*", -1).Result()
2020-04-11 15:25:53 +00:00
return
}
2020-04-12 00:15:24 +00:00
// FlushAll drop the database
func (c *RedisClient) FlushAll() error {
return c.conn.FlushAll().Err()
}
2020-04-11 15:25:53 +00:00
// Close closes the Redis connection
func (c *RedisClient) Close() error {
return c.conn.Close()
}