公司新闻

Company news

增值业务经营许可证编号:B2-20193929

公司新闻

利用redis实现简单搜索功能——重庆网站优化

来源:追天科技|时间:0000-00-00 00:00:00|浏览:

搜索功能需要使用反向索引(reversed indexes),反向索引是互联网绝大多数搜索引擎使用的底层结构,与之对应的是正向索引。从逻辑上来说,反向索引就是一个字典,key是关键字,value就是一个文档集。

下面简单介绍一下redis创建反向索引及简单关键字查询的过程(只包含关键代码)。

1. redis连接

pool=redis.ConnectionPool(host='127.0.0.1',port=6379,db=0)

conn = redis.StrictRedis(connection_pool=pool)

2. 针对每个文档进行语法解析

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

3. 针对每个文档进行语法解析,并建立反向索引

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())

4. 搜索

其中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

侍
重庆短信群发