Search code examples
pythonelasticsearchelasticsearch-dsl

Unexpected outcome with Elasticsearch-DSL filter


I'm new to Elasticsearch and python's elasticsearch-dsl and I really can't figure out why my filter returns no results:

In [1]: from elasticsearch import Elasticsearch 
   ...: from elasticsearch_dsl import Search 
   ...:  
   ...: search = Search(using=Elasticsearch())                                            

In [2]: search.execute()                                                     
Out[2]: <Response: [<Hit(general-index/1): {'first_name': 'Piero', 'full_name': 'Piero Pierone'}>]>

In [3]: search.filter('term', first_name='Piero').count()                  
Out[3]: 0

My index contains only one entry with first_name == 'Piero' so I'd expect this to be returned and count equal to 1. I get 0 instead.


Solution

  • Try with this, it should work :

    search.filter('term', first_name='piero').count()
    

    The term query lowercase all charachters, and it is not very useful to match exact queries. Refer to the warning section on the link to use match query instead, like this :

    search.filter('match', first_name='Piero').count()
    

    Here you have all the results with diferent queries and type of queries :

    In [19]: search.filter('term', first_name='Piero').count()   
    Out[19]: 0
    
    In [20]: search.filter('term', first_name='piero').count()   
    Out[20]: 1
    
    In [21]: search.filter('match', first_name='Piero').count()   
    Out[21]: 1
    
    In [22]: search.filter('match', first_name='piero').count()   
    Out[22]: 1