Is it possible to query multiple indices but only apply a bool to results from one of the indices?

My use case is this: I have an index items and an index userItems. In my query, I want to pull results that match a search term on both indices. HOWEVER, I want to only pull results from userItems that belong to the user.

I'm not sure how to structure a query where a bool clause is only applied to results from one of the indices and not the other. Can I do this in a single query? Do I need to split this into two different queries?

Any tips would be much appreciated! Thanks!

Hi Swidge,

Yes, you can do this like so:

GET /items,userItems/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "match": {
                  "myfield": "potato"
                }
              }
            ],
            "filter": [
              {
                "term": {
                  "_index": "items"
                }
              }
            ]
          }
        },
        {
          "bool": {
            "must": [
              {
                "match": {
                  "myfield": "potato"
                }
              }
            ],
            "filter": [
              {
                "term": {
                  "_index": "userItems"
                }
              },
              {
                "term": {
                  "username": "bob"
                }
              }
            ]
          }
        }
      ]
    }
  }
}

Hopefully that makes sense, by having a top level bool query this essentially says "give me all the documents that have "potato" in "myfield" in the "items" index, OR all the documents that have "potato" in "myfield" in the "userItems" index that also have the "username" of "bob".

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