Search code examples
scalaelasticsearchelastic4s

ElasticSearch - Get different types from different indices


I have two indices: A and B.

A has the following types: car, motorbike and van.

B has the following types: bus, car and pickup.

I want to be able to have a single query which gets motorbike and van from A and car and pickup from B.

I want to use a filter to do this and currently, I have:

.filter(
   not(
      should(
         termsQuery("key", Seq("car", "bus"))
      )
   )
)

But obviously, this will filter car for both indices. I know I can do two separate queries for each index and filter different types for each but I want to avoid this if possible.

Is it possible to do what I am trying to do in a single query?


Solution

  • You can search on index and type by using the special fields _index and _type so once you know that, it's just a matter of putting together a boolean query.

      search("_all").query(
        boolQuery().should(
          boolQuery().must(
            termQuery("_index", "A"),
            termsQuery("_type", "motorbike", "van")
          ),
          boolQuery().must(
            termQuery("_index", "B"),
            termsQuery("_type", "car", "pickup")
          )
        )
      )