Keep Craft content in a Typesense search index, and give search pages a safe, filtered search key, by declaring what to index instead of writing a module.
- The index follows the content. Saving, disabling, deleting or restoring an element queues a sync. So do a user's status and group changes. Nothing is indexed unless you declare it.
- Schema changes without downtime. The utility shows how each collection differs from what your formatters declare. It applies the difference in place, or rebuilds the collection beside the live one and switches search over when the rebuild is complete, joined collections included.
- Keys that can only read what the page may show.
craft.typesense.searchConfig()hands a search page a short-lived key. The key only searches, never returns pending or expired entries, and never returns the fields you mark private. The admin key never reaches a template. - Built in, off until you declare it: users, categories, Craft Commerce products, search analytics (popular searches, searches with no results, view counters that survive reindexing), and collections that join to one another.
- Rules and synonyms editors can manage. A Typesense section in the control panel lets editors pin and hide entries for a search, schedule those rules, and say which words mean the same thing. Craft keeps the record, so rules survive a rebuild and move between environments.
- See what visitors search for. The Insights tab shows the popular searches and the searches that found nothing over the last 7, 30 or 90 days, with the change on the period before. A search that found nothing becomes a synonym or a rule in two clicks. Stopwords lets editors keep sets of words search ignores and pick one per collection, and presets keep a collection's search settings in config instead of the page's JavaScript.
The plugin owns the machinery: queueing, batching, safe rebuilds and keys. Your site owns the meaning: which content goes where, and what a result looks like.
- Requirements
- Installation
- Getting started
- How the index follows content
- Configuration reference
- Writing a formatter
- Search pages
- Joined collections
- Analytics
- Rules and synonyms
- Stopwords
- Search insights
- Control panel
- Console commands
- Extension points
- Several environments, one cluster
- Troubleshooting
- Uninstalling
- Craft CMS 5.6 or later
- PHP 8.2 or later
- A Typesense server, version 30.0 or later, self-hosted or Typesense Cloud
- Craft Commerce 5, only to index products
From the Plugin Store: search for "Typesense Sync" and install it.
With Composer:
composer require webdna/typesense-sync
php craft plugin/install typesense-syncGo to Settings → Plugins → Typesense Sync and enter the server details. Every field accepts an
environment variable, and the settings are saved to project config as the $VARIABLE reference,
never as the value.
TYPESENSE_HOST="xyz.a1.typesense.net"
TYPESENSE_PORT="443"
TYPESENSE_PROTOCOL="https"
TYPESENSE_API_KEY="…" # admin key: stays on the server
TYPESENSE_SEARCH_API_KEY="…" # search-only key: signs the keys pages receive
TYPESENSE_PREFIX="prod_" # optional: one cluster, several environmentsPress Test connection. It reports the server version and checks the search-only key on the
server. A key that allows anything beyond documents:search is refused, because pages receive keys
derived from it. To make a search-only key:
curl "https://$TYPESENSE_HOST/keys" -X POST \
-H "X-TYPESENSE-API-KEY: $TYPESENSE_API_KEY" -H "Content-Type: application/json" \
-d '{"description": "Search only", "actions": ["documents:search"], "collections": ["*"]}'The server returns the key's value once. Copy it straight into .env.
Collections, sources and analytics are declared in config/typesense-sync.php, because they name
PHP classes. Copy the base example to start:
cp vendor/webdna/typesense-sync/examples/config/typesense-sync.php config/
mkdir -p modules/search/formatters
cp vendor/webdna/typesense-sync/examples/formatters/ContentFormatter.php modules/search/formatters/Change the section handle news to one of yours. The example formatter uses the namespace
modules\search\formatters, which Craft's default modules\ autoload already covers. The
examples README lists every example config, formatter and search component.
<?php
use modules\search\formatters\ContentFormatter;
return [
'collections' => [
'content' => [
'defaultSortingField' => 'priority',
],
],
'sources' => [
[
'kind' => 'section',
'handle' => 'news',
'collection' => 'content',
'formatter' => ContentFormatter::class,
],
],
];php craft typesense-sync/setupsetup validates the config, tests the connection, creates each collection and its alias, applies
any analytics rules, and indexes every declared element. It is safe to run again. Run it on each
environment after deploying a config change, or run collections/apply and sync yourself.
Nothing happens on craft up: the plugin never writes to Typesense from a migration, because up
also runs on every developer's machine and in CI, which may share a cluster. Add one line to your
deploy script, after craft up:
php craft up
php craft typesense-sync/collections/applycollections/apply first creates the shipped common_en stopword set if the server
has none of that name, then creates or alters each collection in place and pushes its rule and
synonym sets, its presets and the analytics rules (declared and insights). It changes only what
differs, so a deploy with no config change sends nothing. It never reindexes; it says when a
sync is needed. If Typesense cannot be reached, or a collection picks a stopword set the server
no longer has, it exits 1, so your deploy script decides whether that fails the deploy: leave it
to fail, or append || true to let the deploy go on and apply later.
If an insights rule goes missing anyway (deleted in the Typesense dashboard, say), the daily
insights/update creates it again before it reads the counts. It never changes a rule that exists.
{% set search = craft.typesense.searchConfig('content') %}
{% if search %}
<div data-search="{{ search|json_encode|e('html_attr') }}"></div>
{% else %}
<p>Search is unavailable.</p>
{% endif %}examples/alpine/ has a search box that uses this config.
| Change | What happens |
|---|---|
| An element of a declared source is saved, restored or deleted | A sync or delete job is queued. The save itself makes no network call. |
| A user is activated, deactivated, suspended, unsuspended, locked, unlocked or assigned to groups | A sync is queued, although no save event fires. This only happens while a users source is declared. |
| The same element is saved again while its job is waiting | Nothing more is queued. A save during a running job queues a fresh one. |
| A draft, a revision, a bulk resave, a propagation, or a nested entry with no section is saved | Nothing is queued. Use a reindex after a bulk resave. |
| An element of an undeclared section, group or type is saved | Nothing is queued, and nothing is sent. |
A sync job loads the element again and asks its formatter. A missing element, a disabled element, or
a formatter's shouldIndex() returning false removes the document. Craft's queue makes up to three
attempts at a job that cannot reach the server. A document Typesense rejects is logged and not
retried. A save never fails because of Typesense.
Pending and expired entries stay in the index with their postDate and expiryDate, and every
search key filters them out. No cron is needed for an entry to appear or expire on time.
Two things are not followed automatically:
- Anything your documents read from other elements. If a document shows its author's name, the
entry is not re-synced when the author is saved. Call
queueElement()from a listener of your own. - An entry moved into an undeclared section or entry type. Its document stays until a reindex with prune.
Craft silently ignores an unknown key in a plugin's config file. This plugin reports every key
it does not recognise, at every level, in the utility and in setup. So a typo is caught rather
than quietly doing nothing. The keys below are the complete list.
Values marked env accept an environment variable ('$TYPESENSE_PREFIX') or are resolved with
App::env().
The connection keys are normally set in the control panel. Any of them set here overrides the control panel value.
| Key | Default | |
|---|---|---|
host |
'' |
env. Hostname, without the protocol. |
port |
'443' |
env. |
protocol |
'https' |
env. http or https. |
apiKey |
'' |
env. Admin key. Never passed to Twig, and shown in the control panel only as its last four characters. |
searchApiKey |
'' |
env. Search-only key. Signs every scoped key. |
collectionPrefix |
'' |
env. Prepended to each collection handle to make its live name. |
connectTimeout |
2 |
Seconds allowed to connect. |
timeout |
5 |
Seconds allowed for each request. |
numRetries |
3 |
Retries per request. |
queuePriority |
1024 |
Priority of the plugin's queue jobs. Lower runs sooner. |
batchSize |
100 |
Elements per import during a reindex. |
collections |
[] |
File only. Collections, keyed by handle. |
sources |
[] |
File only. A list of sources. |
analytics |
[] |
File only. See Analytics. |
| Key | Default | |
|---|---|---|
name |
prefix + handle | env. An explicit live name, e.g. to keep names a cluster already uses. |
typeField |
'type' |
The field BaseFormatter writes the document type into. Name another when this collection's documents use type for something of their own. Changing it later needs a recreate and a reindex. |
defaultSortingField |
none | Changing it later needs a recreate. |
enableNestedFields |
true |
Changing it later needs a recreate. |
schema |
[] |
Typesense field definitions added to whatever the formatters declare, e.g. a field another process writes. |
counters |
[] |
Field names whose values are read from the live collection and kept through every reindex. |
presets |
[] |
Named search settings, handle => Typesense search parameters, e.g. ['default' => ['query_by' => 'title,body', 'query_by_weights' => '3,1', 'per_page' => 12]]. Each is pushed as <live name>_<handle> by collections/apply and setup. A preset may not set collection, q, filter_by, exclude_fields, expires_at, stopwords, preset or searches, and each value is a single value. |
insights |
false |
Declares the two analytics rules behind search insights, insights_popular and insights_nohits, each with its own destination and keeping analytics.insightsLimit searches. Applied, reported and removed like declared rules; needs analytics.enabled. Switched back off, analytics/apply deletes the two rules and keeps their destinations. |
search |
What every scoped key for this collection is limited to: | |
search.publicationWindow |
true |
Only documents with postDate <= now and expiryDate > now. |
search.excludeFields |
[] |
Fields a search with this collection's keys never returns, whatever the browser asks. |
search.preset |
none | The preset every key for this collection names. A parameter the page sends itself, such as per_page, still overrides the preset's value; the page cannot name another preset. |
A collection's live name is always an alias. The physical collection behind it is
<name>_1, <name>_2 and so on, which is how a rebuild happens beside the live version.
| Key | Default | |
|---|---|---|
kind |
'section' |
section, categoryGroup, users or productType. |
handle |
The section, category group or product type handle. Not used for users. |
|
collection |
The collection handle it feeds. | |
formatter |
A class implementing FormatterInterface, usually extending BaseFormatter. |
|
enabled |
true |
Switches the whole source. It accepts any PHP expression, e.g. App::env('SEARCH_NEWS') ?? true. |
priority |
100 |
Written to each document's priority. Lower sorts first. |
site |
primary site | The site handle whose version of each element is indexed. |
entryTypes |
[] |
Sections only: overrides keyed by entry type handle. |
An entryTypes.<handle> override takes enabled, collection, formatter and priority. An
override can switch one entry type off, or route it to another collection or formatter. It cannot
switch a type on inside a disabled source.
A productType source is ignored with a warning, not an error, when Commerce is not installed.
The utility and setup list these as problems, and setup exits non-zero:
- an unknown key, anywhere
- a source naming an undeclared collection
- a formatter class that is missing or does not implement
FormatterInterface - two formatters in one collection declaring the same field differently
- a
typeFieldthat is not a field name, or names another field every document carries (id,title,url,priority,postDate,expiryDate,keywords) - two collections resolving to the same live name
- a reference field naming an undeclared collection, or references forming a cycle
- an analytics rule with an unknown type or an undeclared collection, or an events key equal to the admin key
A formatter turns one element into one document and declares the fields its documents carry. Extend
BaseFormatter and implement fields(). Declare any extra fields by adding them to
parent::schema().
<?php
namespace modules\search\formatters;
use craft\base\ElementInterface;
use craft\elements\Entry;
use webdna\typesensesync\formatters\BaseFormatter;
use webdna\typesensesync\formatters\SchemaContext;
class ContentFormatter extends BaseFormatter
{
public function schema(SchemaContext $context): array
{
return [
...parent::schema($context),
['name' => 'summary', 'type' => 'string', 'optional' => true],
self::facet('section'),
];
}
protected function fields(ElementInterface $element): array
{
return [
'summary' => $this->plainText($element, 'summary', 300),
'section' => $element instanceof Entry ? $element->getSection()?->name : null,
];
}
}Every document carries id, title, type (the entry type, product type or element type's
name), url (root-relative), priority, postDate and expiryDate (Unix seconds; "never" is
BaseFormatter::FAR_FUTURE, 253402300799), and keywords.
The type is written into the field the collection's typeField names, type unless it names
another. A collection whose documents need type for their own field — a list of a member's kinds,
say — moves the document type out of the way rather than overwriting it:
'collections' => [
'people' => ['typeField' => 'kind'],
],BaseFormatter::schema() and format() both follow it, so a formatter declares and returns its own
type as usual. Read the name in schema() with $context->getTypeField(). To change the type's
value rather than its field, override documentType().
- Make your own fields
optional. Several formatters can write into one collection, and no single document carries every field. - Null,
''and[]are dropped before indexing, so return values unconditionally. Typesense rejects null for a typed field. - Keep URLs root-relative.
url()already does. One cluster often serves several environments. shouldIndex()decides whether the element has a document at all. By default that is enabled and enabled for the site. Override it to exclude more; the exampleUserFormatterexcludes inactive users.documentId()defaults to the element id. Override it only with a value that never changes for the element, because deletes are addressed by it.
Helpers on BaseFormatter, all safe on a field missing from the element's layout: fieldValue(),
plainText(), firstPlainText(), optionValue(), optionLabel(), optionLabels(),
relatedTitles(), assetUrls(), firstAssetUrl(), number(), integer(), boolean(),
timestamp(), url(), and facet() for a schema entry.
If you do not extend BaseFormatter, implement FormatterInterface:
shouldIndex(ElementInterface): bool, format(ElementInterface): array and
schema(SchemaContext): array. Your documents then need their own postDate and expiryDate, or
set search.publicationWindow to false for that collection.
craft.typesense in Twig, TypesenseSync::getInstance()->search in PHP:
| Method | Returns |
|---|---|
searchConfig(handle, params) |
{host, port, protocol, collection, apiKey, expiresAt} |
scopedKey(handle, params) |
The scoped key alone |
collectionName(handle) |
The live alias name |
analyticsConfig() |
What a page needs to post analytics events; see Analytics |
viewCounts(ruleHandle, ids) |
View counts by document id |
Each one returns null rather than throwing when the plugin is unconfigured, the collection is
undeclared, or a key cannot be made. A page built before setup renders its own "unavailable" state.
params for a key:
| Param | |
|---|---|
filter |
A Typesense filter, ANDed with the collection's own. |
ttl |
Seconds the key lives. Default 3600. |
excludeFields |
Fields to exclude on top of the collection's search.excludeFields. |
preset |
Another preset the collection declares, instead of its search.preset; '' for none. An undeclared one gives null. |
| any other | Embedded as a Typesense search parameter, e.g. limit_hits. |
A scoped key embeds filter_by, exclude_fields, preset, expires_at and, when the collection
picks a stopword set, stopwords, and the browser cannot override any of them. Each filter clause is parenthesised, so an || in one clause cannot widen another. The
key is signed with the search-only key, never the admin key.
- A key's embedded parameters are readable. Anyone can base64-decode them, so never put a secret in a filter.
- A key is not limited to one collection. Its filter is its isolation.
- Page caches must not outlive the key. A static or edge cache that keeps a page for longer than
ttlserves an expired key, and search fails for anonymous visitors. UseexpiresAtto set the cache lifetime, or fetch the config from an uncached endpoint.
A preset names a collection's search settings once, in config, so the page's JavaScript does not repeat them:
'content' => [
// …
'presets' => [
'default' => ['query_by' => 'title,summary,body', 'query_by_weights' => '4,2,1', 'per_page' => 12],
'compact' => ['query_by' => 'title', 'per_page' => 5],
],
'search' => ['preset' => 'default'],
],collections/apply and setup push each preset as <live name>_<handle>, and change only one that
differs. Every key for the collection names its search.preset, and
craft.typesense.searchConfig('content', {preset: 'compact'}) names another declared one. A
parameter the page sends itself, such as per_page or sort_by, still overrides the preset's
value, which is Typesense's own order. The page cannot name a different preset, or switch the
preset off.
Override query_by and query_by_weights together, or neither. A page that sends its own
query_by keeps the preset's weights, and Typesense refuses every search whose number of weights
differs from the number of fields. With a preset, let the page leave out what the preset sets.
examples/alpine/search.js sends query_by and per_page only when given its queryBy and
perPage options, so with a preset write typesenseSearch().
A preset may not set collection, q, filter_by, exclude_fields, expires_at, stopwords,
preset or searches: the plugin or the request owns those. A preset that breaks this is reported
as a problem and never pushed, and a key naming it is not made. collections/status and the utility
show each preset as in step, different or missing, and list any preset under the collection's name
that config does not declare. The plugin never deletes a preset.
Presets are config, never the control panel: a wrong setting breaks every search, which is a developer's change to make and test.
A formatter declares a reference into another collection through the SchemaContext it is given:
['name' => 'authorId', 'type' => 'string', 'reference' => $context->reference('people'),
'optional' => true, 'async_reference' => true, 'cascade_delete' => false],A search can then include the referenced document's fields (include_fields: '$people(title)').
Consider Typesense's defaults before you keep them: without async_reference a document is rejected
while the one it references is not yet indexed, and cascade_delete deletes the referencing
documents with it.
Typesense binds a reference to the physical collection, and a joined search names the alias.
So rebuilding a referenced collection alone breaks every join into it. Recreate therefore rebuilds
the collection and everything that references it, directly or not, in dependency order. It swaps
all the aliases only once every build has succeeded. Declare referenced collections before the ones
that reference them, so that setup creates them first. examples/config/joins.php is a complete
example.
The server must have analytics switched on. A self-hosted server is started with
--enable-search-analytics=true --analytics-dir=…. On Typesense Cloud it is a cluster setting.
'analytics' => [
'eventsKey' => '$TYPESENSE_EVENTS_KEY',
'rules' => [
'popular' => ['type' => 'popular_queries', 'collection' => 'content'],
'noResults' => ['type' => 'nohits_queries', 'collection' => 'content'],
'views' => ['type' => 'counter', 'collection' => 'content', 'counterField' => 'popularity'],
],
],php craft typesense-sync/analytics/create-events-key # once: prints the value to put in .env
php craft typesense-sync/analytics/apply
php craft typesense-sync/analytics/report --limit=20analytics key |
Default | |
|---|---|---|
enabled |
true |
Switches analytics off on an environment without touching the rules. |
eventsKey |
'' |
env. An events-only key, needed by counter rules. Must not be the admin key. |
ignoreQueries |
['*', ''] |
Queries never recorded. |
insightsLimit |
1000 |
How many searches each insights rule keeps. |
rules |
[] |
Keyed by handle. insights_popular and insights_nohits are reserved for a collection's insights. |
| Rule key | Default | |
|---|---|---|
type |
'popular_queries' |
popular_queries, nohits_queries or counter. |
collection |
A declared collection handle. | |
enabled |
true |
|
destination |
live name + _<handle> |
env. Query rules: the collection the counts are kept in. |
limit |
1000 |
Query rules: how many queries are kept. |
counterField |
'popularity' |
Counter rules: the document field incremented. It is added to the schema and kept through every reindex. |
eventType |
'click' |
Counter rules. |
weight |
1 |
Counter rules: added per event. |
A rule's name on the server is the collection's live name plus _<handle>. apply changes only what
differs, and running it twice changes nothing. remove deletes only the rules this config declares,
never one made by hand or by another environment. It keeps the collected counts.
craft.typesense.analyticsConfig() gives a page the events key and rule names, and
examples/alpine/view-counter.js posts one view per page load.
Editors with the Manage Typesense rules permission (typesense-sync:manageRules; admins always
have it) get a Typesense item in the control panel nav. It has a page for each declared
collection, with three tabs: Rules, Synonyms and Insights, and a
Stopwords screen beside the collections. The nav item appears only while the
connection is configured. Someone with only View search insights sees the Insights tab and
nothing else.
- Rules. "When someone searches garden, show these entries first, in this order, and never show that one." A rule has a search term, matched Exact or Contains, up to 20 pinned entries and up to 100 hidden ones, and optional Starts and Ends dates. Typesense calls a rule a curation. Switch on Also match synonyms and the rule also applies when the search is one of its term's synonyms from the Synonyms tab, so a rule for care home also fires for nursing home. When two rules match a search, only the one higher in the list applies, so drag rules to set which wins. A rule can be switched off and kept. A rule not yet started reads Scheduled, and one past its end reads Ended.
- Synonyms. A group of words that count as the same. All equal: each word finds the others. One way: the main term finds the words, and the words do not find it.
The pickers offer only the sources that feed the collection, and a save naming any other element is
refused. Each pinned or hidden element becomes a document id through the collection's formatter
(documentId()) when it is pushed, so an overridden id is respected. An element deleted after it was
picked is skipped and logged. Pinned entries obey the search's filters: a pinned entry outside a
scoped key's publication window, or hidden by its filter, is never shown.
Craft holds the rules, and Typesense holds a copy. For each collection the plugin owns one
curation set, <live alias>_rules, and one synonym set, <live alias>_synonyms. It creates both,
links them to the collection, and links them again to every version a recreate builds. Every save,
reorder, switch or delete in the section pushes the whole set straight away. If Typesense cannot be
reached, the edit is still saved, the page says Saved, not live yet, and a queue job pushes it again.
Each collection page shows its state: nothing when Typesense matches Craft; not live yet, with a
Push now button, when a set or its link is missing; out of step when someone changed the set in
the Typesense dashboard. The next save, or collections/apply, puts Craft's version back. Nothing
writes Typesense's version into Craft except rules/adopt. collections/apply, collections/status,
setup and the utility all push or report the sets alongside the schema, so a wiped or new cluster
gets its rules back from one command.
A set someone linked to the collection by hand stays linked. The plugin carries it through every rebuild and never removes it, and the utility lists it as also linked. Advanced rule options (replacing the query, adding a filter or sort, tags, metadata) are not in the section. Use a set of your own in the Typesense dashboard for those.
php craft typesense-sync/rules/export content --file=content-rules.json # on staging
php craft typesense-sync/rules/import content-rules.json # on productionThe export names each pinned or hidden entry by its uid, and by its type, site, section or group and
slug. Users travel by username. Import finds each one by uid first, then by the rest. It replaces
the collection's rules and synonyms, so it asks you to type the collection's handle (or take
--confirm=<handle>), then pushes. Anything it cannot find is listed and left out. A malformed file,
or one of an unknown version, changes nothing.
php craft typesense-sync/rules/adopt content --curation-set=my_featured
php craft typesense-sync/rules/adopt content --synonym-set=my_synonymsAdopt copies the set's items after the collection's existing rules or synonyms, pushes them, and then
unlinks the original set from the collection. It never deletes the original. Items the section
cannot show are listed and left out: a rule with a filter trigger, tags, a replaced query, a filter
or sort, metadata, stemming or stop_processing: false, and a synonym item with a locale or symbols.
So is a pinned or hidden id that is not an element feeding the collection, and a rule whose term the
section would refuse. Running adopt again adds nothing new.
A rule that matches synonyms is adopted with Also match synonyms on. Typesense 30.0 applies that option but does not report it when a set is read, so on 30.0 adopt cannot tell which rules had it: every adopted rule comes in with it off, and adopt says so. Check those rules in the section.
Its rows are kept. The section stops showing them, and the utility lists them as orphaned. Delete them with:
php craft typesense-sync/rules/prune content --confirm=contentPrune deletes the rows in Craft only. Without the collection's config the plugin cannot name its sets, so they stay in Typesense, as they do on uninstall. Remove them by hand, as in Uninstalling.
A stopword is a word search ignores. With the as a stopword, a search for "the garden room"
finds the same as "garden room". Stopwords are kept in named sets, and each collection uses one
set or none. Manage them under Typesense → Stopwords (admin/typesense/stopwords), which needs
the Manage Typesense rules permission.
- Sets belong to the Typesense server, not to the site. The plugin keeps no words in Craft. The screen lists every set on the server, whoever made it, and creates, edits and deletes any of them. Every site and environment using the server shares them, so an edit is live for all of them at once; the screen says so above the sets. A save is sent straight to Typesense and the set is shown as the server reads it back. If Typesense cannot be reached, or refuses the set, nothing is saved and the form keeps what you typed.
- A set has a name (letters, digits,
_and-, up to 64 characters; it cannot be changed later, so a new name is a new set), an optional locale such asen, and 1 to 1,000 words. Type one word per line. One word per entry: Typesense ignores single words only, so "care home" is refused rather than split into two stopwords that would drop care and home from every search. A word is 1 to 64 letters, marks or digits, kept in lower case. With no locale oren, Typesense folds words to plain letters, so café and cafe are one word; in another locale accents are kept. If any word is refused, nothing is saved, and the page says why for each. common_enis shipped.collections/applyandsetupcreate a set namedcommon_en, 54 common English words in localeen, when the server has none of that name. They never change one that exists, so your edits to it stand. Delete it and the next apply brings it back with the shipped words.- A collection picks no set until you pick one. The Collections list under the sets has one select per declared collection: choose a set or None and Save picks. Every key the plugin signs for a collection with a pick names that set, so stopwords apply with no change to the site's code, and the browser cannot switch the set off or name another. A key for a collection with no pick names no set. A pick takes effect on the next key signed; nothing is pushed. A search made with some other key ignores the pick.
- A search made only of stopwords finds nothing, so keep a set to words that never carry the meaning of a search on their own.
A picked set that goes missing breaks search. Typesense fails every search that names a set it
does not have. So deleting a set a collection on this site picks is refused, naming the collections,
and the delete confirmation warns that other sites using the server may pick it. If a picked set
goes missing anyway (deleted in the Typesense dashboard, or by another site), collections/status,
the utility and the collection's section say missing: every search on content fails until it is
recreated or another set is picked, and collections/apply and setup exit 1 so the deploy
fails loudly. A missing common_en pick heals itself, since apply recreates common_en first; for
any other set, recreate it or pick another.
The pick travels with the rules. rules/export writes the collection's stopwords: null for
none, or the set's name, locale and words. rules/import changes the pick only when the file has
that key, so a file from 1.1 leaves it alone. If the set is missing on the target server, import
creates it from the file; if it exists, its words are left as they are, and import says when they
differ from the file's. rules/prune deletes a removed collection's pick, never a set.
'collections' => [
'content' => [
// …
'insights' => true,
],
],insights => true gives the collection an Insights tab: the 50 most popular searches and the
50 searches that found nothing, over the last 7, 30 or 90 days, with how each popular search moved
against the period before (Up 40%, Down 10%, New). Beside a search that found nothing,
Add synonym and Add rule open the usual forms with the search filled in. Nothing is saved
until the editor saves. Once a search has an enabled synonym or rule, the list says so.
It needs the server's search analytics (see Analytics) and analytics.enabled. The
setting declares two analytics rules for the collection, insights_popular and insights_nohits,
each keeping its searches in its own destination collection (<live name>_insights_popular,
<live name>_insights_nohits, up to analytics.insightsLimit searches). collections/apply
creates them, analytics/status reports them, and switching insights back off deletes the two
rules on the next apply, keeping their destinations.
Typesense keeps only a running all-time count per search, with no dates. So once a day the plugin copies the counts into Craft and keeps what each search gained since the update before. Schedule it daily:
php craft typesense-sync/insights/update # every collection with insights on
php craft typesense-sync/insights/update content # one collection- The first update is a starting point. It records where the counts stand and adds nothing, so years of history never land on one day. Figures start from the second update, on a later day.
- Running it again the same day changes nothing. The command and the job can overlap safely.
- Opening Insights when the last update is over a day old queues one update through Craft's queue, so a site without a scheduler still fills in, as long as someone looks. The page never waits for it.
- It repairs itself. If an insights rule or its destination has gone missing, the update makes it again before reading. It never changes one that exists.
- It exits
1when a collection could not be read, and writes nothing for that collection.
Days are UTC. Popular searches are exact; the long tail is approximate. Typesense keeps only the
top insightsLimit searches, so a rare search can drop off its list and come back with its count
restarted. The update counts what was gained, never a fall, so a search is never negative.
Typesense records a search once the visitor pauses typing, and merges repeats from one visitor, so a count is visits that searched, not keystrokes. Typesense cannot be asked whether it is recording: a server without analytics accepts the rules and records nothing. When updates have run on two or more days and found no searches, the tab says the server may not have search analytics switched on.
The plugin stores counts per search term, per day, never who searched: no visitor, IP address or session. A term is still the visitor's own text and can contain a name or other personal detail they typed. Counts are deleted after 400 days. Typesense's destination collections hold the same terms, as all-time totals, until you delete them. Mention site search in your privacy notice if it covers what visitors type.
The destinations are read with the admin key on the server, never by the browser.
Utilities → Typesense Sync shows the connection, any configuration problems and warnings. For
each collection it shows the alias and live version, the document count and how the schema differs
from the formatters, with Apply, Reindex (optionally pruning documents no element builds)
and Recreate buttons. Recreate asks you to type the collection's handle to confirm. Reindex and
recreate run as queue jobs. When analytics is declared, the utility also shows each rule's state on
the server; apply rules with analytics/apply. Each collection also shows the state of its rule
and synonym sets, any set linked by hand, and rows left by collections no longer declared.
The Typesense section is described in Rules and synonyms, Stopwords and Search insights. It has two permissions:
| Permission | Gives |
|---|---|
Manage Typesense rules (typesense-sync:manageRules) |
Every tab and the Stopwords screen, including Insights with its Add synonym and Add rule buttons |
View search insights (typesense-sync:viewInsights) |
The Insights tab alone, without the buttons |
The utility also shows each collection's stopword pick (and whether its set is missing) and presets, and the insights rules sit with the other analytics rules.
Sync to Typesense is an element index action and an edit-screen action menu item for declared entries, categories, users and products.
The utility, its actions, the element action and the menu item all need the Utilities → Typesense
Sync permission (utility:typesense-sync).
| Command | |
|---|---|
typesense-sync/setup [--skip-sync] |
Validate, test, create collections, apply analytics, index |
typesense-sync/sync [--collection=h] [--prune] [--queue] |
Reindex one collection or all; --queue pushes jobs instead |
typesense-sync/sync/element <id> [--site=h] |
Sync one element now |
typesense-sync/sync/flush <collection> [--confirm=h] |
Delete every document, keeping the collection |
typesense-sync/collections/status |
Each collection's difference from its formatters |
typesense-sync/collections/apply [--collection=h] [--dry-run] |
Create or alter in place, then push sets, presets and analytics rules; the deploy step |
typesense-sync/collections/recreate --collection=h [--confirm=h] |
Rebuild beside the live version, then swap |
typesense-sync/analytics/status|apply|report|create-events-key|remove |
See Analytics; --dry-run, --limit |
typesense-sync/rules/export <collection> [--file=path] |
Write a collection's rules, synonyms and stopword pick (with its set's words) as JSON |
typesense-sync/rules/import <file> [--confirm=h] |
Replace a collection's rules and synonyms with an export's, and its stopword pick when the file has one, creating the set if the server lacks it |
typesense-sync/rules/adopt <collection> --curation-set=n|--synonym-set=n |
Copy a hand-made set in; a curation or synonym set is then unlinked |
typesense-sync/rules/prune <collection> [--confirm=h] |
Delete the rules, synonyms, stopword pick and search counts of a collection no longer declared (never a stopword set) |
typesense-sync/insights/update [<collection>] |
The daily update of search insights |
setup, collections/apply and collections/status include each collection's rule and synonym
sets, its stopword pick and its presets. setup and collections/apply create the shipped
common_en stopword set when it is missing, and exit 1 when a collection picks a set the server
does not have.
Flush, recreate, import and prune ask you to type the collection's handle, or take it as --confirm=<handle> in
scripts. A non-interactive run without --confirm is refused.
Exit codes: 0 success; 78 a configuration problem, or nothing declared; 64 bad usage (an
undeclared collection, a missing option, an unknown element or site); 1 anything else that failed
(the server, a wrong confirmation, a rejected document). A prune skipped because the run built no
documents exits 0 with a warning. The analytics commands exit 0 when no rules are declared, so a
deploy script can run them on every environment.
These are the plugin's public API, and follow semantic versioning.
use webdna\typesensesync\TypesenseSync;
TypesenseSync::getInstance()->sync->queueElement($entry); // bool: whether a job was queuedUse it when a document depends on something saved elsewhere, such as an author's name shown on their articles. It respects everything a save does: undeclared elements, drafts and duplicates queue nothing.
webdna\typesensesync\events\IndexDocumentEvent: element, target (ResolvedTarget) and
document (array). Raised for every document on its way to Typesense, in a single sync and in a
reindex. Change $event->document to alter what is written. The id is always put back to the
formatter's documentId(). Cancellable: set $event->isValid = false to keep the element out
of the index. A single sync then deletes its document, and a reindex skips it.
use webdna\typesensesync\events\IndexDocumentEvent;
use webdna\typesensesync\services\Sync;
use yii\base\Event;
Event::on(Sync::class, Sync::EVENT_BEFORE_INDEX_DOCUMENT, function(IndexDocumentEvent $event) {
$event->document['boost'] = $event->element->featured ? 10 : 0;
});webdna\typesensesync\events\SyncEvent: element, target, outcome (Sync::OUTCOME_INDEXED,
OUTCOME_REMOVED, OUTCOME_REJECTED or OUTCOME_SKIPPED) and document (what was written, or
null). Raised after each single-element sync, but not for each element of a reindex.
webdna\typesensesync\events\DeleteDocumentEvent: collection (the live name) and documentId.
Raised after every delete, including one that found nothing to delete.
webdna\typesensesync\events\ResolveTargetEvent: element and target, a ResolvedTarget or
null. Raised whenever the plugin decides where an element goes. Set target to null to keep an
element out, or change its collection, formatter or priority. Whatever you leave is checked
again, so an element cannot be routed into an undeclared collection. While a handler is attached, a
reindex asks it about every element too.
use webdna\typesensesync\events\ResolveTargetEvent;
use webdna\typesensesync\services\Targets;
Event::on(Targets::class, Targets::EVENT_RESOLVE_TARGET, function(ResolveTargetEvent $event) {
if ($event->element->getFieldValue('hideFromSearch')) {
$event->target = null;
}
});webdna\typesensesync\events\RegisterElementTypesEvent: types, the element classes whose save,
delete and restore events the plugin listens to. Entry is always there, and Category, User and
Commerce's Product appear while a source of their kind is declared. Add a class so that its saves
queue a sync, then route its elements with EVENT_RESOLVE_TARGET. Two limits apply to elements
that no source declares. A reindex does not walk them, so call queueElement() for each one to
fill a new collection. And the collection's schema comes from its sources' formatters and its
schema key, so declare their fields in one of those.
webdna\typesensesync\events\DefineScopedKeyEvent: collection (CollectionConfig), params (the
caller's), now, filters and excludeFields. Raised before each key is signed. Add to
filters and excludeFields to narrow the key. A handler cannot remove the publication window or
the collection's excluded fields, because those are applied on top. Cancellable: set
$event->isValid = false to refuse the key. None is made, and scopedKey() and searchConfig()
return null, so the page shows search as unavailable. Refuse when a filter the key must carry
cannot be built, for example when the collection a join names is not there, rather than let a
wider key through.
use webdna\typesensesync\events\DefineScopedKeyEvent;
use webdna\typesensesync\services\Search;
Event::on(Search::class, Search::EVENT_DEFINE_SCOPED_KEY, function(DefineScopedKeyEvent $event) {
if ($event->collection->handle === 'people') {
$event->filters[] = 'status:=active';
}
});On TypesenseSync::getInstance(): client, targets, sync, collections, search,
analytics, rules, presets, insights and rulesTransfer. The methods named in this README are public API. Other public methods may change in a
minor release.
- Give each environment its own
collectionPrefix(dev_,staging_,prod_), or an explicit env-awarenameper collection. - Documents hold root-relative URLs, so a document indexed by one environment links correctly from another.
- Analytics rule names follow the live name, so each environment's rules are its own, and
removenever touches another's. - Rule and synonym set names follow the live name too, so each environment's rules are its own.
Move them between environments with
rules/exportandrules/import. - Stopword sets are the server's, shared by every environment on it. Each environment keeps its own pick per collection, but an edit to a set is live everywhere that picks it. To try a change on staging alone, make a new set there and pick it.
- Preset and insights rule names follow the live name, so each environment's insights count only the searches made against its own collections.
- Nothing is indexed. Is the queue running? Is the element in a declared source, with an enabled entry type? Open the utility and look for problems first.
- A field is missing from results. Run
collections/status, thencollections/apply, thensync --collection=<handle>, because an alter changes the schema but not existing documents. - "Nothing enabled routes into …": every source for that collection is switched off or undeclared.
- Search works for editors but not for visitors. A page cache is probably serving an expired key. See Search pages.
- Logs. Everything is logged to Craft's logs under the category
typesense-sync, with the document ids involved.
Uninstalling removes the plugin's settings and its tables (rules, synonyms, stopword picks,
search counts and the record of insights updates), and stops the syncing. It does not delete anything on
the Typesense server. The rule and synonym sets stay linked and keep applying to search, since
removing them would change live results. Every stopword set stays, common_en included, since other sites on the server may pick it, and
so do the presets and insights rules.
The collections may be serving another environment. To remove them, first remove the analytics
rules, insights rules included, while the plugin is still installed:
php craft typesense-sync/analytics/removeThen delete each alias and its versioned collections, analytics destinations included, with the admin key:
curl -X DELETE "https://$TYPESENSE_HOST/aliases/prod_content" -H "X-TYPESENSE-API-KEY: $TYPESENSE_API_KEY"
curl -X DELETE "https://$TYPESENSE_HOST/collections/prod_content_1" -H "X-TYPESENSE-API-KEY: $TYPESENSE_API_KEY"To remove the rule and synonym sets, unlink them first. Typesense refuses every search on a collection that links a deleted synonym set. Unlink them from the live version, then delete them:
curl -X PATCH "https://$TYPESENSE_HOST/collections/prod_content_1" -H "X-TYPESENSE-API-KEY: $TYPESENSE_API_KEY" \
-H "Content-Type: application/json" -d '{"curation_sets": [], "synonym_sets": []}'
curl -X DELETE "https://$TYPESENSE_HOST/curation_sets/prod_content_rules" -H "X-TYPESENSE-API-KEY: $TYPESENSE_API_KEY"
curl -X DELETE "https://$TYPESENSE_HOST/synonym_sets/prod_content_synonyms" -H "X-TYPESENSE-API-KEY: $TYPESENSE_API_KEY"Leave out of the PATCH any set someone else linked that should stay. Deleting the collection itself removes its links too.
A stopword set and a preset are not linked to anything, so delete them directly. A search key or
page that still names one fails, so delete them last, and delete a stopword set only when no other
site or environment on the server picks it (GET /stopwords lists them):
curl -X DELETE "https://$TYPESENSE_HOST/stopwords/common_en" -H "X-TYPESENSE-API-KEY: $TYPESENSE_API_KEY"
curl -X DELETE "https://$TYPESENSE_HOST/presets/prod_content_default" -H "X-TYPESENSE-API-KEY: $TYPESENSE_API_KEY"The insights destinations (prod_content_insights_popular, prod_content_insights_nohits) are
ordinary collections, deleted like the others above.
GET /aliases, GET /collections, GET /curation_sets, GET /synonym_sets, GET /stopwords and
GET /presets list what is there. Delete the search-only key and the events
key through /keys if nothing else uses them.
Report issues on GitHub. Typesense Sync is licensed under the Craft License and made by webdna.