我们正在使用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字段的技巧?
答案 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。