4

If I want to return all the documents which have an empty property (IMG) I can do something like that:

GET something/_search/?
{
  "query": {
    "term": {"IMG": ""}
  }
}

It works because IMG is a keyword. If I want the exact inverse, which means get all the documents where IMG is not null, what should I type? Is there an "inverse" of term query?

In other words, is there a way with Elasticsearch to get documents where a property is not empty?

rap-2-h
  • 30,204
  • 37
  • 167
  • 263
  • this answer should help: https://stackoverflow.com/questions/32949321/best-way-to-check-if-a-field-exist-in-an-elasticsearch-document/32949472#32949472 – Val Sep 14 '18 at 14:06
  • Thanks you for your comment. It does not really help, because these answers check for **existence**, not **emptiness**. – rap-2-h Sep 14 '18 at 14:09
  • Sorry, so you mean "the property is not the empty string"? – Val Sep 14 '18 at 14:11
  • @Val Yes. BTW I just found a solution and posted an answer right below. Feel free to comment, edit, or post your own answer! – rap-2-h Sep 14 '18 at 14:13
  • 1
    I've posted one, too ;-) – Val Sep 14 '18 at 14:15

2 Answers2

8

Your solution above would also return documents where the field is null, which you don't want I guess. So the correct solution would be this one:

GET memoire/_search/?
{
  "query": {
    "bool": {
      "filter": {
        "exists": {
          "field": "test"
        }
      },
      "must_not": {
        "term": {
          "test.keyword": ""
        }
      }
    }
  }
}
Val
  • 207,596
  • 13
  • 358
  • 360
2

Here is a solution. Use must_not with term query. This should work:

GET memoire/_search/?
{
  "query": {
    "bool": {
      "must_not": {
        "term": {"IMG.keyword": ""}
      }
    }
  }
}
rap-2-h
  • 30,204
  • 37
  • 167
  • 263
  • 1
    you have `must` instead of `must_not` – Val Sep 14 '18 at 14:13
  • @Val Woops! +1 thank you! (I was just checking with kibana the must_not then the must to be sure, and I posted the wrong one!). Edited, fixed! – rap-2-h Sep 14 '18 at 14:14
  • See my solution in order to make sure that you don't return docs with `IMG: null`. – Val Sep 14 '18 at 14:31