全文索引搜索whoosh(2)

41 篇文章 4 订阅
36 篇文章 1 订阅

承接前面对whoosh的文章,继续:


写索引文件


下面开始写入索引内容,过程如下:

writer = ix.writer()
writer.add_document(title=u"my document", content=u"this is my document", path=u"/a", tags=u"firlst short", icon=u"/icons/star.png")
writer.add_document(title=u"my second document", content=u"this is my second document", path=u"/b", tags=u"second short", icon=u"/icons/sheep.png")
writer.commit()

特别注意:

  • 字段的值必须是unicode类型
  • 不是每个字段都必须赋值

更多的内容,请参考:如何索引文件官方文档


搜索


开始搜索,需要新建立一个对象,如:

searcher = ix.searcher()

一般来讲,不是这么简单地,建立对象相当于开始搜索,完事之后要关闭,所以在实战中,常常写成:

withe ix.searcher() as searcher:
(do somthing)

或者写成(与上面的等效):

try:
    searcher = ix.searcher()
    (do somthing)
finally:
    searcher.close()

接下来就开始搜索了,以搜索content为例:

from whoosh.qparser import QueryParser
with ix.searcher() as searcher:
    query = QueryParser("content",ix.schema).parse("second")
    result = searcher.search(query)
    results[0]

返回显示:

{"title":u"my second document","path":u"/a"}

前面已经将上述两个字段设置为stored=True.


whoosh与结巴分词

原计划写这个相关代码,但是google之后,发现阿小信的博客(恕我不能给出链接,因为只要有链接,本文就不能发布,在我的github中是完整的,这里是阉割版)中有非常完美的解决,我特地将那段代码抄下来,供需要者参考:

#-*- coding:utf-8 -*-
import jieba
from whoosh.analysis import Tokenizer,Token 
from whoosh.compat import text_type

class ChineseTokenizer(Tokenizer):  
    def __call__(self, value, positions=False, chars=False,  
                 keeporiginal=False, removestops=True,  
                 start_pos=0, start_char=0, mode='', **kwargs):  
        assert isinstance(value, text_type), "%r is not unicode" % value  
        t = Token(positions, chars, removestops=removestops, mode=mode,  
            **kwargs)  
        seglist=jieba.cut_for_search(value)                       #使用结巴分词库进行分词  
        for w in seglist:  
            t.original = t.text = w  
            t.boost = 1.0  
            if positions:  
                t.pos=start_pos+value.find(w)  
            if chars:  
                t.startchar=start_char+value.find(w)  
                t.endchar=start_char+value.find(w)+len(w)  
            yield t                                               #通过生成器返回每个分词的结果token

def ChineseAnalyzer():  
    return ChineseTokenizer()

声明


本文属于阉割之后的版本。要看完整版,请到我的github:qiwsir的algorithm。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qiwsir

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值