Is it possible to add alter query to add an "OR" operator condition?

Created on 22 March 2023, over 1 year ago
Updated 2 June 2024, 26 days ago

Problem/Motivation

We need to alter a Search API query using hook_search_api_query_alter() to add an additional condition OR condition that is "any of the previous condition OR this new condition"

Example: We want to show nodes whose State field is Florida or the Location Type field is "National".

Doing something like the below continues to narrow the results instead of expanding them as Florida is already set in the View query and the alter code below now narrows the results to State=FL AND Type=National instead of State=FL OR Type=National

  $parse_mode = \Drupal::service('plugin.manager.search_api.parse_mode')->createInstance('direct');
  $parse_mode->setConjunction('OR');
  $query->setParseMode($parse_mode);
  $conditions = $query->createConditionGroup('OR');
  $conditions->addCondition('field_resource_location_type', 'national', 'IN');
💬 Support request
Status

Fixed

Version

1.28

Component

General code

Created by

🇺🇸United States 3CWebDev

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

  • Issue created by @3CWebDev
  • Status changed to Fixed about 1 month ago
  • 🇦🇹Austria drunken monkey Vienna, Austria

    Sorry for taking so long to reply – it seems I overlooked this issue and was just pointed here by coincidence.
    In the future, if I take longer than a month to reply, if the issue is still relevant please feel free to ping me on Slack or via my contact form. (If it stops being relevant, please do go back and close it in any case.)

    The answer is that the parse mode is just for the fulltext keys, not the filters/conditions, so setting conjunction OR on the parse mode will not influence the condition you add in any way. For combining multiple conditions with OR, you need to add a new “condition group” with that conjunction and add conditions on that, instead of on the query directly. For instance, this code could be used to change all the existing conditions of a query to be combined with OR, and then add one more OR condition:

      $or_conditions = $query->createConditionGroup('OR');
      $old_conditions = &$query->getConditionGroup()->getConditions();
      foreach ($old_conditions as $condition) {
        if ($condition instanceof \Drupal\search_api\Query\ConditionInterface) {
          $or_conditions->addCondition($condition->getField(), $condition->getValue(), $condition->getOperator());
        }
        else {
          $or_conditions->addConditionGroup($condition);
        }
      }
      $old_conditions = [];
      $query->addConditionGroup($or_conditions);
      $or_conditions->addCondition('field_resource_location_type', 'national', 'IN');
    
  • Automatically closed - issue fixed for 2 weeks with no activity.

Production build 0.69.0 2024