Getting incorrect results while doing nested must and should

If written in SQL it would be:

Select * from Cars where id=10 and((color='blue' and company='BMW') OR (color='red' and company ='Mercedes'))

I've tried with Nested must and should like:

{
  "query": {
    "bool": {
      "must": [
        {
          "terms": {
            "id": [
              10
            ]
          }
        },
        {
          "bool": {
            "should": [
              {
                "nested": {
                  "path": "cars",
                  "query": {
                    "bool": {
                      "must": [
                        {
                         "terms": {
                           "cars.company": [
						   "BMW"
						   ]
                         }
                        },
                        {
                          "terms": {
                            "cars.color": [
                              "blue"
                            ]
                          }
                        }
                      ]
                    }
                  }
                }
              }, 
              {
                "nested": {
                  "path": "cars",
                  "query": {
                    "bool": {
                      "must": [
                        {
                          "terms": {
                            "cars.company": [
                              "Mercedes"
                            ]
                          }
                        },
                        {
                          "terms": {
                            "cars.color": [
                              "red"
                            ]
                          }
                        }
                      ]
                    }
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

When I did this, I am only getting the results for first part of query(i.e., id=10 and car.company=BMW and car.color = blue) even though the index consists data for mercedes and red color. Do I need to modify anything in the query?

Hi rama_krishna,

Can you provide one example of document you indexed? And if possible the relevant part of the mapping. That would help someone to reproduce the behavior you described.

Cheers,
LG

Hi Luiz,

Found the fix. Actually, the issue is with the data as it has special characters in the data. There is no change in the query; it is bringing back the correct set of results.

Thanks for your reply.

1 Like

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