1
GET dspdocs/_search
{
 "query": {
  "filtered": {
    "filter": {
      "bool": {
        "must": ["must_term1", "must_term2"],
        "must_not": ["must_not_term", "must_not_term2"]
        }
      },
    "query": {
      "match": {
        "text": {
          "query": "query_term",
          "operator": "or"
        }
      }
    }
  }
}
}

I am trying to execute the above query and I get the following error:

"type": "query_parsing_exception",
"reason": "[_na] query malformed, must start with start_object",

I know this means that my query hasn't been written properly or I've screwed up some order somewhere but for the life of me, I can't seem to figure out where I went wrong.

I'm basically trying to filter out all documents which don't contain the must terms and contain the must_not terms. Then I search within the filtered set for all documents which have the query_term in them.

(I do the filtering first to increase the speed of the search slightly)

2
  • Could you given an example of must_term1 and must_not_term ? Are they term queries or just a query_term ? Commented Jun 23, 2016 at 20:15
  • They are just strings, just needed to convert them into term queries like pickypg showed below and it works! Commented Jun 24, 2016 at 13:45

1 Answer 1

3

Your issue is in the example:

...
  "bool": {
    "must": ["must_term1", "must_term2"],
    "must_not": ["must_not_term", "must_not_term2"]
    }
  },
...

The array of must and must_not (and should and filter for that matter) expects either a single object or an array of objects. For example:

"bool": {
  "must": [
    {
      "term" : {
        "my_field" : "must_term1"
      }
    },
    {
      "term" : {
        "my_field" : "must_term2"
      }
    }
  ],
  "must_not": [
    {
      "term" : {
        "my_field" : "must_not_term"
      }
    },
    {
      "term" : {
        "my_field" : "must_not_term2"
      }
    }
  ]
}

Note that I am using the term query, but you're free to use any type of query. With Elasticsearch 2.x+, you should write this as a pure bool query, rather than a filtered one:

{
  "query": {
    "bool": {
      "must": [
        {
          "query_string" : {
            "query" : "query_term"
          }
        }
      ],
      "must_not": [
        {
          "term" : {
            "my_field" : "must_not_term"
          }
        },
        {
          "term" : {
            "my_field" : "must_not_term2"
          }
        }
      ],
      "filter": [
        {
          "term" : {
            "my_field" : "must_term1"
          }
        },
        {
          "term" : {
            "my_field" : "must_term2"
          }
        }
      ]
    }
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.