首页 > 解决方案 > 如何使用 django_elasticsearch_dsl 在 Django 中的 NestedField 内索引 JSONField?

问题描述

我有用户模型和评论,我正在使用 django_elasticsearch_dsl 在 ElasticSearch 中建立索引

# models.py

class Comment(models.Model):
  user = models.OneToOneField(User, on_delete=models.CASCADE)
  reply_type =  models.JSONField(default=dict)

reply_type内容

reply_type: {
  "one": "on... ...",
  "two": "tw... ..."
}

索引弹性我正在这样做

# documents.py

@registry.register_document
class UserDocument(Document):
    email = fields.TextField()
    username = fields.TextField()
    first_name = fields.TextField()
    ...
    ...
    ...


    comment = fields.NestedField(properties={
        # other fields...
        'some_field': fields.TextField(),
        'reply_type': fields.ObjectField(),
    })    

    class Index:
        name = 'user'
        settings = {
            'number_of_shards': 1,
            'number_of_replicas': 0
        }

    class Django:
        model = User        

问题是当我做索引时reply_type是空的

"reply_type": [
   { },
   { }
]

有什么建议吗?

标签: pythondjangoelasticsearchdjango-models

解决方案


像这样构造您的reply_type ObjectField:

'reply_type': fields.ObjectField(properties={
        'one': fields.TextField(),
        'two': fields.TextField(),
})

推荐阅读