Elastic4s - finding multiple exact values for one

2019-08-07 20:53发布

问题:

I'm trying to filter a term to be matching one of the values in an array.

relaying on the ES https://www.elastic.co/guide/en/elasticsearch/guide/current/_finding_multiple_exact_values.html

 GET /my_store/products/_search
            {
                "query" : {
                    "filtered" : {
                        "filter" : {
                            "terms" : { 
                                "price" : [20, 30]
                            }
                        }
                    }
                }
            }

I tried this:

    val res =  ESclient.execute {
        search in "index" query {
          filteredQuery query {
            matchall
          } filter {
                   termsFilter("category", Array(1,2))
          }
        }

But got an error from ES.

How can I do that?

回答1:

When calling termsFilter, the method is expecting a var args invocation of Any*, so termsFilter("category", 1, 2) would work. But termsFilter("category", Array(1,2)) is treated as a single argument, since Array is a subclass of Any of course. By adding : _ * we force scala to see it as a vars arg invocation.

So this will work:

val res =  ESclient.execute {
  search in "index" query {
    filteredQuery query {
      matchall
   } filter {
        termsFilter("category", Array(1,2) : _ *)
   }
}

Maybe the best solution of all is to update the client to be overloaded on Iterables.