Home > Blockchain >  Use of zero_terms_query in elasticsearch dsl query
Use of zero_terms_query in elasticsearch dsl query

Time:06-02

Can anyone explain zero_terms_query elasticsearch in detail, I went through elasticsearch documentation but I didn't understand properly

CodePudding user response:

Lets understand it by taking our own example, for that lets create an index using the english analyzer which would remove all the english stop words like to be or not to be example given by Elasticsearch.

Index mapping

{
    "mappings" : {
        "properties" : {
            "title" : {
                "type" : "text",
                "analyzer" : "english"
            }
        }
    }
}

Index few sample document

{
    "title": "sudeesh"
}

{
    "title": "to be or not to be"
}

Search query which removes all the stop words from query as we are using match query which applies the same english analyzer to search query.


{
    "query": {
        "match": {
            "title": {
                "query": "to be or not to be",
                "operator": "and",
                "zero_terms_query": "all"
            }
        }
    }
}

Search result

 "hits": [
            {
                "_index": "72442818",
                "_id": "1",
                "_score": 1.0,
                "_source": {
                    "title": "to be or not to be"
                }
            },
            {
                "_index": "72442818",
                "_id": "2",
                "_score": 1.0,
                "_source": {
                    "title": "sudeesh"
                }
            }
        ]

Note, above search query returns both the document as we specified "zero_terms_query": "all" so it would be considered as match_all and returns all the documents.

If you remove "zero_terms_query": "all" than it would be considered as none default value mentioned in Elasticsearch documentation and you wouldn't get any search result as there is no search term to search in the Elasticsearch.

this is especially useful when you are having all stop words in your query, and instead of 0 search results you want to return more search results.

  • Related