django-es / django-elasticsearch-dsl

This is a package that allows indexing of django models in elasticsearch with elasticsearch-dsl-py.
Other
1.02k stars 262 forks source link

How to add a mapping on the Document class #475

Open pulse-mind opened 7 months ago

pulse-mind commented 7 months ago

I have a Document class like that :

@registry.register_document
class MyDataDocument(Document):    
    data_json = fields.ObjectField()

    def prepare_data_json(self, instance):
        return instance.data_json    

    class Index:
        name = "mydata"
        settings = {"number_of_shards": 1, "number_of_replicas": 0}

    class Django:
        model = MyData
        fields = [
            "data_name",            
        ]

But for some reason in the JSON I have data_json.form.content = '2024-24' but elastic defined this field as Date. So I get an exception during the indexing. I wanted to define a specific mapping for this and my idea was to add a class Meta into my MyDataDocument, something like this :

class Meta:
        mapping = {
            "properties": {
                "data_json": {
                    "properties": {
                        "form": {
                            "properties": {
                                "content": {
                                      "type": "text",
                                       "fields": {
                                              "keyword": {
                                                  "type": "keyword",
                                                  "ignore_above": 256
                                               }                                    
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

But it does not work like this. Is it possible to define it in the Document Class ?

pulse-mind commented 7 months ago

It seems to work with :

data_json = fields.ObjectField(
        properties={
            "form": fields.ObjectField(
                properties={
                    "content": fields.TextField()
                                                }
                                            )
                                        }
                                    )