0

I created a view using indexed fields (search api) to list a taxonomy. I used the rest export checkbox so I have an api endpoint for my view. I am not able to find a filter criteria "starts with" for a field (indexed) that is a string. I don't understand why, the field is behaving like an integer and showing greater than, less than etc..

I am trying to use the hook_views_query_alter but I am getting an error from the line $query->where :

Error: Cannot access protected property Drupal\search_api\Plugin\views\query\SearchApiQuery::$where

In my view , I can see in the "Preview" section the query :

Index: books
Keys: NULL
Options: array (
    'search_api_view' => 'object (Drupal\\views\\ViewExecutable)',
    'search_api_base_path' => 'api/books',
  )

How do I add a filter criteria "starts with" for an indexed field which is a string? Thanks for your help

2
  • 1
    Apparently, this is a known and old issue since there was a Drupal 7 module specifically for that need. I had an index where I had to filter on author names and I did use the trick mentioned here: drupal.org/project/search_api/issues/3114833#comment-13528391. Perhaps it may help you as well.
    – misterdidi
    Commented Jan 10, 2022 at 9:39
  • @misterdidi thanks for your help! I will try that
    – el sparrow
    Commented Jan 11, 2022 at 6:15

1 Answer 1

0

See the full thread linked by @misterdidi here: https://www.drupal.org/project/search_api/issues/3114833#comment-13528391 This is the gist of it:

If it’s “starts with” you are interested in, you could conceivably emulate this using “greater than”: field STARTS WITH 'abc' is pretty much the same as field >= 'abc' AND field < 'abd' (unless the field is multi-valued – then you’d have to use IS BETWEEN

If you're using Solr index fields, this field has to be of type string (not fulltext). The letter to be filtered on can be set on the url parameters: url.tld?initial=a for example.

You can implement this filter using hook_views_query_alter. Here "surname" is the machine name of the field as set in solr index fields.

function my_module_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() === 'my_view') {
    // Get filter value from URL.
    $initial = strtoupper(\Drupal::request()->query->get('initial'));
    if (!empty($initial)) {
      $query->addWhere(0, 'surname', $initial, '>=');
      $query->addWhere(0, 'surname', ++$initial, '<');
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.