Elasticsearch Nested Filter

I am new to Elasticsearch and I am trying to create a filter to retrieve documents with specific attributes.

Attributes are defined as nested objects in a display like this:

"attributes": {
  "type": "nested",
    "properties" : {
      "id": {
        "type": "integer"
      },
      ...
    }
  }
}

I am trying to execute a complex query in the form:

(attribute.id == 1 OR attribute.id == 2) AND (attribute.id == 3 OR attribute.id == 4)

According to what I have read so far, I have created the following query for es:

{
  "query": {
    "filtered": {
     "query": {
        "match_all": {}
     },
     "filter": {
        "nested": {
           "path": "attributes",
           "filter": {
              "bool": {
                "must": [
                    { "bool" : {
                      "should" : [
                        { "term": { "attributes.id": 1 }},
                        { "term": { "attributes.id": 2 }}
                      ]
                    }},
                    { "bool" : {
                      "should" : [
                        { "term": { "attributes.id": 3 }},
                        { "term": { "attributes.id": 4 }}
                      ]
                    }}
                ]
              }
           }
        }
     }
  }
},
"sort": {
    "date": { "order": "desc" }
  }
}

However, this does not return any results. If I delete one of the two boolsin the block must, it filters the documents correctly.

The same problem exists (no results) if I change the request (for testing purposes) to:

"must": [
  { "term": { "attributes.id": 3 }},
  { "bool" : {
    "should" : [
      { "term": { "attributes.id": 1 }},
      { "term": { "attributes.id": 2 }}
    ]
  }}
]

which, as I understand it, translates into attributes.id == 3 AND (attributes.id == 1 OR attributes.id == 2)

This is elasticsearch 2.x. What am I doing wrong?

+4
source share
1 answer

, , nested bool.

:

{
  "bool":{
    "must":[
      {
        "nested":{
          "path":"attributes",
          "filter":{
            "bool":{
              "should":[
                { "term": {"attributes.id": 1 }},
                { "term": {"attributes.id": 2 }}
              ]
            }
          }
        }
      },
      {
        "nested":{
          "path":"attributes",
          "filter":{
            "bool":{
              "should":[
                { "term": {"attributes.id": 3 }},
                { "term": {"attributes.id": 4 }}
              ]
            }
          }
        }
      }
    ]
  }
}

. , :

/, ( ) ( ).

nested ( ). , .

id = (1 2) id = (3 4) . , , id.

+3

Source: https://habr.com/ru/post/1625503/


All Articles