SearchAPI module
Provides ability to search models using elastic search and scout.
Configuration
- Any model that wants to search using this module should implement and use
Modules\SearchApi\Contracts\SearchableContractinterface and useModules\SearchApi\Traits\HasSearchabletrait. - The model should then implement following methods.
/**
* Prepare a row for indexing.
*/
public function prepare(array $searchable): array
{
return [
'id' => $searchable['id'],
'title' => $searchable['title'],
'title_sort' => $searchable['title'],
'summary' => $searchable['summary'] ?? '',
'body' => $searchable['body'] ?? '',
'created_at' => $searchable['created_at'],
'permissions' => ProjectPermissions::SUBJECT.'.'.PermissionActions::VIEW,
];
}
/**
* Search index mapping.
*
* Notes:
* - Changes to this require index recreate and index: * `lando artisan district:rebuild-index`
* This is REQUIRED for this map to get applied, otherwise elastic
* will just 'guess' and get it wrong.
* - If you require sorting use `keyword` field. If you require searching
* use `text` field.
*/
public function mappableAs(): array
{
return [
'id' => 'keyword',
'title' => 'text',
'title_sort' => 'keyword',
'summary' => 'text',
'body' => 'text',
'created_at' => 'date',
];
}
Fix elastic perms and rebuild index as per required.
NOTE that any change to the prepare() method require
horizonto restart if indexing is done via queue. This can be done by restarting theworkercontainer on local.
Testing
For unit testing your models use the Modules\SearchApi\Tests\Traits\ModelSearchableTrait.
Raw access to elastic via the CLI (Debugging elastic)
If you want to test elastic directly on production/uat you can use curl. You will first need the index name you want to query. You can get the index for a model via the following:
Run php artisan tinker then run (new Modules\Engage\Models\Project())->searchableAs() it should return something like
district_captivate_deploy_lagoon_staging_scout_projects
Then use that index in the url to query. Eg
curl -u ${ELASTIC_USERNAME}:${ELASTIC_PASSWORD} \
https://${ELASTIC_HOST}:443/district_captivate_deploy_lagoon_staging_scout_projects/_search \
-H "Content-Type: application/json" \
-d '{"query":{"query_string":{"query":"*"}},"size":10,"from":0,"sort":[]}'
Notes on above:
- The url includes the index name
- The host and credentials need to exist in env variables
- The payload (
-d) is searching for anything (*) - To search for a specific keyword replace
*with your keyword, eg"query":"foo" - You can pipe the output into jq for further parsing