Search code examples
ruby-on-railselasticsearchsearchkick

Searchkick Aggregation OR


I'm using Searchkick to search for products. It's working great but now I'm adding in filters. Because of the nature of the products I always want to show for the selected filter so rather than using AND it always need to use OR.

I'm building the search like:

    Product.search(
          "shower",
          fields: [:name]
          where: {showers_ids: [46,41], accessories_ids: [104, 102]},
          aggs: [: showers_ids, : accessories_ids, : bath_ids]
    )

This is trying to query:

where IN (46 OR 41) AND (104 OR 102)

This will always bring back no products as the products are only ever in one Category. But I'd like to show products from all the categories so it needs to be like:

where IN (46 OR 41) OR (104 OR 102)


Solution

  • You should be able to achieve your desired result using the or_ parameter in your where clause. There's an example of this in the Searchkick docs, but for your specific scenario, the following should work:

    Product.search(
      "shower",
      fields: [:name],
      aggs:   [:showers_ids, :accessories_ids, :bath_ids],
      where:  {
                _or: [
                       {showers_ids:     [46, 41]},
                       {accessories_ids: [104, 102]}
                     ]
              }
    )