Problem Using 'must_not' to Exclude Matches

I'm trying to add a feature to my search where I can exclude users that contain certain hashtags from the result .

My code for including users that contain all of the given hashtags works, and is the same as the code below except it uses 'must' instead of 'must_not'.

When I change 'must' to 'must_not', it appears to have no effect whatsoever, instead of the intended effect of excluding users that contain those hashtags. I'm not sure what else to try or if I misunderstood the purpose of must_not.

I'm using ES 6.8 in PHP.

foreach ($this->hashtags as $hashtag) {
	$query[] = [
		'nested' => [
			'path' => 'hashtags',
			'query' => [
				'bool' => [
					'must_not' => [
							'match' => [
								'hashtags.hashtagId' => $hashtag


I think nested queries mean "give me documents where any of the nested objects matches the query", so this is indeed not doing what you want... Try moving the must_not negation outside of nested.

That causes the following error:

Elasticsearch\Common\Exceptions\BadRequest400Exception: {"error":{"root_cause":[{"type":"parsing_exception","reason":"no [query] registered for [must_not]","line":1,"col":95}],"type":"parsing_exception","reason":"no [query] registered for [must_not]","line":1,"col":95},"status":400}

must_not still needs to be wrapped by a bool query. Did you move bool together with it?

Moving the bool together with it fixed it, thanks a lot.

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.