1

I am using the Element API to search for entries that match a search query: either the title OR the excerpt should contain the query term. The entry is very simple and has these fields:

-title
-excerpt
-link

when I use this to only search in the title field it works:

$section_handle = ['item'];
$q = Craft::$app->request->getParam('query');

$criteria = [
   'section' => $section_handle, 
   'search' => 'title:'.$q
];

So I thought I just add the excerpt field like this:

$criteria = [
   'section' => $section_handle, 
   'search' => 'title:'.$q.' OR '.'excerpt:'.$q
];

but this did NOT work and I found out that it just won't search that excerpt field, this also does not work:

   $criteria = [
   'section' => $section_handle, 
   'search' => 'excerpt:'.$q
];

After some research I found out that when I use this as the 'criteria' it works:

$criteria = [
    'section' => $section_handle, 
    'excerpt' => "*{$q}*"
];

And now I wonder how to proceed. How can I either get the first example to work to search in the excerpt field, or add the OR title clause to my latest example where I am able to search in the excerpt field...

I hope this makes sense and that someone can point me in the right direction!

Thanks very much,

Wouter

2

In your last example:

$criteria = [
    'section' => $section_handle, 
    'excerpt' => "*{$q}*"
];

You are making a fuzzy search by surrounding your keyword(s) with * (see docs for syntaxes) and I wonder if that's why you are seeing results (I'd need to see the keywords/entry).

However, if that works, then this should work for you:

'criteria' => [
    'section' => $section_handle,
    'search' => ($q ? 'title:' . $q . ' OR '.'excerpt:*'. $q . '*' : null),
],

Alternatively, make everything fuzzy (not as precise):

'criteria' => [
    'section' => $section_handle,
    'search' => ($q ? 'title:*' . $q . '* OR '.'excerpt:*'. $q . '*' : null),
],

One final thought, if your section has three fields, if you only check Use this field’s values as search keywords on your Settings → Fields → excerpt field then you can search on both title + excerpt simply by doing:

'criteria' => [
    'section' => $section_handle,
    'search' => ($q ?? null),
],
0
1

thank you for your answer. It did help as in I understand it a bit better, and I finally got it to work!

The solution seems to be this:

check the excerpts field 'use this field's values as search keywords'

But then I had to recreate the entries and only then the searching worked!

I am very happy I got it to work now, thanks again Oli!!!

1
  • 1
    Oh! I see :) To re-index your entries, you can run ./craft resave/entries --update-search-index (docs) rather than having to recreate them.
    – Oli
    Dec 7 '20 at 5:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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