Search code examples
node.jsmongodbelasticsearchmongoosastic

Elasticsearch bool query with filter and should


My main aim is to write a query that must search for the searchtext and if any filter of loading port or unloading port is applied then it must filter that from the result of search text.

And if no filter is applied then it should proceed further.

For eg: I search for jeans and if I apply filter then the loading port must be India and its unloading port must be US.

I tried to write this report but it's not giving appropriate result.

{
 "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "query_string": {
                  "query": searchText
                }
              }
            ]
          }
        },
        {
          "terms": {
            "loadingPort":loadingPortArray
          }
        },
        {
          "terms": {
            "unloadingPort":unloadingPortArray
          }
        }
      ]
    }
  }
}

Solution

  • Your problem is that you are wrapping all the quires\filters inside should, which means that all the statements with be combined by OR logic. If you need AND you need to wrap statements inside must.

    By the way, you are not using filter, you are using term query. There is huge difference between query and filter in elasticsearch. To use filter you need to use bool query with filter.

    {
     "query": {
        "bool": {
          "must": [
            {
              "bool": {
                "must": [
                  {
                    "query_string": {
                      "query": searchText
                    }
                  }
                ]
              }
            }        
          ],
          "filter": {
              "bool": {
                  "must": [
                      {
                        "terms": {
                            "loadingPort":loadingPortArray
                        }
                      },
                      {
                        "terms": {
                            "unloadingPort":loadingPortArray
                        }
                      }
                  ]
              }
          }
        }
      }
    }