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
|
|
|
)
|
|
|
|
|
|
|
|
// NewRedisClient returns a Redis client
|
2020-04-17 18:19:15 +00:00
|
|
|
func NewRedisClient(addr, port, password string, db int) (*redis.Client, 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
|
|
|
|
}
|
|
|
|
|
2020-04-17 18:19:15 +00:00
|
|
|
return client, nil
|
2020-04-11 15:25:53 +00:00
|
|
|
}
|
|
|
|
|
2020-04-17 18:19:15 +00:00
|
|
|
// AddFile indexes a file and its words in the database
|
|
|
|
func AddFile(c *redis.Client, file, content string) error {
|
2020-04-17 17:41:33 +00:00
|
|
|
for w, s := range Scan(content) {
|
2020-04-17 18:19:15 +00:00
|
|
|
if err := c.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
|
2020-04-17 18:19:15 +00:00
|
|
|
func Get(c *redis.Client, key string) ([]string, error) {
|
|
|
|
return c.ZRevRangeByScore(key, &redis.ZRangeBy{
|
2020-04-14 10:45:51 +00:00
|
|
|
Min: "-inf",
|
|
|
|
Max: "+inf",
|
|
|
|
Offset: 0,
|
|
|
|
Count: -1,
|
|
|
|
}).Result()
|
2020-04-11 15:25:53 +00:00
|
|
|
}
|
|
|
|
|
2020-04-17 18:19:15 +00:00
|
|
|
// GetWordScoreFromFile retreive the score of a file's word
|
|
|
|
func GetWordScoreFromFile(c *redis.Client, key, member string) float64 {
|
|
|
|
return c.ZScore(key, member).Val()
|
2020-04-11 15:25:53 +00:00
|
|
|
}
|
|
|
|
|
2020-04-17 18:19:15 +00:00
|
|
|
// GetFiles returns all registered files
|
|
|
|
func GetFiles(c *redis.Client) (keys []string, err error) {
|
|
|
|
keys, _, err = c.Scan(0, "*", -1).Result()
|
2020-04-11 15:25:53 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-04-17 18:19:15 +00:00
|
|
|
// FlushAll drops the database
|
|
|
|
func FlushAll(c *redis.Client) error {
|
|
|
|
return c.FlushAll().Err()
|
2020-04-12 00:15:24 +00:00
|
|
|
}
|
|
|
|
|
2020-04-11 15:25:53 +00:00
|
|
|
// Close closes the Redis connection
|
2020-04-17 18:19:15 +00:00
|
|
|
func Close(c *redis.Client) error {
|
|
|
|
return c.Close()
|
2020-04-11 15:25:53 +00:00
|
|
|
}
|