Search code examples
ruby-on-railselasticsearchsearchkick

Searchkick - ranges on 2 separate columns


I'm trying to create multiple ranges with 2 columns. I know multiple ranges can be achieved but I need it to work with 2 columns.

In my model I have a min_age and max_age. The user can select multiple ages to filter from, for example: the options are 10,11,12,13,14,15,16,17,18 and the user selects 11, 13 and 16. How would I filter the model from the selected options?

Also, I think I need to change the selected options to a range so the above would become, 10-11, 12-13 and 15-16 so the range filter can work by using the gt and lt args. However, maybe a range filter won't work for this?

EDIT

In SQL I can do the below, which returns what I am expecting to see so I just need to convert this into elasticsearch syntax via Searchkick.

  select * from events
  where (min_age <= 11 AND max_age >= 11)
  OR (min_age <= 13 AND max_age >= 13)
  OR (min_age <= 16 AND max_age >= 16)

Solution

  • Without delving into whether or not ranges are the best option for your application logic, to achieve the equivalent to your SQL you can use something like the following:

    Event.search(
      "*",
      where:  {
                _or: [
                       {min_age: {lte: 11}, max_age: {gte: 11)},
                       {min_age: {lte: 13}, max_age: {gte: 13)},
                       {min_age: {lte: 16}, max_age: {gte: 16)}
                     ]
              }
    )