Search engines
ScoutEngine runs the text search of a resource on the search engine of its Laravel Scout model. The engine matches the text, applies the filters and the sorts, pages the results and counts them. The package then loads the rows of the page in one SQL query, with the includes, aggregates, selects and gates of the search.
use Lomkit\Rest\Fields\Integer;
use Lomkit\Rest\Fields\Number;
use Lomkit\Rest\Text\Engine\EngineQuery;
use Lomkit\Rest\Text\ScoutEngine;
use Lomkit\Rest\Text\TextSearch;
public function text(): ?TextSearch
{
return ScoutEngine::make()
->filterable([Integer::make('category_id'), Number::make('price'), 'status'])
->sortable(['price'])
->perimeter(fn (EngineQuery $query) => $query->where('team_id', '=', $this->request()->user()->team_id))
->indexAttributes([Integer::make('team_id')]);
}
{
"search": {
"text": {"value": "desk lamp"},
"filters": [{"field": "category_id", "operator": "in", "value": [1, 2]}],
"sorts": [{"field": "price"}],
"includes": [{"relation": "category"}]
}
}
A blank text runs the normal SQL search, with its whole grammar, unless the request asks for an engine list. A text without a letter or a digit matches no row, see Text search.
Declaration
- The model uses
Laravel\Scout\Searchable, and its engine is a Scout engine or a class that extends one:collection,database,meilisearch,typesense,algolia,turbopufferornull. Another engine is refused, because the package cannot know which filters and sorts it runs, unless an extension provides its profile. filterable()lists the index attributes that clients may filter on: fields, such asInteger::make('category_id'), or the names of fields of the resource, such as'status', which take the type and the operators of that field.- An attribute is an
ID,Integer,Number,Boolean,TextorEnumfield, withoutfilterUsing()orsortUsing().Date,DateTime,Jsonand app types that extend a field type are refused: index a date as a timestamp and declare it as anInteger. - Declare an attribute that holds the cases of an enum as an
Enum, such asEnum::make('kind', VoucherKind::class), not as aText: a value outside the enum then getsThe selected search.filters.0.value is invalid.before the engine is called, as anEnumfield does in a SQL search. - A name starts with a letter or
_and holds only letters, digits and_.__soft_deletedis reserved. - A name that points to a field declared
selectable(false)needs that field to be declaredfilterable(). sortable()names thefilterable()attributes that clients may sort on.searchable()does not apply toScoutEngine.- The declaration is checked when the resource is first searched in a request, and by
/details?with=textandrest:check. A missing perimeter, a model withoutSearchable, another engine, a refused type, a refused name, an attribute declared twice or a sort on an attribute that is not filterable throwsInvalidTextSearchException, which names the resource.
The index perimeter
The index perimeter is required: declare perimeter() or withoutPerimeter(), not both.
- The closure of
perimeter()receives theEngineQueryof each search and reads the request with$this->request(). Its conditions narrow every search of the resource, its total and its pages, and clients cannot widen them. search.textmatches the attributes that the index searches (with thedatabaseandcollectionengines, every key oftoSearchableArray()). Index only attributes that every user who can list the resource may read.- Use
withoutPerimeter()only when every such user may see every indexed row. - Extensions can add their own conditions next to the perimeter. They never stand for it:
perimeter()orwithoutPerimeter()stays required.
perimeter(Closure $perimeter, array $attributes = []) is deprecated and will be removed in 4.0. It keeps working in 3.x, without a warning at runtime. Move its attributes to indexAttributes(), which also takes lists of strings. Until then its entries add up with those of indexAttributes(), and a name in both throws.Index attributes
indexAttributes() declares the attributes that only the server compares: the perimeter, the extensions and the instructions that implement AppliesToEngine.
use Lomkit\Rest\Fields\Integer;
use Lomkit\Rest\Text\Engine\EngineQuery;
use Lomkit\Rest\Text\Engine\StringListAttribute;
use Lomkit\Rest\Text\ScoutEngine;
return ScoutEngine::make()
->filterable(['status'])
->perimeter(fn (EngineQuery $query) => $query
->where('team_id', '=', $this->request()->user()->team_id)
->whereIn('readers', $this->request()->user()->readerKeys()))
->indexAttributes([Integer::make('team_id'), StringListAttribute::make('readers')]);
- It takes fields (
ID,Integer,Number,Boolean,TextorEnum, with the rules offilterable()), names of fields of the resource, and lists of strings withStringListAttribute::make('readers'). - Clients never use them: they stay out of the client grammar,
/detailsand the OpenAPI document. A client filter or sort that names one gets the422of an unknown name. - A second call replaces the list, as
filterable()does. A name declared twice, inindexAttributes(), infilterable()or in the second argument ofperimeter(), throwsInvalidTextSearchException. - It works behind
withoutPerimeter(), and does not replace the perimeter. - It does not change
toSearchableArray()or the settings of the index: index each attribute yourself, as a filterable attribute of the engine. The package cannot check that the index holds them.
Lists of strings
A StringListAttribute holds several strings per row, such as the keys of the users and groups that may read it.
whereIn('readers', [...])keeps the rows that share at least one value with the list, andwhereNotIn()the rows that share none.where()is refused on a list.- Two or more
whereIn()lists on one list attribute keep the rows that share at least one value with each list, whichever source sets them: the perimeter, the extensions and the instructions. No list widens another. When one list holds the other, only the narrower one is sent. - On an engine that cannot require two lists, Algolia and a profile that an extension provides, two lists that neither holds throw
Lomkit\Rest\Exceptions\ConflictingListsException. When an instruction sets such a list, the request answers422undersearch.instructions.N:The search.instructions.0 field restricts a list with values that neither hold nor are held by the list that the search already keeps, and the search engine cannot require both lists.On such an engine, an instruction must not take client values for a list that the perimeter or an extension also restricts. - Algolia, Meilisearch, Typesense and Turbopuffer match lists. Comparing a list on the
collection,databaseornulldriver throwsInvalidEngineQueryException: a perimeter or an instruction that compares a list runs only on engines that match lists. - Index the list as a list of strings:
filterOnly(readers)inattributesForFacetingon Algolia,readersinfilterableAttributeson Meilisearch, astring[]field on Typesense, a[]stringattribute on Turbopuffer.
Keep access filters compact: one list attribute matched with one whereIn() sends a shorter filter than many or conditions.
Keeping the index in sync
The rows of a page load by key without perimeterQuery() and without the RestrictsQueries restrictions of the extensions: the engine and its perimeter decide the rows, so pages stay full and total is the engine's. Declare in perimeter(), or in an engine extension, every condition that keeps rows from some users, on attributes that the index holds.
- A row that a stale index still matches is shown until the index is updated. Set
scout.after_committotrue, and leavescout.queueoff for a model whose perimeter or restrictions keep rows from some users, so that a change reaches the index before the next search. - A mass
query()->update(), or a change in another table that an indexed attribute comes from (permissions, membership, a list of readers), never reindexes by itself: callsearchable()on the affected models, or runscout:import. - On the Scout
databaseandcollectiondrivers, the perimeter and the restrictions run on the live table, so a change applies at once. - On a row that the index still matches but a restriction now excludes, the
update,delete,restoreandforceDeletegates answerfalse, and an action skips the row: it answers200and leaves the row out ofimpacted.
Filters and sorts
The grammar of an engine search follows the declaration of the engine:
filterstake thefilterable()attributes. Relation paths and relation groups give a 422: index the related value as a flat attribute and declare it infilterable().=,!=,inandnot inwork on every attribute;>,>=,<and<=onIntegerandNumberattributes, among the operators of the field.inandnot inneed a list of at least one value.nullgives a 422. A number that is not finite gives a 422.- Every engine receives filter values as literals. A string that holds a backtick or a colon followed by
(or[ (, ends with*, is wrapped in double quotes, or is a number written with+givesThe search.filters.0.value field holds a value the search engine cannot compare. sortstake thesortable()attributes.@relevancekeeps the order of the engine: it is accepted alone, with a text, withoutdirectionor withdesc.ascgives a 422 undersearch.sorts.0.direction, and@relevancenext to another sort gives a 422.scopesgives a 422.instructionstakes the instructions that implementAppliesToEngine, see below.trashedneeds a model that usesSoftDeletesandscout.soft_deleteset totrue, otherwise it gives a 422.includes,aggregates,selectsandgatesare validated and applied as in a SQL search, on the rows of the page. Each include and aggregate applies theperimeterQuery()of its own resource.
Groups of filters
On the Typesense, Meilisearch, Turbopuffer, collection, database and null engines, the filters accept "type": "or" and nested groups, as in a SQL search:
{
"search": {
"text": {"value": "desk lamp"},
"filters": [
{"field": "status", "value": "active"},
{"nested": [
{"field": "category_id", "value": 3},
{"field": "price", "operator": "<", "value": 20, "type": "or"}
]}
]
}
}
- The client filters form one block, joined with
andto the perimeter, the extension restrictions, the instructions and the lists of strings. A clientornever widens what they keep out. typejoins a filter to the previous one, andandbinds tighter thanor.- Groups follow the limits of the SQL filters:
rest.limits.depths.filtersfor the depth,sizes.filtersfor each list andtotals.filtersfor the whole search. See Limits. - Algolia and a profile that an extension provides accept no group:
"type": "or"givesThe selected search.filters.1.type is invalid., andnestedgivesThe search.filters.0.nested field is prohibited. /details?with=textadds"groups": trueto theengineblock when the engine accepts them.
The text
text.modeacceptswordsonly. The engine receives the letters and digits of the text, separated by single spaces: the query syntax of the engine has no effect.- A text without a letter or a digit, such as
*, matches no row: the package sends no request to the engine. See Text search. - An engine may relax a text that finds nothing: drop words, accept typos, or read the last word as a prefix. The rows still stay inside the perimeter, the extension restrictions, the instructions and the client filters, which the engine applies as strict filters. To find a row by an exact code, filter on a
filterable()attribute with=.
Engine lists
A resource can let clients list its rows through the engine, without text, with servesLists():
return ScoutEngine::make()
->filterable([Integer::make('category_id'), Number::make('price'), 'status'])
->sortable(['price'])
->perimeter(fn (EngineQuery $query) => $query->where('team_id', '=', $this->request()->user()->team_id))
->indexAttributes([Integer::make('team_id')])
->servesLists()
->tieBreaker('ulid');
{
"search": {
"source": "engine",
"filters": [{"field": "status", "value": "active"}],
"sorts": [{"field": "price"}]
}
}
servesLists() forces nothing: a search without text, or with a blank text, still runs the normal SQL search, with its whole grammar, perimeterQuery() and the extension restrictions, unless its body sends "source": "engine" at the root of search.
sourcetakesengineordatabase.database, the default of a list, names the SQL search of the resource, not the Scoutdatabasedriver. Another value givesThe selected search.source is invalid.- A text with a letter or a digit always runs on the engine:
"source": "engine"is accepted with it, and"source": "database"givesThe search.source field cannot be database with a text: a text search runs on the search engine.A blank text, or a text without a letter or a digit, follows the rules of a search without text. sourceis reserved: on a resource withoutservesLists(), it givesThe search.source field is prohibited.Metric searches and includes refuse it on every resource.- With
"source": "engine"and no text, the engine runs its match-all query with the filters, sorts, page and total of the request, and the rows of the page load by key, as for a text search.perimeterQuery()does not apply to engine lists: put every condition that keeps rows from some users inperimeter()or in an engine extension.rest:checknotes a resource that serves its lists and overridesperimeterQuery(). sourceapplies to HTTP searches, toRest::search()(page(),render()andlazy()) and to the actions whose target is the search, queued or not.
The grammar of an engine list
An engine list takes the grammar of the engine: filters on filterable() attributes, with groups where the engine accepts them, sorts on sortable() attributes, page, limit, trashed, the instructions that implement AppliesToEngine, and includes, aggregates, selects and gates, which run in SQL on the rows of the page.
A scope, a relation path in a filter or a sort, an attribute outside the grammar of the engine, an instruction that does not apply to the engine and @relevance without text give a 422 on their key:
{
"message": "The search.scopes field is refused: a list sent with source engine runs on the search engine, which does not run it.",
"errors": {
"search.scopes": ["The search.scopes field is refused: a list sent with source engine runs on the search engine, which does not run it."]
}
}
A refused engine list never falls back to SQL. To keep one vocabulary for both sources, index the related values that clients filter on as flat attributes, and write the scopes that clients need as instructions that implement AppliesToEngine.
Stable order
An engine list sent without a sort is ordered descending, as a SQL search is: on the tieBreaker() attribute when the resource declares one, otherwise on the scout key when the engine can sort on it, so that pages do not overlap.
- The
collection,databaseandnullengines and Turbopuffer always sort on the key. Meilisearch and Typesense do whensortable()declares it. Algolia keeps the ranking of its index: end itscustomRankingon a unique attribute. - On
collection,databaseandnull, the key also ends the sorts of the client, descending. - An engine list does not apply
defaultOrderBy(), which the engine cannot run.rest:checknotes a resource that overrides it. - A text search keeps the order of the engine.
tieBreaker('ulid') names a unique attribute of the index that the engine sorts. An engine list sent without a sort follows it, descending, and an engine list that the client sorts ends its sorts on it, descending, unless a requested sort already holds it.
- The package cannot check that the attribute is unique: values that two rows share bring the ties back. A string copy of a ULID or UUID v7 key is unique and ordered by time, and
descon it reads the newest rows first, as the default order of a SQL search does. - The attribute needs no
filterable()orsortable()entry, follows the name rules of the index attributes, and the index must sort it. - Typesense takes 3 sorts: the tie-breaker keeps one, so a client sends 2 at most. Meilisearch,
collection,databaseandnulltake any number of sorts and always append it. Turbopuffer takes one sort without text: the tie-breaker orders the lists sent without a sort only. tieBreaker()throwsInvalidTextSearchExceptionon Algolia, which sorts nothing without text, and withoutservesLists(). On Typesense it refusesid, the document id.
Lists in the details
/details?with=text describes the engine lists of a resource that serves them, in the engine block of text:
{"engine": {
"filters": [
{"name": "category_id", "type": "integer", "operators": ["=", "!=", ">", ">=", "<", "<=", "in", "not in"]},
{"name": "price", "type": "number", "operators": ["=", "!=", ">", ">=", "<", "<=", "in", "not in"]}
],
"sorts": ["price"],
"max_sorts": 3, "max_page_size": 250, "window": null,
"lists": true, "max_list_sorts": 2, "tie_breaker": "ulid", "groups": true
}}
liststells that engine lists are available on request. A search without text that sends"source": "engine"follows this block, and one without it follows the field entries of the SQL search.max_list_sortscounts the sorts left to the client in an engine list,nullwhen unbounded.tie_breakernames the attribute oftieBreaker(): name an attribute that every client may see.- The block of a resource that does not serve its lists has none of these keys. See Details.
Pages and totals
- The engine pages the results with
limitandpage.totalandlast_pageare the engine's, and the rows keep the order of the engine. - The rows of the page load in one SQL query, by their scout key (
getScoutKeyName()), with the global scopes and the soft deletes of the model. - Every page of an engine search, with or without text, adds
droppedaftertotal: the rows that the engine returned for the page and that the SQL read left out, such as a row deleted since indexing, or a row that a global scope orsearch.trashedleaves out. They are missing fromdataand still counted intotal. It is0in the normal case. TheRestrictsQueriesrestrictions do not apply to this read, so they never count indropped: the engine applies them throughRestrictsEngineQueries. A SQL page has nodropped. total_cappedshows when the engine caps its total: every Turbopuffer page has it,truewhen the total reaches 10,000, the most that Scout counts, andfalsebelow. Typesense, Meilisearch and Algolia leave it out.$maxTotaldoes not apply to engine pages.- Keys follow
getScoutKeyType():intorintegergives integer keys, any other type string keys. A model whose scout key is not its primary key declaresgetScoutKeyType(). - The package builds the Scout query itself: an override of the model's
search(),getScoutModelsByIds()orqueryScoutModelsByIds()is not used.Resource::paginate()serves the SQL searches only. - An engine search can return the totals of the rows that it matches, with
groupable()andmeasurable()on theScoutEngine.
Engines
| Engine | Notes |
|---|---|
collection, database | Every operator and sort, exact totals. On PostgreSQL, Scout's database engine compares every key of toSearchableArray() with ilike: return text columns only there. The collection engine loads every matching row to page them: keep it for tests and small tables |
meilisearch | Exact totals: totalHits stays exact beyond the pagination.maxTotalHits of the index, and only the pages past that setting come back empty. Declare the filterable() and indexAttributes() attributes in filterableAttributes, and the sortable() ones and the tie-breaker in sortableAttributes |
typesense | Exact totals. The model needs query_by in scout.typesense.model-settings.<model class>.search-parameters, or in typesenseSearchParameters(). A page holds at most 250 rows, and a search takes at most 3 sorts. See Typesense |
algolia | Exact totals, no sorts: sortable() and tieBreaker() throw, and @relevance alone is accepted. No groups of filters. See Algolia |
turbopuffer | No sorts next to a text; an engine list takes one sort. A page must end within the first 10,000 results. total counts the documents that match the filters, not the text |
null | An empty page and a total of 0, without SQL query |
Meilisearch and Typesense compare filter strings without regard to case: prefer Integer, ID, Boolean or Enum index attributes. On Meilisearch, Typesense, Algolia and Turbopuffer, a row that a global scope of the model leaves out can be in the index: keep it out with shouldBeSearchable(), or add the condition to the perimeter.
Curated and promoted hits
The pages trust the engine, so every hit that it returns must match the filter that the package sends. The package keeps the hits that an engine adds itself inside that filter:
- On Typesense, every search sends
filter_curated_hits: true: pinned hits and the hits that a curation adds follow the perimeter, the extension restrictions, the instructions and the client filters. The request parameter wins over a curation rule or a preset that setsfilter_curated_hits: false. - On Algolia, every search sends
enableRules: false, since a rule that promotes objects returns them without the filters by default. This turns off every consequence of the rules. Express visibility as an indexed attribute filtered inperimeter()orfilterable(), and ranking through the index settings. - The options that would let hits escape the filter are owned by the package:
EngineQuery::options()refuses them withInvalidEngineQueryException.
Typesense
typesenseSearchParameters()must not return a parameter that the package sends itself:q,filter_by,sort_by,per_page,pageorgroup_by, norfilter_curated_hitsornl_query. The first search of such a resource throwsInvalidTextSearchException, which names the model, the resource and the parameter, andrest:checkreports it underrows. Declare the filters infilterable()orperimeter().sortable()andtieBreaker()refuseid, the document id, which Typesense does not sort. Index a copy of the key under another name withsort: true, and declare that copy.filter_curated_hitsexists since Typesense 0.24.pinned_hitsandhidden_hitsstay available, unless theScoutEnginedeclares totals, which owns them: only pin rows that the filter keeps. A preset must not turn onnl_query, whose generated filter the package cannot check.- A search whose query string would pass 3,500 characters runs through the
/multi_searchendpoint, with the same parameters, since Typesense refuses a longer GET. The switch is automatic. A search-only key (documents:search) may call it. /multi_searchreports an error inside a200answer: the package throwsLomkit\Rest\Exceptions\EngineSearchException, which names the collection, the error and its code, and keeps the Typesense exception of that code as its previous exception. Above the threshold, a missing collection throws (code 404) instead of answering an empty page.- A subclass of Scout's
TypesenseEnginethat overridesexecuteSearch()orperformSearch()keeps its override under the threshold only.
Algolia
enableRulesandparamsare owned by the package:EngineQuery::options()refuses them.- Algolia sorts nothing next to a text or in a list:
sortable()andtieBreaker()throw. An engine list follows the ranking of the index. - Algolia accepts no groups of filters, and two lists of strings that neither holds throw.
Engine queries
The perimeter and the instructions receive an EngineQuery:
where($attribute, $operator, $value)takes=,!=,<,>,<=or>=.whereIn($attribute, $values)andwhereNotIn($attribute, $values)take a list.- The attribute must be declared in
filterable(),indexAttributes()or the perimeter, or by an extension, with this operator. The value is converted to the type of the attribute, a backed enum to its value. Anything else throwsInvalidEngineQueryException, aLogicException, except a value that an instruction passes, which answers422, see Instructions. - The conditions add up and never replace each other. On a single-value attribute, two
whereIn()lists keep the values that both hold, andwhereNotIn()lists add up. On a list of strings, see Lists of strings. An emptywhereIn()returns an empty page without calling the engine. whereAny()groups conditions joined withor. The closure receives aLomkit\Rest\Text\Engine\EngineConditionGroup, which offerswhere(),whereIn(),whereNotIn(),whereAll()for a group joined withand, andwhereAny():
use Lomkit\Rest\Text\Engine\EngineConditionGroup;
$query->whereAny(fn (EngineConditionGroup $group) => $group
->where('status', '=', 'open')
->whereIn('assignee_id', $ids));
- The group is one condition, joined with
andto the perimeter, the extension restrictions, the other conditions and the client filters: it never widens past them. A group without any condition matches nothing. - A true member makes the whole group true:
whereNotIn()with an empty list is true, so insidewhereAny()an empty list sent by a client removes the condition. Refuse or replace an empty list before grouping it. filtersWithGroups()tells whether the engine accepts groups. On Algolia and on a profile that an extension provides,whereAny()throwsInvalidEngineQueryException, which names the instruction, the resource and the engine.orderBy($attribute, $direction)sorts on asortable()attribute.options([...])adds options for the engine. An option set again with another value throws, and so do the options that the package owns.
Instructions
An instruction runs next to an engine text, or in an engine list, when it implements AppliesToEngine:
use Illuminate\Database\Eloquent\Builder;
use Lomkit\Rest\Fields\Number;
use Lomkit\Rest\Instructions\AppliesToEngine;
use Lomkit\Rest\Instructions\Instruction;
use Lomkit\Rest\Instructions\InstructionFields;
use Lomkit\Rest\Text\Engine\EngineQuery;
class PricedUpTo extends Instruction implements AppliesToEngine
{
public function fields(): array
{
return [Number::make('max')->rules('required')];
}
public function handle(InstructionFields $fields, Builder $query): void
{
$query->where('price', '<=', $fields->max);
}
public function handleEngine(InstructionFields $fields, EngineQuery $query): void
{
$query->where('price', '<=', $fields->max);
}
}
- Another instruction gives a 422 in an engine search.
- An
AppliesToEngineinstruction that does not overridehandle()only applies to engine searches: it gives a 422 in a search that runs in SQL, such as a search without text sent without"source": "engine", an include or the search of aContainsresource. - A value that
handleEngine()passes towhere(),whereIn()orwhereNotIn()and that the engine query refuses answers422under the key of the instruction: a value that the attribute cannot take givesThe search.instructions.0 field holds a value the search engine cannot compare., and a value that the engine cannot match as it is, such as a number written with+, givesThe search.instructions.0 field holds characters the search engine cannot match as they are.Rest::search()throws aValidationExceptionwith the same key. The same value inperimeter()still throwsInvalidEngineQueryException. Normalise the values that clients type in the instruction. - In the details, each instruction says under
textwhether it applies to a search with text on this resource.
Actions
An action whose search runs on the engine, with a filled text or with "source": "engine", reads every key from the engine first, in pages of chunkCount, then loads each chunk in SQL by key, before it runs, is queued or starts a batch.
- These keys are read through the
RestrictsQueriesrestrictions of the extensions, never throughperimeterQuery(): a row that the index still matches but a restriction now excludes is not handed to the action. - A search that matches more than
maxResourcesresources givesThis action can be run on at most 1000 resources; narrow the search.undersearch. Withsearch.limit, the action acts on the firstlimitresults. - Without
search.limit, the action readspagination.maxTotalHitson Meilisearch orpaginationLimitedToon Algolia: the application key must be allowed to read the settings of the index. Set these limits above themaxResourcesof the actions. - When the results change while the action reads them, it gives
The search results changed while the action was resolving them; run the action again.
See Actions.
Text search
Declare the text search of a resource with LIKE or the full-text index of the database, pick a mode per request and sort by relevance.
Searching outside HTTP
Replay a client search payload from a job, a command or an export with Rest::search(), with the validation, perimeter and policies of the endpoint.