使用Redis进行搜索

搜索引擎以及各种网站中的搜索功能已经是人们从海量信息中快速获取特定信息的常用方式。使用 Redis 可以搭建高性能、多特性的搜索引擎,也特别适合解决基于搜索的问题。

本实训项目从构建反向索引,基本搜索操作,实现搜索三个方面介绍如何使用 Redis 解决基于搜索的问题。

第1关:构建反向索引

#!/usr/bin/env python
#-*- coding:utf-8 -*-

import re
import redis

conn = redis.Redis()

# 文本序列化
def tokenize(content):
    # 请在下面完成要求的功能
    #********* Begin *********#
    words = set()
    for word in re.findall("[a-z]{2,}", content.lower()):
        if len(word) >= 2:
            words.add(word)
    return words
    #********* End *********#

# 创建文本的反向索引
def index_document(content):
    # 请在下面完成要求的功能
    #********* Begin *********#
    content_id = conn.incr("content:id")
    conn.hset("contents", content_id, content)
    words = tokenize(content)

    pipeline = conn.pipeline(True)
    for word in words:
        pipeline.sadd('keyword:' + word, content_id)
    pipeline.execute()
    
  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值