Django中使用Whoosh进行全文检索的方法

作者:周继元的博客 时间:2023-03-20 05:35:43 

Whoosh 是纯Python实现的全文搜索引擎,通过Whoosh可以很方便的给文档加上全文索引功能。

什么是全文检索

简单讲分为两块,一块是分词,一块是搜索。比如下面一段话:

上次舞蹈演出直接在上海路的弄堂里

比如我们现在想检索上次的演出,通常我们会直接搜索关键词: 上次演出 ,但是使用传统的SQL like 查询并不能命中上面的这段话,因为在 上次 和 演出 中间还有 舞蹈 。然而全文搜索却将上文切成一个个Token,类似:

上次/舞蹈/演出/直接/在/上海路/的/弄堂/里

切分成Token后做反向索引(inverted indexing),这样我们就可以通过关键字很快查询到了结果了。

解决分词问题

分词是个很有技术难度的活,比如上面的语句中一个难点就是到底是 上海路 还是 上海 呢?Python有个中文分词库: 结巴分词 ,我们可以通过结巴分词来完成索引中分词工作,结巴分词提供了Whoosh的组件可以直接集成,代码示例

遇到的问题

如果是在一些VPS上测试的时候非常慢的话可能是内存不足,比如512MB做一个博客索引非常慢,尝试升级到1GB后可以正常使用了。

代码


import logging
import os
import shutil
from django.conf import settings

from whoosh.fields import Schema, ID, TEXT, NUMERIC
from whoosh.index import create_in, open_dir
from whoosh.qparser import MultifieldParser
from jieba.analyse import ChineseAnalyzer

from .models import Article

log = logging.getLogger(__name__)

index_dir = os.path.join(settings.BASE_DIR, "whoosh_index")

indexer = open_dir(index_dir)

def articles_search(keyword):

mp = MultifieldParser(
   ['content', 'title'], schema=indexer.schema, fieldboosts={'title': 5.0})
 query = mp.parse(keyword)

with indexer.searcher() as searcher:
   results = searcher.search(query, limit=15)

articles = []
   for hit in results:
     log.debug(hit)
     articles.append({
       'id': hit['id'],
       'slug': hit['slug'],
     })

return articles

def rebuild():
 if os.path.exists(index_dir):
   shutil.rmtree(index_dir)
 os.makedirs(index_dir)

analyzer = ChineseAnalyzer()
 schema = Schema(
   id=ID(stored=True, unique=True),
   slug=TEXT(stored=True),
   title=TEXT(),
   content=TEXT(analyzer=analyzer))
 indexer = create_in(index_dir, schema)

__index_all_articles()

def __index_all_articles():
 writer = indexer.writer()
 published_articles = Article.objects.exclude(is_draft=True)
 for article in published_articles:
   writer.add_document(
     id=str(article.id),
     slug=article.slug,
     title=article.title,
     content=article.content,
   )
 writer.commit()

def article_update_index(article):
 '''
 updating an article to indexer, adding if not.
 '''
 writer = indexer.writer()
 writer.update_document(
   id=str(article.id),
   slug=article.slug,
   title=article.title,
   content=article.content,
 )

writer.commit()

def article_delete_index(article):
 writer = indexer.writer()
 writer.delete_by_term('id', str(article.id))

writer.commit()

来源:https://www.imzjy.com/blog/2018-10-06-full-text-search-with-whoosh

标签:Django,Whoosh,全文检索
0
投稿

猜你喜欢

  • 解决python3 整数数组转bytes的效率问题

    2023-08-09 19:39:41
  • Vue实现父子组件页面刷新的几种常用方法

    2024-06-07 16:05:52
  • PDO::lastInsertId讲解

    2023-06-11 14:31:37
  • MySQL Order By索引优化方法

    2024-01-18 10:34:38
  • Python数据结构之图的存储结构详解

    2021-03-28 10:42:48
  • Python语言中的数据类型-序列

    2023-08-31 14:36:24
  • python爬虫自动创建文件夹的功能

    2023-11-05 08:22:40
  • 表格可读性提升分析

    2010-05-19 13:03:00
  • python使用plot绘制未来15天气温折线图

    2022-11-06 02:09:41
  • python使用imap-tools模块下载邮件附件的示例

    2023-09-16 08:39:38
  • SQLSERVER 时间格式大全

    2024-01-28 12:13:33
  • Python提取特定时间段内数据的方法实例

    2023-09-12 05:21:49
  • Python方法的延迟加载的示例代码

    2022-09-05 03:25:00
  • pyinstaller打包django项目的实现步骤

    2022-08-17 14:28:15
  • 使用python脚本实现查询火车票工具

    2021-03-10 05:48:54
  • Python3基础之基本运算符概述

    2021-04-16 03:15:02
  • 说说掌握JavaScript语言的思想前提

    2008-12-26 17:59:00
  • Python练习之操作MySQL数据库

    2024-01-20 12:29:22
  • Cpython解释器中的GIL全局解释器锁

    2021-08-29 22:06:43
  • javascript中利用柯里化函数实现bind方法【推荐】

    2024-05-02 17:29:26
  • asp之家 网络编程 m.aspxhome.com