Search

Search engines

Run the text search and, on request, the lists of a resource on Meilisearch, Typesense, Algolia or another Laravel Scout engine.

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.

app/Rest/Resources/ProductResource.php
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')]);
}
POST /api/products/search
{
  "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, turbopuffer or null. 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 as Integer::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, Text or Enum field, without filterUsing() or sortUsing(). Date, DateTime, Json and app types that extend a field type are refused: index a date as a timestamp and declare it as an Integer.
  • Declare an attribute that holds the cases of an enum as an Enum, such as Enum::make('kind', VoucherKind::class), not as a Text: a value outside the enum then gets The selected search.filters.0.value is invalid. before the engine is called, as an Enum field does in a SQL search.
  • A name starts with a letter or _ and holds only letters, digits and _. __soft_deleted is reserved.
  • A name that points to a field declared selectable(false) needs that field to be declared filterable().
  • sortable() names the filterable() attributes that clients may sort on.
  • searchable() does not apply to ScoutEngine.
  • The declaration is checked when the resource is first searched in a request, and by /details?with=text and rest:check. A missing perimeter, a model without Searchable, another engine, a refused type, a refused name, an attribute declared twice or a sort on an attribute that is not filterable throws InvalidTextSearchException, which names the resource.

The index perimeter

The index perimeter is required: declare perimeter() or withoutPerimeter(), not both.

  • The closure of perimeter() receives the EngineQuery of 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.text matches the attributes that the index searches (with the database and collection engines, every key of toSearchableArray()). 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() or withoutPerimeter() stays required.
The second argument of 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, Text or Enum, with the rules of filterable()), names of fields of the resource, and lists of strings with StringListAttribute::make('readers').
  • Clients never use them: they stay out of the client grammar, /details and the OpenAPI document. A client filter or sort that names one gets the 422 of an unknown name.
  • A second call replaces the list, as filterable() does. A name declared twice, in indexAttributes(), in filterable() or in the second argument of perimeter(), throws InvalidTextSearchException.
  • 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, and whereNotIn() 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 answers 422 under search.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, database or null driver throws InvalidEngineQueryException: 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) in attributesForFaceting on Algolia, readers in filterableAttributes on Meilisearch, a string[] field on Typesense, a []string attribute 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_commit to true, and leave scout.queue off 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: call searchable() on the affected models, or run scout:import.
  • On the Scout database and collection drivers, 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, restore and forceDelete gates answer false, and an action skips the row: it answers 200 and leaves the row out of impacted.

Filters and sorts

The grammar of an engine search follows the declaration of the engine:

  • filters take the filterable() attributes. Relation paths and relation groups give a 422: index the related value as a flat attribute and declare it in filterable().
  • =, !=, in and not in work on every attribute; >, >=, < and <= on Integer and Number attributes, among the operators of the field.
  • in and not in need a list of at least one value. null gives 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 + gives The search.filters.0.value field holds a value the search engine cannot compare.
  • sorts take the sortable() attributes. @relevance keeps the order of the engine: it is accepted alone, with a text, without direction or with desc. asc gives a 422 under search.sorts.0.direction, and @relevance next to another sort gives a 422.
  • scopes gives a 422. instructions takes the instructions that implement AppliesToEngine, see below.
  • trashed needs a model that uses SoftDeletes and scout.soft_delete set to true, otherwise it gives a 422.
  • includes, aggregates, selects and gates are validated and applied as in a SQL search, on the rows of the page. Each include and aggregate applies the perimeterQuery() 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:

POST /api/products/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 and to the perimeter, the extension restrictions, the instructions and the lists of strings. A client or never widens what they keep out.
  • type joins a filter to the previous one, and and binds tighter than or.
  • Groups follow the limits of the SQL filters: rest.limits.depths.filters for the depth, sizes.filters for each list and totals.filters for the whole search. See Limits.
  • Algolia and a profile that an extension provides accept no group: "type": "or" gives The selected search.filters.1.type is invalid., and nested gives The search.filters.0.nested field is prohibited.
  • /details?with=text adds "groups": true to the engine block when the engine accepts them.

The text

  • text.mode accepts words only. 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():

app/Rest/Resources/ProductResource.php
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');
POST /api/products/search
{
  "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.

  • source takes engine or database. database, the default of a list, names the SQL search of the resource, not the Scout database driver. Another value gives The 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" gives The 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.
  • source is reserved: on a resource without servesLists(), it gives The 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 in perimeter() or in an engine extension. rest:check notes a resource that serves its lists and overrides perimeterQuery().
  • source applies to HTTP searches, to Rest::search() (page(), render() and lazy()) 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:

422 Unprocessable Content
{
  "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, database and null engines and Turbopuffer always sort on the key. Meilisearch and Typesense do when sortable() declares it. Algolia keeps the ranking of its index: end its customRanking on a unique attribute.
  • On collection, database and null, the key also ends the sorts of the client, descending.
  • An engine list does not apply defaultOrderBy(), which the engine cannot run. rest:check notes 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 desc on it reads the newest rows first, as the default order of a SQL search does.
  • The attribute needs no filterable() or sortable() 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, database and null take 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() throws InvalidTextSearchException on Algolia, which sorts nothing without text, and without servesLists(). On Typesense it refuses id, 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
}}
  • lists tells 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_sorts counts the sorts left to the client in an engine list, null when unbounded.
  • tie_breaker names the attribute of tieBreaker(): 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 limit and page. total and last_page are 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 dropped after total: 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 or search.trashed leaves out. They are missing from data and still counted in total. It is 0 in the normal case. The RestrictsQueries restrictions do not apply to this read, so they never count in dropped: the engine applies them through RestrictsEngineQueries. A SQL page has no dropped.
  • total_capped shows when the engine caps its total: every Turbopuffer page has it, true when the total reaches 10,000, the most that Scout counts, and false below. Typesense, Meilisearch and Algolia leave it out. $maxTotal does not apply to engine pages.
  • Keys follow getScoutKeyType(): int or integer gives integer keys, any other type string keys. A model whose scout key is not its primary key declares getScoutKeyType().
  • The package builds the Scout query itself: an override of the model's search(), getScoutModelsByIds() or queryScoutModelsByIds() 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() and measurable() on the ScoutEngine.

Engines

EngineNotes
collection, databaseEvery 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
meilisearchExact 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
typesenseExact 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
algoliaExact totals, no sorts: sortable() and tieBreaker() throw, and @relevance alone is accepted. No groups of filters. See Algolia
turbopufferNo 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
nullAn 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 sets filter_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 in perimeter() or filterable(), and ranking through the index settings.
  • The options that would let hits escape the filter are owned by the package: EngineQuery::options() refuses them with InvalidEngineQueryException.

Typesense

  • typesenseSearchParameters() must not return a parameter that the package sends itself: q, filter_by, sort_by, per_page, page or group_by, nor filter_curated_hits or nl_query. The first search of such a resource throws InvalidTextSearchException, which names the model, the resource and the parameter, and rest:check reports it under rows. Declare the filters in filterable() or perimeter().
  • sortable() and tieBreaker() refuse id, the document id, which Typesense does not sort. Index a copy of the key under another name with sort: true, and declare that copy.
  • filter_curated_hits exists since Typesense 0.24. pinned_hits and hidden_hits stay available, unless the ScoutEngine declares totals, which owns them: only pin rows that the filter keeps. A preset must not turn on nl_query, whose generated filter the package cannot check.
  • A search whose query string would pass 3,500 characters runs through the /multi_search endpoint, with the same parameters, since Typesense refuses a longer GET. The switch is automatic. A search-only key (documents:search) may call it.
  • /multi_search reports an error inside a 200 answer: the package throws Lomkit\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 TypesenseEngine that overrides executeSearch() or performSearch() keeps its override under the threshold only.

Algolia

  • enableRules and params are owned by the package: EngineQuery::options() refuses them.
  • Algolia sorts nothing next to a text or in a list: sortable() and tieBreaker() 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) and whereNotIn($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 throws InvalidEngineQueryException, a LogicException, except a value that an instruction passes, which answers 422, 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, and whereNotIn() lists add up. On a list of strings, see Lists of strings. An empty whereIn() returns an empty page without calling the engine.
  • whereAny() groups conditions joined with or. The closure receives a Lomkit\Rest\Text\Engine\EngineConditionGroup, which offers where(), whereIn(), whereNotIn(), whereAll() for a group joined with and, and whereAny():
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 and to 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 inside whereAny() 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() throws InvalidEngineQueryException, which names the instruction, the resource and the engine.
  • orderBy($attribute, $direction) sorts on a sortable() 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 AppliesToEngine instruction that does not override handle() 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 a Contains resource.
  • A value that handleEngine() passes to where(), whereIn() or whereNotIn() and that the engine query refuses answers 422 under the key of the instruction: a value that the attribute cannot take gives The 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 +, gives The search.instructions.0 field holds characters the search engine cannot match as they are. Rest::search() throws a ValidationException with the same key. The same value in perimeter() still throws InvalidEngineQueryException. Normalise the values that clients type in the instruction.
  • In the details, each instruction says under text whether 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 RestrictsQueries restrictions of the extensions, never through perimeterQuery(): a row that the index still matches but a restriction now excludes is not handed to the action.
  • A search that matches more than maxResources resources gives This action can be run on at most 1000 resources; narrow the search. under search. With search.limit, the action acts on the first limit results.
  • Without search.limit, the action reads pagination.maxTotalHits on Meilisearch or paginationLimitedTo on Algolia: the application key must be allowed to read the settings of the index. Set these limits above the maxResources of 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.