@@ -0,0 +1,1443 @@
+#-*- coding:utf-8 -*-%0A%0Aimport redis%0Aimport simplejson%0Aimport mmseg%0A%0Ar = redis.Redis (%22localhost%22)%0Ammseg.Dictionary.load_dictionaries()%0A%0Adatabase='database:book'%0Aindexbase='index:book'%0A%0Adef rebuild_index (items):%0A  del_index ()%0A  build_index (items)%0A%0Adef del_index ():%0A  prefixs = r.smembers (indexbase)%0A  for prefix in prefixs:%0A    r.delete('%25s:%25s'%25(indexbase,prefix))%0A  r.delete(indexbase)%0A  r.delete(database)%0A%0Adef build_index (items):%0A  %22%22%22%0A  Build index for items.%0A  %22%22%22%0A  for item in items:%0A    add_item (item)%0A%0Adef add_item (item):%0A  %22%22%22%0A  Create index for ITEM.%0A  %22%22%22%0A  r.hset (database, item%5B'id'%5D, simplejson.dumps(item))%0A  for prefix in prefixs_for_term (item%5B'term'%5D):%0A    r.sadd (indexbase, prefix)%0A    r.zadd ('%25s:%25s'%25(indexbase,prefix),item%5B'id'%5D, item%5B'score'%5D)%0A%0Adef del_item (item):%0A  %22%22%22%0A  Delete ITEM from the index%0A  %22%22%22%0A  pass%0A%0Adef prefixs_for_term (term):%0A  %22%22%22%0A  Get prefixs for TERM.%0A  %22%22%22%0A  prefixs=%5B%5D%0A  tokens=mmseg.Algorithm(term)%0A  for token in tokens:%0A    word = token.text%0A    for i in xrange (1,len(word)+1):%0A      prefixs.append(word%5B:i%5D)%0A%0A  return prefixs%0A%0Adef search_query (prefix):%0A  ids=r.zrange ('%25s:%25s'%25(indexbase,prefix), 0, 5)%0A  if not ids: return ids%0A  return r.hmget(database, *ids)%0A%0Adef load_items ():%0A  items= (%0A    %7B'id':'1', 'term': u'%E8%BD%BB%E8%BD%BB%E5%9C%B0%E4%BD%A0%E8%B5%B0%E4%BA%86', 'score': '9'%7D,%0A    %7B'id':'2', 'term': u'%E6%AD%A3%E5%A6%82%E4%BD%A0%E8%BD%BB%E8%BD%BB%E5%9C%B0%E6%9D%A5', 'score': '8'%7D,%0A    %7B'id':'3', 'term': u'%E4%BD%A0%E6%8C%A5%E4%B8%80%E6%8C%A5%E8%A1%A3%E8%A2%96%EF%BC%8C%E4%B8%8D%E5%B8%A6%E8%B5%B0%E4%B8%80%E7%89%87%E4%BA%91%E5%BD%A9', 'score': '8.5'%7D,%0A    )%0A  rebuild_index (items)%0A

Build index ready for autocomplete.