Matching fields in a if-then manner

Hello,
I have a user object with nested objects such as "stores" (favorite shopping stores) inside which we have details such as the id of the store, the brand of the store, country of the store, etc.

I want to come with a query for 2 separate scenarios but have not been successful:

  1. People who visit only Brand B in Country C1.
  2. People who visit only store 1 for brand B in C1. (This should include people who go to brand d in store 2 but not those who go to brand B in store 2)

Any leads?

Your constraints aren't terribly clear, so I've reformulated the first one as: People who, in country C1, visit only Brand B and no other brands. It's OK for them to visit Brand B or any other brands in a different country.

Here's an example:

PUT t 
{
  "mappings": {
    "t": {
      "properties": {
        "stores": {
          "type": "nested",
          "properties": {
            "brand": {
              "type": "keyword"
            },
            "country": {
              "type": "keyword"
            }
          }
        }
      }
    }
  }
}

PUT t/t/1
{
  "stores": [
    {
      "brand": "B",
      "country": "C1"
    },
    {
      "brand": "A",
      "country": "C1"
    }
  ]
}

PUT t/t/2
{
  "stores": [
    {
      "brand": "B",
      "country": "C1"
    },
    {
      "brand": "A",
      "country": "C2"
    }
  ]
}

GET t/_search
{
  "query": {
    "bool": {
      "filter": {
        "nested": {
          "path": "stores",
          "query": {
            "bool": {
              "filter": [
                {
                  "match": {
                    "stores.brand": "B"
                  }
                },
                {
                  "match": {
                    "stores.country": "C1"
                  }
                }
              ]
            }
          }
        }
      },
      "must_not": {
        "nested": {
          "path": "stores",
          "query": {
            "bool": {
              "filter": {
                "match": {
                  "stores.country": "C1"
                }
              },
              "must_not": {
                "match": {
                  "stores.brand": "B"
                }
              }
            }
          }
        }
      }
    }
  }
}

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