如何通过Haystack建立pdf文档的全文索引

通过Haystack可以快速建立Django的全文检索。如果我们的模型里面models.py使用了文件上传(假设这里你上传的pdf),并且你希望能够同时对这个pdf文件内容建立全文索引。那么应该怎么办?

如果你还不了解Haystack,或者不知道怎么快速建立基于Django 的全文检索下面的内容会很有帮助:

下面的内容建立在能快速建立基于Haystack全文索引的基础上

那么具体怎么做?

查阅官方文档看到有这么一个页面RichContentExtraction其中有这么一段话

For some projects it is desirable to index text content which is stored in structured files such as PDFs, Microsoft Office documents, images, etc. Currently only Solr’s ExtractingRequestHandler is directly supported by Haystack but the approach below could be used with any backend which supports this feature.

大概意思就是目前只有Solr的后端能直接处理pdf索引,但是其它后台只要实现相同的方法也可以支持这个功能。

Haystackwhoosh后端为例

思路: 如果我们能够读取出pdf内容,那么pdf就和其他的字段没有什么太大区别,也就可以建立全文索引。

python中读取pdf的包这里使用的是 textract

前面我们建立索引建立了一个search_indexes.py文件,内容大概应该是这样的

class BaseFileIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    title = indexes.CharField(model_attr='title')

    def get_model(self):
        return BaseFile

    def index_queryset(self, using=None):
        return self.get_model().objects.all()

步骤很简单只需要添加一个def prepars(self, obj)方法在这里处理pdf文件读取既可。

# <your_app>/search_indexes.py
class BaseFileIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    title = indexes.CharField(model_attr='title')

    def get_model(self):
        return BaseFile

    def index_queryset(self, using=None):
        return self.get_model().objects.all()

    def prepare(self, obj):
        data = super(BaseFileIndex, self).prepare(obj)
        extracted_data = search_utils.parse_to_string(obj.content.path)  # 解析pdf内容
        t = loader.select_template(('search/indexes/himadatabase/basefile_text.txt', ))  
        data['text'] = t.render({'object': obj, 'extracted': extracted_data})
        return data

# search_utils.py

# coding=utf-8
import textract


# 读取pdf到string
def parse_to_string(filename):
    return textract.process(filename)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值