복붙노트

[REDIS] 레디 스 자동 완성

REDIS

레디 스 자동 완성

어떻게 레디 스를 사용하여 자동 완성을 구현할 수있다?

말은 예를 들어 I 배열이 [ "알프레드", "조엘", "제프", "addick"]. 나는를 입력 할 때 나는 [ "알프레드을", "addick"] 수

난 당신이 포인트를 얻을 수 있기를 바랍니다. 어떻게이 사용 레디 스를 구현할 수 있습니다 효율적 명령 (가능하다면하지만 난 그게 생각). 내가 모방이 동작 텔넷을 통해 시도 할 수있는 몇 가지 간단한 명령을 얻을 수 있다면 그것은 좋은 것입니다.

감사

P.S : 메리는 당신의 모든 마스를 X :)

해결법

  1. ==============================

    1.당신은 큰 데이터 세트를 처리하는 경우, 내가 트라이으로 이것을 구현을 고려 건의 할 것입니다. 나는이 작업을 수행 할 것 루비의 작은 비트를 함께 던져 :

    당신은 큰 데이터 세트를 처리하는 경우, 내가 트라이으로 이것을 구현을 고려 건의 할 것입니다. 나는이 작업을 수행 할 것 루비의 작은 비트를 함께 던져 :

    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 값을 반환하는 모든 값을 반환하지에 당신의 제안 방법을 최적화 할 것입니다. 그것은 전체 데이터 구조를 반복하는 목적을 물리 칠 것이다.

  2. ==============================

    2.[예, 질문 후 2 년 게시, 그럼에도 불구하고 관련되었다]

    [예, 질문 후 2 년 게시, 그럼에도 불구하고 관련되었다]

    하여 레디 스 웹 사이트에서 (루비) 전체 튜토리얼이있다 :

  3. ==============================

    3.사이먼 윌리 슨의 인상적인 레디 스 자습서를 읽을 때 나는이 조각을 발견했다.

    사이먼 윌리 슨의 인상적인 레디 스 자습서를 읽을 때 나는이 조각을 발견했다.

  4. ==============================

    4.여기 레디 스와 알파벳 자동 완성에 대한 PHP에서 죽은 간단한 알고리즘이다 :

    여기 레디 스와 알파벳 자동 완성에 대한 PHP에서 죽은 간단한 알고리즘이다 :

    function getNextChar($char) {
        $char++;
        if(strlen($char) > 1) { $char--; }
        return $char;
    }
    
    function createDictionary($redis, $key, $wordList) {
        if(!$redis->exists($key)) {
            foreach($wordList as $word) {
                $redis->zadd($key, 0, $word);
            }
        }
    }
    
    function getLexicalAutocomplete($redis, $dictionaryKey, $input) {
        $inputNext = substr($input, 0, -1) . getNextChar(substr($input, -1)); //ab -> ac
    
        $redis->zadd($dictionaryKey, 0, $input);
        $redis->zadd($dictionaryKey, 0, $inputNext);
    
        $rangeStart = $redis->zrank($dictionaryKey, $input)+1;
        $rangeEnd = $redis->zrank($dictionaryKey, $inputNext)-1;
    
        $autocompleteResults = $redis->zrange($dictionaryKey, $rangeStart, $rangeEnd);
    
        $redis->zrem($dictionaryKey, $input);
        $redis->zrem($dictionaryKey, $inputNext);
    
        return $autocompleteResults;
    }
    
    $redis = new Redis();
    $redis->connect('', 0); //Your redis server ip/port goes here
    
    createDictionary($redis, "dict", array("alfred", "joel", "jeff", "addick"));
    $result = getLexicalAutocomplete($redis, "dict", $argv[1]);
    
    echo json_encode($result);
    

    I를 제외하고 살바토레에 의해 레디 스에 전체 기사 자동, 바탕으로 성능 저하 (추가 zadds 및 zrems의 커플)의 작은 약간의 비용 추가 자동 완성 사전을 생성 할 필요가, hax하지만, 대부분의 경우는 수행해야 잘. 이 스크립트는 phpredis을 가정하지만, 실질적으로 predis과 동일해야합니다.

    출력 예 :

    > php redisauto.php a
    ["addick","alfred"]
    
    > php redisauto.php ad
    ["addick"]
    
    > php redisauto.php al
    ["alfred"]
    
    > php redisauto.php j
    ["jeff","joel"]
    
    > php redisauto.php je
    ["jeff"]
    
  5. ==============================

    5.다음은 파이썬에서 원래 antirez의 루비 구현의 포트입니다 :

    다음은 파이썬에서 원래 antirez의 루비 구현의 포트입니다 :

    http://www.varunpant.com/posts/auto-complete-with-redis-python
    
  6. ==============================

    6.난 그냥 정확한 문제를 얘기하고 더되는 서비스를 제공 멋진 게시물을 통해 갔다. 확인 해봐

    난 그냥 정확한 문제를 얘기하고 더되는 서비스를 제공 멋진 게시물을 통해 갔다. 확인 해봐

  7. ==============================

    7.당신이 여기 도착하면 아마 관련이없는이 있지만, 당신은 또한 제안 자동 완성 UI 필드에 쉽게 적절한 빠르고 확장 성있는 방법에 관심이있을 수 있습니다

    당신이 여기 도착하면 아마 관련이없는이 있지만, 당신은 또한 제안 자동 완성 UI 필드에 쉽게 적절한 빠르고 확장 성있는 방법에 관심이있을 수 있습니다

    http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/search-suggesters-completion.html

  8. from https://stackoverflow.com/questions/1958005/redis-autocomplete by cc-by-sa and MIT license