【发布时间】:2020-07-31 14:01:17
【问题描述】:
我正在构建一个 Django Web 应用程序来存储文档及其相关元数据。
大部分元数据将存储在底层 MySQL 数据库中,在 Elasticsearch 中索引 OCR 的文档文本以启用全文搜索。我已经合并了django-elasticsearch-dsl 来连接和同步我的数据模型,因为我还在索引(因此,双重存储)我模型中的其他一些字段。我曾考虑使用Haystack,但它缺乏对最新 Elasticsearch 版本的支持。
当通过应用程序的管理界面上传文档时,post_save 信号会自动触发 Celery 异步后台任务以执行 OCR,并最终将提取的文本索引到 Elasticsearch 中。
看到我的模型中没有定义全文字段(并希望避免这样做,因为我不想在数据库中存储或搜索 CLOB),我正在寻找最好的从我的 tasks.py 文件中更新我的 Elasticsearch 文档的练习。似乎没有办法使用 django-elasticseach-dsl 做到这一点(但也许我错了?)所以我想知道我是否应该这样做:
尝试使用姐妹django-elasticsearch-dsl-drf 包通过REST 与Elasticsearch 交互。
通过使用更普通的 elasticsearch-dsl-py 包(基于 elasticsearch-py)更松散地将我的应用程序与 Elasticsearch 集成。使用这种方法我会失去一些“奢侈”,因为我必须编写更多的集成代码,至少如果我想用信号连接我的模型。
有最佳实践吗?还是我没有考虑过的其他方法?
更新 1: 在尝试实现@Nielk 的答案时,我能够将 OCR 文本(下面的 tasks.py 中的结果 =“test”)持久化到 ElasticSearch 中,但它也保留在 MySQL 数据库中。我仍然对如何将 Submission.rawtext 配置为 ElasticSearch 的通路感到困惑。
models.py:
class Submission(models.Model):
rawtext = models.TextField(null=True, blank=True)
...
def type_to_string(self):
return ""
documents.py:
@registry.register_document
class SubmissionDocument(Document)
rawtext = fields.TextField(attr="type_to_string")
def prepare_rawtext(self, instance):
# self.rawtext = None
# instance.rawtext = "test"
return instance.rawtext
...
tasks.py(在提交模型 post_save 信号上调用):
@shared_task
def process_ocr(my_uuid)
result = "test" # will ultimately be OCR'd text
instance = Submission.objects.get(my_uuid=my_uuid)
instance.rawtext = result
instance.save()
更新 2(工作解决方案):
models.py 类提交(models.Model):
@property
def rawtext(self):
if getattr(self, '_rawtext_local_change', False):
return self._rawtext
if not self.pk:
return None
from .documents import SubmissionDocument
try:
return SubmissionDocument.get(id=self.pk)._rawtext
except:
return None
@rawtext.setter
def rawtext(self, value):
self._rawtext_local_change = True
self._rawtext = value
documents.py
@registry.register_document
class SubmissionDocument(Document):
rawtext = fields.TextField()
def prepare_rawtext(self, instance):
return instance.rawtext
tasks.py
@shared_task
def process_ocr(my_uuid)
result = "test" # will ultimately be OCR'd text
# note that you must do a save on property fields, can't do an update
instance = Submission.objects.get(my_uuid=my_uuid)
instance.rawtext = result
instance.save()
【问题讨论】:
标签: django elasticsearch celery django-celery elasticsearch-dsl-py