Redis 自动完成 [英] Redis autocomplete

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

问题描述

如何使用 redis 实现自动完成?

How can I implement an autocomplete using redis?

例如我有一个数组 ["alfred","joel","jeff","addick"].当我输入 a 我得到 ["alfred", "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
    []

维基百科关于 Tries 的条目上阅读更多关于 Tries 的信息.

Read more on Tries at Wikipedia's entry on Tries.

您肯定希望优化您的建议方法,使其不返回所有值,而是仅返回它找到的前 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天全站免登陆