Redis的自动完成 [英] Redis autocomplete

查看:163
本文介绍了Redis的自动完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Redis的实现自动完成?

How can I implement an autocomplete using redis?

比方说我有一个数组 [阿尔弗雷德,乔尔,杰夫,addick] 。当我键入​​ A 我得到 [阿尔弗雷德,addick]

Say for example I have an array ["alfred","joel","jeff","addick"]. When I type a I get ["alfred", "addick"]

我希望你明白了吧。我怎么能实现这个使用Redis的命令有效(如果可能的话,但我认为这是)。这将是巨大的,如果我能得到一些简单的命令,我可以通过telnet尝试模仿这种行为。

I hope you get the point. How can I implement this using redis commands efficiently(if possible but I think it is). It would be great if I could get some simple commands I can try out via telnet to mimic this behaviour.

感谢

P.S:快乐耶诞给大家:)

P.S: Merry x-mas to all of you :)

推荐答案

如果你正在处理大型数据集,我会建议考虑实施这是一个线索。我已经一起引发一个小一点的Ruby的,将做到这一点:

If you're dealing with a large data set, I would suggest considering implementing this as a trie. I have thrown together a small bit of Ruby that would do this:

require 'rubygems'
require 'redis'

class RedisTrie
  TERMINAL = '+'

  def initialize(prefix)
    @prefix = prefix
    @r = Redis.new
  end

  def add_word(word)
    w = word.gsub(/[^a-zA-Z0-9_-]/, '')
    key = "#{@prefix}:"

    w.each_char do |c|
      @r.zset_add key, c.bytes.first, c
      key += c
    end

    @r.zset_add key, 0, TERMINAL
  end

  def add_words(*words)
    words.flatten.compact.each {|word| add_word word}
  end

  def suggest(text)
    @r.zset_range("#{@prefix}:#{text}", 0, -1).map do |c|
      (c == TERMINAL) ? text : suggest(text + c)
    end.flatten
  end
end

rt = RedisTrie.new('trie')

rt.add_words %w( apple automobile carwash oil-change cranky five ruthie axe auto )

p rt.suggest(ARGV.shift.to_s)

例如:

$ ruby RedisTrie.rb
["apple", "auto", "automobile", "axe", "carwash", "cranky", "five", "oil-change", "ruthie"]
$ ruby RedisTrie.rb a
["apple", "auto", "automobile", "axe"]
$ ruby RedisTrie.rb au
["auto", "automobile"]
$ ruby RedisTrie.rb aux
[]

了解更多关于在维基百科的词条试穿的尝试次数

您一定要优化你的建议的方法不会返回所有的价值观,而不是只返回第一x值找到。它会破坏目的来遍历整个数据结构。

You will definitely want to optimize your suggest method to not return ALL values, instead only returning the first X values it finds. It would defeat the purpose to iterate the entire data structure.

这篇关于Redis的自动完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆