Search code examples
elasticsearchelasticsearch-7

How to combine simplequerystring with bool/must


I have this ElasticSearch query for ES version 7:

{
  "from": 0,
  "simple_query_string": {
    "query": "*"
  },
  "query": {
    "bool": {
      "must": [
        {
          "term": {
            "organization_id": "fred"
          }
        },
        {
          "term": {
            "assigned_user_id": "24584080"
          }
        }
      ]
    }
  },
  "size": 50,
  "sort": {
    "updated": "desc"
  },
  "terminate_after": 50,
}

but ES gives me back this error:

reason: Unknown key for a START_OBJECT in [simple_query_string]

my goal is to be able to use a query-string for multiple fields, and also use term/match with bool/must. Should I abandon the query string and just use bool.must[{match:"my query"}]?


Solution

  • You can use bool to combine multiple queries in this way. The must clause will work as logical AND, and will make sure all the conditions are matched.

    You need to include the simple_query_string inside the query section

    Adding Working example with sample docs, and search query.

    Index Sample Data

    {
      "organization_id": 1,
      "assigned_user_id": 2,
      "title": "welcome"
    }{
      "organization_id": 2,
      "assigned_user_id": 21,
      "title": "hello"
    }{
      "organization_id": 3,
      "assigned_user_id": 22,
      "title": "hello welocome"
    }
    

    Search Query :

        {
      "query": {
        "bool": {
          "must": [
              {
              "simple_query_string": {
                "fields" : ["title"],
                "query" : "welcome"
              }
            },
            {
              "match": {
                "organization_id": "1"
              }
            },
            {
              "match": {
                "assigned_user_id": "2"
              }
            }
          ]
        }
      }
    }
    

    Search Result:

    "hits": [
            {
                "_index": "my_index",
                "_type": "_doc",
                "_id": "1",
                "_score": 3.0925694,
                "_source": {
                    "organization_id": 1,
                    "assigned_user_id": 2,
                    "title": "welcome"
                }
            }
        ]