1

我们使用Django MarkupField来存储 Markdown 文本,它工作得很好。

然而,当我们尝试在 Wagtail 中索引这些字段时,我们会从 Elasticsearch 中得到序列化错误,如下所示:

File "/usr/local/lib/python3.5/dist-packages/wagtail/wagtailsearch/management/commands/update_index.py", line 120, in handle
  self.update_backend(backend_name, schema_only=options.get('schema_only', False))
File "/usr/local/lib/python3.5/dist-packages/wagtail/wagtailsearch/management/commands/update_index.py", line 87, in update_backend
  index.add_items(model, chunk)
File "/usr/local/lib/python3.5/dist-packages/wagtail/wagtailsearch/backends/elasticsearch.py", line 579, in add_items
  bulk(self.es, actions)
File "/usr/local/lib/python3.5/dist-packages/elasticsearch/helpers/__init__.py", line 195, in bulk
  for ok, item in streaming_bulk(client, actions, **kwargs):
File "/usr/local/lib/python3.5/dist-packages/elasticsearch/helpers/__init__.py", line 162, in streaming_bulk
  for bulk_actions in _chunk_actions(actions, chunk_size, max_chunk_bytes, client.transport.serializer):
File "/usr/local/lib/python3.5/dist-packages/elasticsearch/helpers/__init__.py", line 61, in _chunk_actions
  data = serializer.dumps(data)
File "/usr/local/lib/python3.5/dist-packages/elasticsearch/serializer.py", line 50, in dumps
  raise SerializationError(data, e)
elasticsearch.exceptions.SerializationError: ({'_partials': [<markupfield.fields.Markup object at 0x7faa6e238e80>, <markupfield.fields.Markup object at 0x7faa6dbc4da0>], 'pk': '1', 'research_interests': <markupfield.fields.Markup object at 0x7faa6e238e80>, 'bio': <markupfield.fields.Markup object at 0x7faa6dbc4da0>}, TypeError("Unable to serialize <markupfield.fields.Markup object at 0x7faa6e238e80> (type: <class 'markupfield.fields.Markup'>)",))

一种解决方法是索引返回的可调用对象,field.raw但我们必须为模型中的每个 Markdown 字段属性编写一个这样的可调用对象。我认为我们可以通过使用方法扩展字段属性(即Markup替换 的 django-markupfield 类MarkupField)来解决此问题,get_searchable_content(value)但序列化错误仍然存​​在。

有人对在 Wagtail + elasticsearch 中索引自定义 Django 字段有任何提示吗?

4

2 回答 2

2

有几种方法可以做到这一点。最好的办法是在 中创建您自己的字段elasticsearch-dsl,例如参见 (0),并将其用于(反)序列化。其他选项是创建您自己的JSONSerializer(1) 子类,并将其作为serializer=MyJSONSerializer()构造函数传入Elasticsearch,它可以处理markupfield.fields.Markup对象。

0 - https://github.com/elastic/elasticsearch-dsl-py/blob/master/test_elasticsearch_dsl/test_document.py#L49-L58 1 - https://github.com/elastic/elasticsearch-py/blob/master /elasticsearch/serializer.py#L24

于 2017-10-21T11:41:25.043 回答
1

我把它get_searchable_content放在了错误的地方,我认为它在Markup课堂上是需要的,但它需要放在 Django 模型Field类本身上。Wagtail 然后将提取适当的值以在 elasticsearch(或任何其他搜索后端)中进行索引。

最直接的解决方案是MarkupField使用自定义 Field 类进行扩展,并添加一个get_searchable_content(self, value),将其实现委托给MarkupField.get_prep_value

于 2017-10-31T00:12:12.543 回答