Mark Lorenzo
Mark Lorenzo

Reputation: 33

ElasticSearch query_string with filter failed to get the results

I have the following Elasticsearch query (its usually bigger, but stripped out the part which causes the issues):

'query' => [
    'bool' => [
        'must' => [
            'query_string' => [
                'query' => $keywords,
                'fields' => ['title']
            ]
        ],
        'filter' => [
             'term' => [
                'school_id' => 1
            ]
         ]
    ]
]

But if I remove the filter it's working fine, but what I want is to filter only the search with the specific school id.

Upvotes: 1

Views: 249

Answers (1)

Green
Green

Reputation: 2555

Why don't you instead of filtering the data - just take what you need in the first place?

Filtering is used for a binary result-in a sense, if you would like to know if a document field school_id is 1 or not. If you just want to get a result there is other ways to do it as well.

In your case I think believed you just "jumped" over the mustand the bool and this is the reason your query failed.

As so, you got 2 options, the first to fix yours as follows:

GET /_search
{
  "query": {
    "bool": {
      "must": {
        "query_string": {
          "default_field": "keywords",
          "query": "title"
        }
      },
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "school_id": "1"
              }
            }
          ]
        }
      }
    }
  }
}

OR if you wish to get a scoring to your result you can use this one:

GET /_search
{
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "default_field": "keywords",
            "query": "title"
          }
        },
        {
          "match": {
            "school_id": {
              "query": "1"
            }
          }
        }
      ]
    }
  }
}

Upvotes: 1

Related Questions