当前位置: 动力学知识库 > 问答 > 编程问答 >

elasticsearch - 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.

网友答案:

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

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: