go-search/engine/redis.go

75 lines
1.7 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 _, v := range GetWordsFromText(content) {
if err := c.conn.ZAdd(file, &redis.Z{
Score: float64(CountWord(content, v)),
Member: strings.ToLower(v),
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
}
2020-04-14 10:45:51 +00:00
// GetWordsFromFile search for a key
func (c *RedisClient) GetWordsFromFile(key string) ([]string, error) {
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
}
2020-04-14 10:45:51 +00:00
// GetAllFiles returns a key value
func (c *RedisClient) GetAllFiles() (keys []string, err error) {
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()
}