我會考慮兩個有序集。
當搜索term
提交,獲得當前timestamp
和:
zadd timestamps timestamp term
zincrby counts 1 term
,上述兩個操作應該是原子的。
然後找到在給定的時間間隔timestamp_from
,timestamp_to
所有條款:
zrangebyscore timestamps timestamp_from timestamp_to
你得到這些後,環比他們從counts
得到計數。
或者,我很好奇你是否可以使用zunionstore
。下面是我在Ruby中的測試:
require 'redis'
KEYS = %w(counts timestamps results)
TERMS = %w(test0 keyword1 test0 test1 keyword1 test0 keyword0 keyword1 test0)
def redis
@redis ||= Redis.new
end
def timestamp
(Time.now.to_f * 1000).to_i
end
redis.del KEYS
TERMS.each {|term|
redis.multi {|r|
r.zadd 'timestamps', timestamp, term
r.zincrby 'counts', 1, term
}
sleep rand
}
redis.zunionstore 'results', ['timestamps', 'counts'], weights: [1, 1e15]
KEYS.each {|key|
p [key, redis.zrange(key, 0, -1, withscores: true)]
}
# top 2 terms
p redis.zrevrangebyscore 'results', '+inf', '-inf', limit: [0, 2]
編輯:在某些時候,你就需要清除counts
集。類似於@Eli提出的(https://stackoverflow.com/a/16618932/410102)。
你如何知道如何爲你所做的工作指定zunionstore的參數。我正在做以下工作,'redis.zunionstore('tmp',2,'some-zest','some-set','weights',0,1,'aggregate','max')'直到我找到你:)我在哪裏可以找到一些文件或相同的例子..或者我應該只是通過github上的代碼(例如在github上也沒有任何東西) – Akshay
@Akshay我想我從github存儲庫中學到了它:https ://github.com/redis/redis-rb/search?utf8 =%E2%9C%93&q = zunionstore – akonsu
明白了..謝謝:)當我查看redis.rb時,你的技術沒有響個不停:p – Akshay