Whoosh + jieba 中文检索

本文参考简书:Whoosh + jieba 中文检索
Whoosh官方文档入口

一. 核心对象

1.1 index对象和Schema对象

  • index对象是一个全局索引,在创建index对象前首先要声明index对象的一些属性,这些属性通过Schema对象进行包装。Schema对象有很多Fields,每个Field都是index对象的一个信息块,即需要被我们检索的内容。
  • 创建Schema对象时需要用关键字来映射Field nameField type,如title=TEXT
  • 创建好Schema对象后,接着就是使用creat_in方法来创建Schema的索引
  • 接着可以用以下两种方法打开一个已创建的索引
    # 方法一 使用FileStorage对象
    from whoosh.filedb.filestore import FileStorage
    storage = FileStorage(idx_path)  #idx_path 为索引路径
    idx = storage.open_index(indexname=indexname, schema=schema)
    
    # 方法二 使用open_dir函数
    from whoosh.index import open_dir
    idx = open_dir(indexname=indexname)  #indexname 为索引名
    

1.2 IndexWriter对象

  • 一旦有了index对象,我们就需要在index里写入需要被检索的信息
  • IndexWriter对象就是用来提供一个add_document(**args)方法来在之前声明的各种Fields里写入数据
  • 注:不是每个字段都要传值
  • 如果需要异步处理可以创建异步的IndexWriter对象
    from whoosh.writing import AsyncWriter
    writer = AsyncWriter(index=index)
    
  • 如果需要Buffer进行处理可以创建BufferWriter对象
    <
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用 Whoosh 实现信息检索系统,可以按照以下步骤进行: 1. 安装 Whoosh:可以使用 pip 命令安装 Whoosh,如下所示: ``` pip install whoosh ``` 2. 创建索引:使用 Whoosh 可以创建索引,将需要检索的数据存储到索引中。下面是一个简单的示例: ```python from whoosh.index import create_in from whoosh.fields import * import os # 创建索引目录 if not os.path.exists("indexdir"): os.mkdir("indexdir") # 定义索引的schema my_schema = Schema(title=TEXT(stored=True), content=TEXT) # 创建索引 my_index = create_in("indexdir", my_schema) # 获取索引的writer对象 writer = my_index.writer() # 添加文档索引 writer.add_document(title="Document 1", content="This is the content of document 1.") writer.add_document(title="Document 2", content="This is the content of document 2.") writer.add_document(title="Document 3", content="This is the content of document 3.") # 提交写入的文档 writer.commit() ``` 3. 查询匹配:使用 Whoosh 可以根据关键词进行查询匹配,下面是一个简单的示例: ```python from whoosh.qparser import QueryParser # 获取索引的searcher对象 searcher = my_index.searcher() # 定义查询解析器 query_parser = QueryParser("content", my_index.schema) # 解析查询语句 query = query_parser.parse("content:document") # 根据查询语句进行查询 results = searcher.search(query) # 输出匹配结果 for result in results: print(result["title"]) ``` 通过以上步骤,我们就可以使用 Whoosh 实现一个简单的信息检索系统。当然,在实际的应用中,还需要进行更多的优化和扩展,例如:分词、去重、排序等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值