Elastic Search Query String Feature

by Devansh


Posted on 18 Nov 2018 09:11:57 (1 month ago)




If you want to search keywords in a particular docs and you want if all the keywords are present in elasticsearch doc then display the result otherwise no results will be displayed.

So, in this case we will use elastic search query string feature.

Suppose you have a document which contains data in elasticsearch, Please look the below e.g.,

{
    "content": "Lorem Ipsum is simply dummy text of the printing and typesetting industry Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
}

Now, we will apply "query_string" feature,

GET test/test/_search
{
    "query" : {
        "query_string" : {
            "field" : ["content"],
            "query" : "lorem AND ipsum AND been"
        }
    }
}

Now, as you see the query i am searching for lorem, ipsum and been. If any of these three keywords not present in elasticsearch docs then no results will be displayed.

By default "query_string" operator is set to 'OR'. So, if you search like this,

GET test/test/_search
{
    "query" : {
        "query_string" : {
            "field" : ["content"],
            "query" : "lorem ipsum been"
        }
    }
}

Then, you will get result of 'lorem' OR 'ipsum' OR 'been' i.e. if in document any of the keyword present then elasticsearch will display results.

So, in order to achive our result. We need to change the default operator. So our updated query will be,

GET test/test/_search
{
    "query" : {
        "query_string" : {
            "field" : ["content"],
            "query" : "lorem ipsum been",
            "default_operator" : "AND"
        }
    }
}

Now this query will search the result for 'lorem' AND 'ipsum' AND 'been' i.e. if any of the keyword not present then elasticsearch will not display the result.