公司新闻
Company news
搜索功能需要使用反向索引(reversed indexes),反向索引是互联网绝大多数搜索引擎使用的底层结构,与之对应的是正向索引。从逻辑上来说,反向索引就是一个字典,key是关键字,value就是一个文档集。
下面简单介绍一下redis创建反向索引及简单关键字查询的过程(只包含关键代码)。
pool=redis.ConnectionPool(host='127.0.0.1',port=6379,db=0)
conn = redis.StrictRedis(connection_pool=pool)
patern = re.compile("[a-z']{2,}")
def tokenize(content):
words = set()
for match in patern.finditer(content.lower()):
word = match.group().strip("'")
if len(word) >= 2 :
words.add(word)
return words
def index_document(conn,docid,content):
words = tokenize(content)
pipeline = conn.pipeline(True)
for word in words:
pipeline.sadd('idx:'+word, docid)
return (pipeline.execute())
其中keywords是解析输入得到的列表,遍历反向索引,得到文档id,然后再获取文档的详细信息
#search the input
def search(conn, keywords):
data = set()
for item in keywords:
pipeline = conn.pipeline(True)
index = 'idx:'+item
pipeline.smembers(index)
temp = pipeline.execute()
if data:
data.intersection(temp)
elif len(temp) > 0:
data = temp
return data