Bool filter and must - must not Query with nested not right response

This is my mappings:
"mappings": {
"_doc":{
"properties": {
"channels": {
"type": "nested",
"properties":{
"name":{
"type":"keyword"
},
"value":{
"type":"long"
}
}
}

This is my DSL:
GET my_index2/_search
{
"_source": "channels.name",
"query": {
"bool": {
"filter": {
"nested": {
"path": "channels",
"query": {"bool": {
"must": [
{"match": {
"channels.name": "cXl0zgxy1e6"
}}
],
"must_not": [
{"match": {
"channels.name": "SwZ0PLh0gxD"
}}
]
}}
}
}
}
}
}

This is result:
image
The result did not follow my expectations;
The channels is a array contains nested type;
I dont have any idea...
And I want get doc that nested objet equal “cXl0zgxy1e6“,but not ”SwZ0PLh0gxD“;
Can you help me? Thanks !!

There is a problem with the boolean logic of your bool query. :slightly_smiling_face: Which is not uncommon, because when you combine bool queries with nested queries, things become a bit complicated.

Your query basically asks Elasticsearch "find me a document that has at least one nested object that does not have a channel.name equal to SwZ0PLh0gxD." Which your document matches, because there is a nested object that has a channel.name set to cXl0zgxy1e6, which is not SwZ0PLh0gxD.

What you want to do instead is take the bool query out of the nested query. This way you ask Elasticsearch "find me a document that does not have any nested object that has a channel name equal to SwZ0PLh0gxD. That query would look like this:

GET my_index2/_search
{
  "_source": "channels.name",
  "query": {
    "bool": {
      "filter": {
        "nested": {
          "path": "channels",
          "query": {
            "match": {
              "channels.name": "cXl0zgxy1e6"
            }
          }
        }
      },
      "must_not": [
        {
          "nested": {
            "path": "channels",
            "query": {
              "match": {
                "channels.name": "SwZ0PLh0gxD"
              }
            }
          }
        }
      ]
    }
  }
}
1 Like

ye This is useful; Thank you for your kind reply,

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