You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

bayes_cache_learn.lua 1.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. -- Lua script to perform cache checking for bayes classification
  2. -- This script accepts the following parameters:
  3. -- key1 - cache id
  4. -- key3 - is spam (1 or 0)
  5. -- key3 - configuration table in message pack
  6. local cache_id = KEYS[1]
  7. local is_spam = KEYS[2]
  8. local conf = cmsgpack.unpack(KEYS[3])
  9. cache_id = string.sub(cache_id, 1, conf.cache_elt_len)
  10. -- Try each prefix that is in Redis (as some other instance might have set it)
  11. for i = 0, conf.cache_max_keys do
  12. local prefix = conf.cache_prefix .. string.rep("X", i)
  13. local have = redis.call('HGET', prefix, cache_id)
  14. if have then
  15. -- Already in cache, but is_spam changes when relearning
  16. redis.call('HSET', prefix, cache_id, is_spam)
  17. return false
  18. end
  19. end
  20. local added = false
  21. local lim = conf.cache_max_elt
  22. for i = 0, conf.cache_max_keys do
  23. if not added then
  24. local prefix = conf.cache_prefix .. string.rep("X", i)
  25. local count = redis.call('HLEN', prefix)
  26. if count < lim then
  27. -- We can add it to this prefix
  28. redis.call('HSET', prefix, cache_id, is_spam)
  29. added = true
  30. end
  31. end
  32. end
  33. if not added then
  34. -- Need to expire some keys
  35. local expired = false
  36. for i = 0, conf.cache_max_keys do
  37. local prefix = conf.cache_prefix .. string.rep("X", i)
  38. local exists = redis.call('EXISTS', prefix)
  39. if exists then
  40. if not expired then
  41. redis.call('DEL', prefix)
  42. redis.call('HSET', prefix, cache_id, is_spam)
  43. -- Do not expire anything else
  44. expired = true
  45. elseif i > 0 then
  46. -- Move key to a shorter prefix, so we will rotate them eventually from lower to upper
  47. local new_prefix = conf.cache_prefix .. string.rep("X", i - 1)
  48. redis.call('RENAME', prefix, new_prefix)
  49. end
  50. end
  51. end
  52. end
  53. return true