Search code examples
pythonelasticsearchelasticsearch-dsl

Problem with elasticsearch queries like Q, term and terms


client = Elasticsearch()
s = Search(using=client,index="myntra_clothes")

fts_query = MultiMatch(query=data['text'], fields=['Title', 'Description'], operator="AND", fuzziness='AUTO')
s = s.query(fts_query)
s = s.filter('match', SubCategory3='Jeans')
result = s.execute()

While the above works just fine, Following is the list I tried, that won't work:

s = s.filter('terms', Colour['Blue','Black'])

q = Q('term', Category='Men') &  Q('term', SubCategory3='Jeans')
s = s.query(q)

es_query = []
es_query.append(Q("match", Category="Male"))
es_query.append(Q("match",SubCategory3="Jeans"))
final_query = Q("bool", must=es_query)
s = s.query(final_query)

These queries execute without throwing any error, just returns a blank response.

Update: I am using Django framework and follow is my mapping:

@registry.register_document
class MyntraClothesDocument(Document):

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

class Django:
    # The Django model associated with this Document
    model = MyntraClothes 

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

Solution

  • In the second query, you are using term or terms query. Both these queries work on exact matches

    The term/terms query does not apply any analyzer to the search term, so will only look for that exact term in the inverted index.

    To search for the exact term, you need to use the Category.keyword field OR change the mapping of the field. The search result will come if "Blue" OR "Black" terms are are present in the index.

    Whereas in the first query you are using match query, which analyzes the text (using standard analyzer if no analyzer is specified) while performing the search queries, therefore you are getting search results in the first query.