Return all results where field is missing or false


#1

How could I return all results where myboolean field below is either missing or false? I want it to be under filter because I don't want it to contribute to the store, it should just remove all results where myboolean is true. This is the rough idea I had of what it should look like but it doesn't work.

{
	"query": {
		"bool": {
			"filter": [
				{ "must_not": { "exists": { "field": "myboolean" } } },
				{ "term": { "myboolean": false } }
			]
		}
	}
}

(Matija Bruncic) #2

I think that you should use "should bool query" https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

Something like this:

POST /index/_search
{
  "query": {
    "bool": {
      "filter": {
        "bool": {
          "should": [
            {
              "term": {
                "myboolean": false
              }
            },
            {
              "bool": {
                "must_not": {
                  "exists": {
                    "field": "myboolean"
                  }
                }
              }
            }
          ]
        }
      }
    }
  }
}

it should just remove all results where myboolean is true

Don't you think you can simplify this with must not term filter myboolean:true?


#3

That sounds like a great idea, could you show me how I could add that to this new query? Would I need to add a new object to the filter array?

{
	"query": {
		"bool": {
			"must": {
				"multi_match": {
					<some content here>
				}
			},
			"filter": [
				{ "must_not": { "term": { "myboolean": true } } },
				{ "term": { "otherboolean": false } },
				{ "range": { "myfield": { gte: 50 } } }
			]
		}
	}
}

(Matija Bruncic) #4

You almost got it, the only thing you should add is another bool inside a filter. This should work:

POST index/_search
{
  "_source": "myboolean", 
  "query": {
    "bool": {
      "filter": {
        "bool": {
          "must_not":{
            "term":{
              "myboolean": true
            }
          }
        }
      }
    }
  }
}

I just tested it and my results look like this:

"hits": [
      {
        "_index": index",
        "_type": "_doc",
        "_id": "1",
        "_score": 0,
        "_source": {
          "myboolean": false
        }
      },
      {
        "_index": "index",
        "_type": "_doc",
        "_id": "2",
        "_score": 0,
        "_source": {}
      }]

(system) #5

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