在wagtail

时间:2017-10-21 00:41:40

标签: django elasticsearch wagtail elasticsearch-py

我们正在使用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方法扩展字段属性(即替换MarkupField的django-markupfield get_searchable_content(value)类)来解决这个问题,但序列化错误仍然存​​在。

有没有人有任何关于在Wagtail + elasticsearch索引自定义Django字段的技巧?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我将get_searchable_content置于错误的位置,我认为Markup类需要它,但需要将它放在Django模型Field类本身上。然后Wagtail将拉出适当的值以在elasticsearch(或任何其他搜索后端)中编入索引。

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