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 {
|
|
|
|
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 {
|
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-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()
|
|
|
|
}
|