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
|
2020-04-14 09:52:52 +00:00
|
|
|
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,
|
2020-04-14 09:52:52 +00:00
|
|
|
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
|
2020-04-12 21:59:20 +00:00
|
|
|
func (c *RedisClient) AddFile(file, content string) error {
|
2020-04-17 17:41:33 +00:00
|
|
|
for w, s := range Scan(content) {
|
2020-04-12 21:59:20 +00:00
|
|
|
if err := c.conn.ZAdd(file, &redis.Z{
|
2020-04-17 17:41:33 +00:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2020-04-17 17:41:33 +00:00
|
|
|
// 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 {
|
2020-04-12 21:59:20 +00:00
|
|
|
return c.conn.ZScore(key, member).Val()
|
2020-04-11 15:25:53 +00:00
|
|
|
}
|
|
|
|
|
2020-04-17 17:41:33 +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()
|
|
|
|
}
|