Search code examples
pythondjangopython-3.xelasticsearchelasticsearch-py

Using HstoreField in Django/ElasticSearch


I'm new to elastic search and I really want to implement it in my Django project.
My problem: I want to store a Python dict object

 ({'key_1': 'value_1', 'key_2': 'value_2', [...]})  

and be sure that my search will look each key.
In Django I use Hstore field and I can access my datas doing

Model.objects.get(hstorefield__key='value')

Does anyone has an idea to do it using elastic search and be sure that all my keys for my Hstorefield are tracked ?

Thanks for help !

Here is my Django model:

class Product(models.Model):

    code = models.BigIntegerField()
    url_off = models.URLField()
    creator = models.CharField(max_length=200)
    product_name = models.CharField(max_length=200)
    last_modified_t = models.DateTimeField()
    created_t = models.DateTimeField()
    metadatas = HStoreField()

Solution

  • by default any and all fields you index into elasticsearch in your documents will be indexed and available for search and filtering. All you have to do is produce a document that also contains the fields from you HStoreField. If you want to control your mappings for those fields you need to define them first, for example using a DocType (0) class (analogous to django's Model):

    from elasticsearch_dsl import DocType, Long, Text, Keyword,Date, Object, InnerDoc
    
    class Metadata(InnerDoc):
        meta_field = Text()
        meta_number = Long()
        ...
    
    class Product(DocType):
        code = Long()
        creator = Text(fields={'keyword': Keyword()})
        last_modified_t = Date()
        metadata = Object(Metadata)
        class Meta:
            index = 'i'
    
    # create the index in elasticsearch, only run once
    Product.init()
    

    Then you just need to create a method on your model that will serialize it into the Product class:

    def to_search(self):
        return Product(
          _id=self.pk,
          code=self.code,
          creator=self.creator,
          metadata=Metadata(**self.metadatas)
        )
    

    Hope this helps!

    0 - http://elasticsearch-dsl.readthedocs.io/en/latest/persistence.html#doctype