scout icon indicating copy to clipboard operation
scout copied to clipboard

fix(typesense): properly format boolean filters in Typesense

Open tharropoulos opened this issue 1 year ago • 0 comments

Rationale

This change addresses an issue where boolean filters were not properly handled in the TypesenseEngine for Laravel Scout. When users attempted to search with a boolean filter (e.g., Model::search($query)->where('myFilter', true)->get()), the engine was incorrectly transforming boolean values to integers before passing them to the Typesense SDK. This resulted in a Typesense\Exceptions\RequestMalformed exception with the message "Value of filter field myFilter must be true or false."

By implementing this fix, we ensure that boolean filters are correctly formatted and passed to Typesense, allowing users to perform searches with boolean conditions as expected.

Changes

Code Changes:

  1. In src/Engines/TypesenseEngine.php:
    • Modified the filters method to use a new parseFilterValue method when processing wheres and whereIns.
    • Added a new parseFilterValue method to handle various data types, including booleans:
      protected function parseFilterValue(array|string|bool|int|float $value)
      {
          if (is_array($value)) {
              return array_map([$this, 'parseFilterValue'], $value);
          }
      
          if (gettype($value) == 'boolean') {
              return $value ? 'true' : 'false';
          }
      
          return $value;
      }
      
    • Updated parseWhereInFilter method to use string interpolation for better readability.

Test Updates:

  1. In tests/Unit/TypesenseEngineTest.php:
    • Added new test methods to cover the changes:
      • test_filters_method: Ensures the filters method correctly formats multiple conditions.
      • test_parse_filter_value_method: Verifies the new parseFilterValue method handles various input types correctly.
      • test_parse_where_filter_method: Checks the parseWhereFilter method's output for different inputs.
      • test_parse_where_in_filter_method: Validates the parseWhereInFilter method's formatting.
    • Implemented a helper method invokeMethod to test protected methods.

Context

This change was prompted by #873. @bredmor encountered a RequestMalformed exception when attempting to use boolean filters with Typesense in Laravel Scout. The problem was traced to the TypesenseEngine::filters() method, which was not properly handling boolean values.

This fix ensures that boolean values are correctly formatted as strings ('true' or 'false') before being sent to Typesense, resolving the exception and allowing users to successfully perform searches with boolean filters.

tharropoulos avatar Oct 21 '24 11:10 tharropoulos