5.8.5
Settings
Every search setting, for plain Astro in astro.config.mjs and for EmDash on the plugin's admin page.
Search has two places to set it up, one for each way to install it:
- Plain Astro: options to
search()inastro.config.mjs. A change shows on the next build. - EmDash: a few options in
astro.config.mjs, and the settings on the plugin’s Search admin page. An admin change shows on the next page view, with no rebuild.
For the look and the text of the dialog, see Look and text.
Plain Astro
One index or several
Most sites need one index. Put its settings at the top level, and the index is named default:
// astro.config.mjs
import { defineConfig } from "astro/config";
import search, { collections, html } from "@astronomic-dev/search/astro";
export default defineConfig({
site: "https://example.com",
integrations: [
search({
sources: [collections({ docs: { label: "Docs", facets: ["theme"] } }), html({ include: ["/", "/pricing"] })],
weights: { title: 3, heading: 2, text: 1, keywords: 1 },
group: { dialog: "type" },
types: { docs: { weight: 1.5 } },
shortcut: { keys: ["mod+k", "/"] },
browse: [{ label: "Docs", href: "/docs" }],
}),
],
});
A big part of the site, such as a component catalog, can get its own index. Each index has its own files, so it does not slow down the main search:
search({
indexes: {
site: { sources: [collections({ docs: {} }), html()] },
kit: { sources: [records(loadParts, { types: { kit: { label: "Kit parts" } } })], group: { dialog: false } },
},
default: "site",
});
A search button picks its index with the index prop. See Install on Astro for sources and the three adapters.
Index settings
Each index takes these. With one index, put them at the top level.
| Setting | Default | What it does |
|---|---|---|
sources |
(required) | Where the records come from: collections(), html() and records(). |
weights |
{ title: 3, heading: 2, text: 1, keywords: 1 } |
How much a match in each field counts. keywords covers a page’s keywords and its facet values. |
group |
{ dialog: "type", page: false } |
How results are grouped in the dialog and on the search page: "type", a facet name, or false for one list by score. The plain Astro SearchPage always shows one list, so page has no effect there. |
groupOrder |
"best" |
"best" puts the group with the best match first. A list of group keys fixes the order, and the type tabs follow it: the types it names first, in its order, then the rest by name. With "best" the tabs are in type-name order. |
types |
from the sources | Per type: a label, and a score weight (default 1). |
facets |
from the sources | Per facet: a label, and labels for its values. |
budget |
{ gzipKB: 300 } |
The build warns when the index file grows past this size, gzipped. |
clip |
whole text | How many characters of each section’s text the index keeps. At least 200. |
suggested |
none | Links shown in an empty box, before recent searches. |
synonyms |
none | Groups of words that match each other. |
pinned |
none | Pages shown first for a whole query. |
A few of these need more detail.
Facets. No source or index may name a facet type (that is the content type) or q (the search page reads ?q= as the query). The build fails on either.
Clip. Use it for a smaller file on a large site. Words past the cut are still found, and a result still links to their section, but its preview shows the start of the section. The first 1,000 characters of a section rank higher than the rest, with or without clip.
Suggested. A list of { label, href, type? }, at most 8. Give one list for every locale, or one per locale: { en: [...], fr: [...] }. A locale the map leaves out shows none. Each href must be a canonical URL on this site, and each type one of the index’s types. The build fails otherwise.
suggested: [
{ label: "Install", href: "/docs/install", type: "docs" },
{ label: "Pricing", href: "/pricing" },
],
Synonyms. One word per entry: [["docs", "documentation"], ["price", "cost"]]. A query word in a group is searched as any word of its group. Case and accents do not matter.
Pinned. A whole query, mapped to the pages shown first, in that order:
pinned: { "get started": ["/docs/install", "/docs/first-steps"] },
The query is matched whole, ignoring case, accents and extra spaces. A pinned page shows even when the words do not match it, but only when it passes the type tab and the filters. Each URL must be a canonical page URL in the index. The build fails otherwise.
Result type of a built page
A page that html() reads takes its source’s type. A page can set its own in its head, so one html() source can read pages of several types that share a route, such as posts and pages both at /<slug>:
<meta name="search:type" content="posts">
The type must be one a source of the index declares (html({ type: "posts" }), a collection, or a records() type). Another value is a build warning, and the page keeps its source’s type. Its heading records take the page’s type. The meta needs version 0.2.5 or later.
Site settings
These apply to the whole site, not to one index.
| Setting | Default | What it does |
|---|---|---|
indexes |
none | Named indexes: { name: { sources, ... } }, each with the index settings above. |
default |
"default" with one index |
The index a search button uses when it names none. |
shortcut |
{ keys: ["mod+k", "/"] } |
The shortcut keys, or false for none. |
strings |
US English | Labels that replace the defaults. See Look and text. |
browse |
[] |
Links for the error state and the no-JavaScript part: [{ label, href }]. |
theme |
none | "light" or "dark": the dialog’s colors, whatever the visitor’s device is set to. Left out, the dialog follows the device. A site with its own toggle: see Look and text. |
An index name is letters, digits, - and _, and starts with a letter or a digit. Names must be unique, ignoring case, because each becomes part of the index’s file names. Each browse link’s href must be a canonical URL on this site. The build fails otherwise.
Shortcut keys
A key is written as modifiers joined by +, then one key: mod+k, /, shift+?, alt+s. The modifiers are ctrl, meta, alt, shift and mod. mod is Cmd on Apple devices and Ctrl elsewhere. A modifier the key does not name must be up, so mod+k does not match Cmd+Shift+K.
shortcut: { keys: ["mod+k"] }, // only Cmd+K or Ctrl+K
shortcut: false, // no shortcut
For what each key does in the dialog, see Keyboard.
EmDash
Config options
The plugin takes a few options in astro.config.mjs. Most sites need none:
// astro.config.mjs
import { defineConfig } from "astro/config";
import emdash from "emdash/astro";
import { search } from "@astronomic-dev/search/emdash";
import { searchFiles } from "@astronomic-dev/search/emdash/astro";
export default defineConfig({
integrations: [
emdash({
// your existing EmDash options (database, storage and so on)
plugins: [search({ collections: ["posts", "pages"] })],
}),
searchFiles(),
],
});
| Option | Default | What it does |
|---|---|---|
collections |
every collection with search support that is routable and not hidden | The collection slugs to index. A listed collection that is not routable is skipped, with a build warning. |
groupOrder |
"best" |
The order of the result groups and the type tabs: "best" (the group with the best match first, the tabs by collection slug) or a list of collection slugs, first to last. Collections it leaves out follow. Each slug once; a slug the index does not have is a build warning. |
budget |
{ gzipKB: 300 } |
The size warning for each locale’s index, gzipped. |
clip |
whole text | How many characters of each entry’s text the index keeps. |
exclude |
none | Site paths to leave out of search, such as a page the theme has turned off: ["/speaking", "/projects/*", "/sitemap-*.xml"]. Case makes no difference. A * segment is any one segment; a * inside a segment is any run of characters there. See Leave pages out. |
excludeWhen |
none | Site paths to leave out while a switch in a settings entry is set, such as a part the site owner has turned off in the admin: [{ collection: "details", field: "switch_areas", values: ["off"], paths: ["/areas", "/areas/*"] }]. See Leave pages out. |
locked |
none | Entries for members or paying readers only, by a field: { collection: "posts", field: "access", open: ["public"] }. Their text never goes in the index. See Members-only entries. |
skipWhen |
none | Entries to leave out entirely by a field value or their slug, such as a home entry the theme shows at /: [{ collection: "pages", field: "slug", values: ["home"] }]. See Leave pages out. |
trailingSlash |
the site’s | "always", "never" or "ignore": the address form of record URLs and of the results page URL the page prints, in place of the site’s trailingSlash. See Results page URL. |
listPages |
none | Pages that list whole collections, such as a talks page or a FAQ, so a search for an item finds the page. See List pages. |
taxonomyKeywords |
none | Taxonomies whose term labels are keywords of their entries: ["category", "tag"]. See Categories and tags. |
textFields |
none | More fields to search, per collection: { projects: ["problem", "case_*"], areas: ["intro"] }. See More fields. |
filesPath |
/_search/embed/ |
Where the site serves the search files. Must match searchFiles({ path }). |
The options must be plain JSON, because EmDash passes them to the plugin as JSON. A function, a RegExp or a Date throws.
Leave pages out
Use exclude for an entry that is published but has no page: a theme can turn a page off in its code, while the entry that words it stays published, and a result for it would be a 404.
search({ exclude: ["/speaking", "/projects/*"] });
- A path is exact, in any case:
/Speakingand/speakingare the same. A*segment is any one segment:/projects/*leaves out every project, but not/projectsitself. A*inside a segment is any run of characters in that segment, none too:/sitemap-*.xmlleaves out/sitemap-0.xmland/sitemap-index.xml, but not/sitemap.xml. An encoded%2Ais a plain asterisk. - Write paths as the site has them, starting with
/, with no base. A trailing slash makes no difference. Letters can be plain or encoded (/caféor/caf%C3%A9). - A path with no locale prefix is left out in every locale:
/speakingalso leaves out/fr/speaking. To leave a page out in one locale only, write its prefix:/fr/speaking. A first segment that is a locale’s prefix always means the locale, even if a page has the same slug. A*never stands for the prefix. - A change to an option (
exclude,excludeWhen,skipWhen,trailingSlashfor record URLs,collections,clip,listPages,locked,taxonomyKeywords,textFields) is in your code, so EmDash sends no content event for it. It shows after the next build: click Rebuild now after you deploy, or wait for the next content change or the nightly build. excludeandexcludeWhencover this index only. EmDash’s own search, which the theme’s server list uses, still finds the entry.
While a switch is off. Use excludeWhen when the site owner turns a part of the site on and off in the admin, with a field of a settings entry (a select of on and off, say). At each build the plugin reads that entry, and while the field holds one of values, the paths are left out as exclude leaves them out.
search({
excludeWhen: [{ collection: "details", field: "switch_areas", values: ["off"], paths: ["/areas", "/areas/*"] }],
});
collectionis a collection with one entry. It needs no search support and no URL. The plugin reads its newest published entry, the one a theme that lists the collection gets first (EmDash lists the newest first). A second published entry is a build warning, and the newest one is read.pathswork as inexclude, and the two lists join: a path left out gets no page fromlistPageseither.- An empty field and no published entry both read as
null. Putnullinvalueswhen the part is off by default. - A collection or field the site does not have, or a field that holds a list or an object, is a build warning, and the rule leaves nothing out.
- If the entry cannot be read, the build fails, the live index stays as it was, and the next tick tries again. A read error never brings back the pages of a part that is off.
- Only published content counts. Publishing the entry is a content change, so the index is rebuilt within about a minute. With
collectionslisted, the rule’s collection counts too. - When it shows: a part turned off leaves search on page loads after the next build that succeeds. A tab that loaded the index earlier keeps the old results until it reloads, and while builds fail, the old index stays live.
By a field or slug. Use skipWhen to leave single entries out, wherever their URL is: a home entry the theme renders at /, a page the theme never routes, or an item a list page hides.
search({
skipWhen: [{ collection: "pages", field: "slug", values: ["home"] }],
});
- A skipped entry is left out before anything else reads it: it gets no record, takes no URL (so another entry at the same URL is the result, and it hides none), adds no words to a page in
listPages, and gets notaxonomyKeywordslabels. collectionis an indexed collection or one that onlylistPagesreads.fieldis a data field, orslugfor the entry’s own slug.valueshold strings, numbers, booleans andnull, matched exactly: no trimming, no case folding, and1is not"1". An absent field reads asnull.- A collection that is neither indexed nor read by
listPages, or a field the collection does not have, is a build warning, and the rule skips nothing. A rule that is not a list of{ collection, field, values }throws at config load. - A change to the field is a content change, so the index is rebuilt within about a minute. With
collectionslisted, the rule’s collection counts too.
List pages
Use listPages for a page whose route shows a whole collection with no page per entry, such as talks, a FAQ or price plans. The words of the entries go to the end of the page’s text, so a search for an item finds the page that lists it.
search({
listPages: [
{
path: "/speaking",
from: [{ collection: "talks", fields: ["title", "event", "summary"] }],
fallback: { title: "Speaking", text: "Talks and workshops." },
},
],
});
| Key | What it does |
|---|---|
path |
The page’s site path, literal, with no base and no locale prefix. Each path once. |
from |
The collections the page lists, and the fields to take the words from. A field holds a string or Portable Text; anything else adds nothing. The collections need no search support and no public URL. |
fallback |
{ title, text? }: makes the page when no entry has the path, for a route whose words are in the theme’s code. Leave it out, and only an entry’s own page gets the words. |
type |
The type of the page fallback makes. Default pages. |
fromtakes the whole collection: every published entry withoutseo.noIndex, in the page’s locale. List only collections and fields the page really shows, because the index is public. There are no filters.- The page keeps its entry’s title, type and URL, in every locale that has one.
fallbackmakes a page in the default locale only. - A published entry at the path with
seo.noIndexon keeps the page out, with or withoutfallback. An unpublished one leaves the fallback, if any. An entry in a collection that is not indexed is not seen. If two entries have the path, nothing is added and the build warns. excludewins: an excluded path gets no page. An excluded entry still adds its words to the page that lists it.- A page gets up to 20,000 characters from its items; the build warns when it cuts the rest. An unknown collection or field is a build warning too.
listPagesadds to a searchable site. With no search collection at all, the build staysno-collections.- A change to an item shows like any other change. A change to
listPagesitself is in your code, so click Rebuild now after you deploy.
Categories and tags
taxonomyKeywords makes the labels of an entry’s terms its keywords, so a search for a tag finds the posts that have it. It is off by default.
search({ taxonomyKeywords: ["category", "tag"] });
- The names are the taxonomies’ names in EmDash. A name no entry has terms in adds nothing, with no warning.
- The entry’s own keywords come first, then the labels in the order of the list, with no duplicates. An entry keeps its first 20 keywords, as everywhere.
- A label is the one in the entry’s locale, else the one in the default locale. The terms of an entry in
listPagesdo not go to the page that lists it. - When a change shows. Saving or publishing the entry rebuilds the index as usual. But setting a term in the admin on its own, and renaming or deleting a term, send no content event in EmDash. They show after the next build: the next content change, Rebuild now or the nightly build.
- Cost: about 2 more D1 queries per 100 entries (more on a site whose entries are in several locales). If EmDash cannot read the terms, the build warns and goes on without them.
More fields
By default an entry’s text is its lead (the first of excerpt, summary, description and the SEO description) and its Portable Text content. textFields names more fields to search, per collection, such as a project’s case study or an area’s intro. Their words follow the lead, before the content.
search({
textFields: {
projects: ["problem", "approach", "result", "case_*"],
areas: ["intro"],
},
});
- A field holds a string, Portable Text, or a list of blocks of your theme’s own types: each block’s text, such as its heading, text and list items. Images, links and anything else add nothing.
- A name that ends in
*is every field whose slug starts with the rest, in the collection’s field order:case_*takescase_title,case_ledeandcase_blocks. - For a list of blocks,
{ field: "case_blocks", keys: ["heading", "text", "steps"] }reads only the words under those keys of each block, at any depth (astepslist gives each step’s words), so a layout value such asside: "end"stays out of search. Withoutkeys, every string of a block counts. The entry sets the keys of that field when a*name takes it too. title,contentandsearch_keywordsare read already, so they are left out. The lead field is not added twice.- A field the collection does not have, a
*no field matches, and a collection that is not indexed are build warnings. A name that is not a field slug throws. - Each entry gets up to 20,000 characters from these fields; the rest is cut, with a build warning.
clipand the size budget still apply, and the index is public, so list only fields the page shows. - A change to the option shows after the next build: click Rebuild now after you deploy.
Members-only entries
The index is public: anyone can download it. When some entries are for members or paying readers only, name the field that says so with locked, and the text of those entries never goes in the index.
search({ locked: { collection: "posts", field: "access", open: ["public"] } });
- An entry is open when the field is missing,
nullor exactly"", or when it is a string that, with spaces trimmed from both ends, is exactly one ofopen. Case counts. Anything else locks the entry:"members","paid","Paid"," ", a number or an object. A typo locks an entry; it never opens one. - A locked entry’s record has its title and its
taxonomyKeywordslabels only. Its excerpt, summary, description, SEO description, content,textFieldsandsearch_keywordsare left out. A reader finds it by its title, categories and tags, and the result leads to its page, which shows what your theme shows a reader who is not signed in. - In a list page, a locked entry adds only its title (its
titlefield, elsename), whateverfieldsnames. This holds for a collection that is not indexed too. - Give a list for more than one collection:
locked: [{ collection: "posts", ... }, { collection: "letters", ... }], each collection once. fieldis a field slug, and cannot betitle,contentorsearch_keywords.openis a list of strings with no spaces around them. Any other key, or any other value, throws when the config loads. So does an optionsearch()does not know, so a misspelledlockednever builds an index with the text in it.- It fails closed: a collection in
lockedthat the site does not have, or that has no such field, is a build warning, and every entry of it is locked. - Search checks the field only. Who is signed in does not matter: a member who may read an entry still finds it by its title and labels only.
lockedneeds version 0.2.5 or later. Earlier versions do not know it.- When a change shows. A save, publish, restore or schedule that leaves an entry locked takes the public index offline at once, so the dialog falls back to your theme’s server list (
/searchwith no JavaScript). The next build, about a minute later, leaves the entry’s text out and search comes back. A failed build, or one that started before the change, does not bring it back: watch the admin’s search page after you lock an entry. Editing an entry that is already locked takes the index offline for that minute too. A tab that loaded the index earlier keeps its copy until it reloads. The entry’s page itself is your theme’s to lock at once.
searchFiles() takes one option, path (default /_search/embed/). It must match the plugin’s filesPath.
Admin settings
Open Search in the EmDash admin. The settings are under the index status.
| Setting | Default | What it does |
|---|---|---|
| First shortcut | mod+k |
A key that opens search. |
| Second shortcut | / |
A second key that opens search. |
| Take over the theme’s search form | off | The theme’s own search box opens the search dialog. |
| Search input name | q |
The name of the theme’s search field. Used only with takeover on. |
| Search box text | Search the site |
The text in an empty search box. |
| Theme | Auto | The dialog’s colors: Auto (follow the visitor), Light or Dark. |
| Results page URL | /search |
Where “See all results” goes, and the form address takeover looks for. |
Press Save. The admin page says “Changes show on the next page view. No rebuild needed.” The settings go into a small config tag on each public page, so the next page a visitor opens uses them.
A value that is not valid takes its default when you save.
Shortcut keys
Click a shortcut field and press the keys. The field records the press, such as mod+k or shift+?. Backspace or Delete clears it. Tab moves on to the next field. A cleared field means one shortcut, or none.
mod is Cmd on a Mac and Ctrl elsewhere. Some limits:
- Space cannot be a shortcut. The field records nothing for it.
- On a Mac, Ctrl records as
ctrl, notmod. So Ctrl+K on a Mac savesctrl+k, which works only with Ctrl. Press Cmd+K to savemod+k, which is Cmd+K on a Mac and Ctrl+K elsewhere. - A modifier alone, such as Shift, records nothing.
- Every held modifier is part of the key: Shift+/ saves
shift+?.
Takeover and the input name
Most themes have their own search box. With Take over the theme’s search form on, that box opens our search dialog instead. It works by itself on two kinds of box:
- A GET form that goes to your results page URL, with one search field named as in Search input name (
qby default). - EmDash’s
LiveSearchbox, in EmDash’s default templates.
With takeover on, the shortcut keys also win over the theme’s own. If search cannot load, the theme’s box is given back to the theme. A theme with its own search popup needs a small change instead. See Works with your theme.
If your theme’s field has another name, such as s or query, type it in Search input name. A name is letters, digits, _, - and [].
Search box text
The text in an empty search box, such as “Search recipes”. It shows in the search dialog. With takeover on, it also shows in your theme’s search box, so both read the same. Up to 80 characters.
Theme
- Auto (follow the visitor): light or dark, from the visitor’s device setting.
- Light or Dark: always that, whatever the device says. Pick the one that matches your site.
The theme sets the dialog and the small box phones show on the first tap. The results page has no colors of its own: it always takes your page’s text color. To match your brand colors, see Look and text.
Results page URL
The address of your site’s search page, such as /search. “See all results” in the dialog goes there with the query as ?q=.
With takeover on, it must match your theme’s search form action exactly, trailing slash included. A form that goes anywhere else is left alone. With the trailingSlash config option set, the URL is printed in that form whether you save it with a slash or without, and the index’s result URLs follow it too, in place of the site’s setting. Your form’s action must then use the same form. The URL is a path that starts with /, or a full http or https address. To set up the page itself, see The results page.
What the admin page cannot set
Ranking weights, several indexes and the other dialog labels are not on the admin page yet. The index status, Rebuild now and what is indexed are covered in Install on EmDash.