betto86
betto86

Reputation: 714

Boolean filter on nested objects

I'm having some troubles using boolean operators with nested objects. This is my mapping:

   "IP": {
        "properties": {
          "ip": {
            "type": "ip"
          }
        },
        "type": "nested"
      }

I want to get documents which contains exactly two specified ips and maybe more.

Suppose that my document has the followinh ips:

    DOC 1
        192.168.1.0
        192.168.0.1
        10.0.0.9

    DOC 2
       192.168.0.1

I want to retrieve only DOC 1 by searching with this filter:

      "bool": {
        "must": {
          "terms": {
            "IP.ip": [
              "192.168.0.1",
              "10.0.0.9"
            ]
          }
        }
      }

The problem is that both DOC 1 and DOC2 are retrieved.

Upvotes: 2

Views: 138

Answers (2)

deepakchauhan
deepakchauhan

Reputation: 290

You can use "minimum_match" with "terms" query

"bool": {
    "must": {
      "terms": {
        "IP.ip": [
          "192.168.0.1",
          "10.0.0.9"
        ],
        "minimum_match" :"100%"
      }
    }
  }

This would return the record which contains all the values in terms query.

Upvotes: 1

Sloan Ahrens
Sloan Ahrens

Reputation: 8718

You can use "execution":"and" on your terms filter like this:

{
   "filter": {
      "bool": {
         "must": [
            {
               "terms": {
                  "ip": [
                     "192.168.0.1",
                     "10.0.0.9"
                  ],
                  "execution": "and"
               }
            }
         ]
      }
   }
}

Here is some code I used to test it:

http://sense.qbox.io/gist/d6b5f4e4c0d2977a04b1795f4bbb0503f6365dfe

EDIT: Nested version (I misunderstood the question).

This query should give you what you need, assuming your index is set up the way I set up mine for testing (see code below). There need to be two nested clauses in the must list since we are looking for a document that contains two different nested documents, one with each IP.

POST /test_index/_search
{
   "filter": {
      "bool": {
         "must": [
            {
               "nested": {
                  "path": "ips",
                  "filter": {
                     "term": {
                        "ip": "192.168.0.1"
                     }
                  }
               }
            },
            {
               "nested": {
                  "path": "ips",
                  "filter": {
                     "term": {
                        "ip": "10.0.0.9"
                     }
                  }
               }
            }
         ]
      }
   }
}

Here is the code I used to set it up:

http://sense.qbox.io/gist/cd3a0ec61cb1348d5cc2bd1ef444f4898f6d8e57

Upvotes: 3

Related Questions