pythondjangoelasticsearchelasticsearch-dsl-py

How to map keyword field in Django Elasticsearch?


I am using django-elasticsearch-dsl library a high level client to interact with elasticsearch.

This is my Document.py file

from django_elasticsearch_dsl import Document
from django_elasticsearch_dsl.registries import registry
from .models import Clothes

@registry.register_document
class ClothesDocument(Document):

    class Index:
        # Name of the Elasticsearch index
        name = 'clothes'
        settings = {'number_of_shards': 1,
                    'number_of_replicas': 0}

    class Django:
        # The django model associated with this Document
        model = Clothes 

        # The fields of the model you want to be indexed in Elasticsearch
        fields = [
            'Type',
            'Pattern',
            'Category',   
            'Title',
            'Description',]

Here is the model file from django.db import models

class Clothes(models.Model):
    Type = models.TextField(null=True)
    Pattern = models.TextField(null=True)
    Type = models.TextField(null=True)
    Brand = models.TextField()
    Category = models.TextField()

I want to use "term" and "terms" query [Ex. Q("term", Category="Male")] for which I am required to define Category as a KeywordField in Documents.py, How to do that? or Am I missing something?


Solution

  • I figured out how to explicitly map keyword fields:

    In documents.py

     Category = fields.TextField(
                    fields={'raw': fields.KeywordField()},
                    analyzer="keyword")
    

    Rather than letting Django-Elasticsearch-Dsl take care of mapping, we have to explicitly map our index.