# Seekmere: the guide for app teams

Seekmere (Lunaor's Search) makes an app's data searchable: typo-tolerant, as people type, with facets, filters,
sorting, synonyms and semantic search. It can follow your TwilightDB collection or FS3 folder by itself. This guide
takes you from nothing to a search box in a web page. Every step can also be done in the console
(`https://search.lunaor.com/console`) or by asking your agent (the MCP tools are in brackets).

API: `https://search.lunaor.com`. Every call but search-key searches takes a Harpora access token for the API
`urn:search:api` (`Authorization: Bearer …`).

## 1. An org, and who's in it

Indexes belong to an org. Roles:
- **members** search;
- **deployers** write documents;
- **admins** create indexes, connect sources and tune relevance;
- **owners** do all of that and manage members.

An org's owner adds people (`set_member`):

```sh
curl -X PUT $SEARCH/v1/orgs/acme/members/email:ana@acme.com -H "authorization: Bearer $TOKEN" -d '{"role": "deployer"}'
```

**An app's server** is a member too: give its Harpora machine client a role by subject (`sub:<client id>`) and let
it use a client-credentials token for `urn:search:api`. Deployer is enough to write documents.

**Or give it an API key** (`POST /v1/orgs/{org}/keys {"role": "deployer", "label": "backend"}`; Seekmere's console
makes them too): a secret `sadm_…` sent as `Authorization: Bearer sadm_…` that acts as the member `sub:key:<id>`
with that role (member, deployer or admin; never owner). An owner makes one at once, an admin with an owner's nod. The
secret is shown once; `GET /v1/orgs/{org}/keys` lists them (admins), `DELETE /v1/orgs/{org}/keys/{id}` revokes one at
once. Keep it on the server: a page gets a search-only key (section 5).

## 2. Make an index (`create_index`)

An index's fields are fixed when it's made:
- **text:** searched by word;
- **keyword:** exact, for filters and facets;
- **numeric:** for ranges and sorting;
- **vector:** optional, for semantic search. With `"from": ["title", "body"]` Seekmere makes each document's vector
  from those fields when it comes without one, and a search with `"semantic": true` embeds its words too (a hybrid
  search); `"model"` picks another embedding model than the server's. Without `from`, documents bring their vectors.

```sh
curl -X PUT $SEARCH/v1/indexes/help -H "authorization: Bearer $TOKEN" -d '{
  "org": "acme", "text": ["title", "body"], "keyword": ["section", "lang"], "numeric": ["updated"], "geo": "location",
  "vector": {"field": "embedding", "dims": 384}
}'
```

An org holds up to its `max_indexes` (10 by default); past that, an owner approves.

## 3. Fill it: write documents, or follow a source

**Write** (`write_documents`, a deployer):
- Documents are JSON objects with a string `id`; one with an id already there is replaced.
- A batch (up to 10,000) is searchable together when the call returns.

```sh
curl -X POST $SEARCH/v1/indexes/help/documents -H "authorization: Bearer $TOKEN" -d '{
  "put": [{"id": "reset", "title": "Password reset", "body": "Open settings…", "section": "account", "updated": 1764633600}],
  "delete": ["old-faq"]
}'
```

**Or follow a source** (an admin). Seekmere copies everything once, then applies each change as it happens; no sync
code:
- **A TwilightDB collection** (`attach_source`): records become documents with their fields' proto names.

  ```sh
  curl -X PUT $SEARCH/v1/indexes/help/source -H "authorization: Bearer $TOKEN" \
    -d '{"database": "helpdesk", "collection": "articles", "token": "<a TwilightDB token that reads it>"}'
  ```

- **An FS3 folder** (`attach_fs3_source`): each file becomes `{id: key, name, folder, size, updated, text}`, with the
  text of text files, PDFs and Word documents.

  ```sh
  curl -X PUT $SEARCH/v1/indexes/help/source -H "authorization: Bearer $TOKEN" \
    -d '{"fs3": {"bucket": "team", "prefix": "handbook/", "key": "<a read key for the bucket, kid.secret>"}}'
  ```

- **A website** (`attach_web_source`, as Algolia's Crawler or DocSearch): each page under `prefix` (default: the
  start page's folder) becomes `{id: url, url, title, description, headings, text, updated}`, found from the site's
  sitemaps and links, obeying robots.txt (`SeekmereBot`) and `noindex`, at most 2000 pages, crawled again each day
  (pages gone are removed). Only public sites; on servers where the operator turned crawling on (`SEARCH_CRAWL=1`).
  For docs, `"sections": true` makes a result per heading instead, as DocSearch's records: `{id: url#anchor, url, page,
  title, hierarchy, heading, text}`, so a hit links to its place on the page. A page's schema.org JSON-LD adds fields
  (`schema_type`, `brand`, `price`, `currency`, `availability`, `sku`, `category`, `rating`, `reviews`, `author`,
  `published`, `image`): name `brand` a keyword field and `price` a numeric one, and a crawled shop facets and filters.

  ```sh
  curl -X PUT $SEARCH/v1/indexes/help/source -H "authorization: Bearer $TOKEN" \
    -d '{"web": {"url": "https://example.com/docs/"}}'
  ```

Seekmere checks the token reads the data before following, and keeps it sealed. `GET /v1/indexes/help` shows how far
the source has got.

## 4. Search (`search`)

```sh
curl "$SEARCH/v1/indexes/help/search?q=pasword%20rese&facet=section&filter=lang:en&sort=-updated&limit=10" \
  -H "authorization: Bearer $TOKEN"
```

- **Words:** every one must match. Typos are forgiven (one from 4 letters, two from 8), and the last word matches
  as a prefix. `"quoted phrases"`, `+must` and `-not` are read as written (`exact=true` turns typos and prefixes off).
- **`filter=field:value`** narrows on exact fields. **`range=updated:1764000000..`** narrows on numbers.
  **`sort=-updated`** sorts by a number field (`-` for descending).
- **`facet=section`** counts each value across all matches.
- **The answer:** `{found, hits: [{id, score, doc, highlights}], facets}`. `highlights` holds each text field's best
  fragment as escaped HTML, the matched words in `<b>`.
- **Near a place:** an index made with `"geo": "location"` (documents hold `{"lat", "lng"}` or `[lat, lng]`)
  searches `near=-33.86,151.21&within=2000`. Hits carry `distance_m`. Without words they come nearest first; with
  words they're ranked by the words inside the radius (or add `sort=_distance`).
- **Inside an area:** `inside_box=<north>,<east>,<south>,<west>` keeps to a map's visible area (a west longitude
  above the east one crosses the antimeridian), and `inside=<lat>,<lng>,<lat>,<lng>,<lat>,<lng>…` to a polygon of 3
  to 100 points (straight edges in latitude and longitude; not across the antimeridian). As JSON: `"inside_box": [n,
  e, s, w]`, `"inside": [[lat, lng], …]`. Either goes with words, filters, facets and `near`.
- **Semantic and hybrid:** `POST` the same search as JSON with `"vector": [your query's embedding]`. With `q` too,
  the two rankings are fused: what both find leads.

- **More like this** (related items, "you may also like"): `GET /v1/indexes/{name}/documents/{id}/similar?limit=5`
  (MCP `similar_documents`) answers documents like that one, best first, never itself: by its vector in an index
  with vectors, else by the words that say most about it (frequent in it, rare in the index). `by` says which.
  Filters and ranges narrow the hits, as in a search. A search key may ask too, for a document inside its fixed
  filters, and gets hits inside them. The console's results have **Similar** under each hit.
- **Answers** (a question answered from the results, as Typesense's conversational search and Algolia's Ask AI):
  `POST /v1/indexes/{name}/answer {"q": "when is the offsite?", "filters": …}` searches the question's words (any may
  match, the most and rarest first), sends the first 5 results' text fields to the server's answer model, and answers
  `{answer, sources: [{n, id, doc}], found}`, the answer citing its sources as [n] (null when nothing was found). Off
  until the index's admins tick **Answer questions from results** in Relevance (`answers` in `set_relevance`), and only
  on a server with a model (`SEARCH_ANSWER_URL`, `SEARCH_ANSWER_KEY_FILE`, `SEARCH_ANSWER_MODEL`); 30 an index a minute.
  A search key may ask, within its filters (Seekmere's `.answer(q)`); show the answer as text. The console's Search
  tab has **Ask** beside the box where answers are on (MCP `answer_question`). A follow-up sends `history`: the
  earlier `[{q, answer}]`, oldest first; the last 3 go to the model before the sources, and the question before it is
  searched with the follow-up's words ("and which lodge?" still finds the offsite). Nothing is kept on the server.
  With `"stream": true` the answer comes as server-sent events as the model writes it: `sources`, `delta` (`{text}`)
  pieces, then `done` (`{answer}`) or `error`; Seekmere's `.answerStream(q, options, onText)`. A refusal before the
  model is asked (off, an empty question, the minute's cap) is a plain JSON error. The search box takes `answers`
  (`<seekmere-search … answers>`): an **Ask** button that streams the answer under the box, as text, with its sources;
  each Ask follows up the last until the box is emptied, and a `seekmere-answer` event carries each answer. Connect's
  snippet includes it where answers are on.

`GET /v1/indexes/{name}/trending?days=3&limit=10&filter=category:lamps` (MCP `trending_documents`, the browser
client's `trending()`) answers trending items: documents chosen more in the last `days` (1 to 14) than their usual rate
over 30 days, most risen first, each with its document, `recent` choices and `usual_per_day`. It counts the clicks the
search box and your app report (`POST …/click`), so report them. Search keys work, inside their filters.

`GET /v1/indexes/{name}/documents/{id}/bought-together?limit=4` (MCP `bought_together`, the browser client's
`boughtTogether(id)`, InstantSearch's `frequentlyBoughtTogether`) answers what's bought with a document: others the
same people converted on within a week of it, at least twice, most often first, each with `together`. It counts the
conversions your app reports with a `user` (`POST …/conversion {"q", "id", "user"}`, or InstantSearch's insights
through the client's `insightsClient`). Search keys work, inside their filters.

## 5. In the browser: a search key and one tag

**A search-only key** (`make_search_key`) searches one index, always inside its fixed filters (e.g. one customer's
documents), from any origin, at 20 searches a second. An owner makes one at once; an admin or an agent asks an owner.
The secret is shown once. A key can also expire (`expires_ms`: a campaign's key, a contractor's week; refused
once past, and listed as expired) and cap its hits (`max_hits`, 1 to 100 a search, which slows scraping), as Algolia's
`validity` and `maxHitsPerQuery`; both are part of what the owner approves.

**Private fields** (relevance `private_fields`, the console's Private fields box; Algolia's `unretrievableAttributes`)
are fields keys never get back: a cost price, a margin, internal notes. Searches still match their words and members
still see them, but a key's hits, highlights, recommendations and answers leave them out, and a key that filters,
sorts, facets, counts or groups on one is refused (403), so their values can't be worked out by probing. A field in
`facet_words` or `facet_order` can't be private (those show values to anyone). MCP `set_relevance` keeps them as
they are unless `private_fields` is given.

```sh
curl -X POST $SEARCH/v1/indexes/help/keys -H "authorization: Bearer $TOKEN" -d '{"filters": {"lang": "en"}, "label": "help centre"}'
```

**Then, in the page:**

```html
<script type="module" src="https://search.lunaor.com/v1/sdk/seekmere.js"></script>
<seekmere-search index="help" key="srch_…" facets="section" title-field="title" text-field="body"></seekmere-search>
<script>
  document.addEventListener("seekmere-select", (e) => location.href = `/help/${e.detail.id}`);
</script>
```

What the element does:
- searches as people type;
- highlights matches, and offers facets to narrow by;
- works with the arrow keys, Enter, and screen readers;
- when nothing is found, offers searches that work.
- with `trending`, shows what's trending (chosen more lately than usual) in the empty box once it's focused; picking
  one isn't counted as a click, so trending doesn't feed on itself.

Style it with `--seekmere-accent`, `--seekmere-bg`, `--seekmere-fg`, `--seekmere-muted`, `--seekmere-line` and
`--seekmere-mark`. Or use the client:
`await new Seekmere({ index, key }).search(q, { facets, filters, any, sort, limit })`, `.suggest(q)`, `.trending({ days, filters })`
and `.similar(id, { limit, filters, fields })` ("you may also like" on a product page).

**Already using InstantSearch?** (InstantSearch.js, React or Vue InstantSearch.) Give it Seekmere as its search
client, and keep your widgets:

```js
import { instantSearchClient } from "https://search.lunaor.com/v1/sdk/seekmere.js";
const search = instantsearch({ indexName: "help", searchClient: instantSearchClient({ key: "srch_…" }) });
```

Search boxes, hits with `Highlight` and `Snippet`, refinement lists (several values: any of them, and searching
within their values), menus, toggles, range inputs and sliders, and pagination work as they do on Algolia. A slider
spans what the matches hold once the client knows its number fields: `instantSearchClient({ key, numeric: ["price"]
})` sums them up and answers Algolia's `facets_stats` (min, max, average, sum). Not available: excluding a value
(`-field:value`). Pages reach the first 1,000 hits.

Click analytics come along too: hand InstantSearch the client's own insights client, and `sendEvent` in your hits
templates (or the hits widgets' own clicks) report clicks, with their positions, and conversions to Seekmere instead
of Algolia:

```js
const sc = instantSearchClient({ key: "srch_…" });
const search = instantsearch({ indexName: "help", searchClient: sc, insights: { insightsClient: sc.insightsClient } });
```

The geoSearch map works too: `aroundLatLng` and `aroundRadius`, `insideBoundingBox` (the map's visible area) and
`insidePolygon`, one each. Name the index's geo field and each hit carries `_geoloc` for its marker:
`instantSearchClient({ key, geo: "location" })`.

The recommendation widgets work through the same client (Algolia Recommend's `getRecommendations`): `relatedProducts`
and `lookingSimilar` from the document's similar items, `trendingItems` from trending (a `facetName` and `facetValue`
narrow it to one category). Equality `facetFilters` narrow both. `frequentlyBoughtTogether` and `trendingFacets`
answer no hits: Search doesn't have those models.

Number fields can also be counted in named buckets, as a price filter lists them (Typesense's range facets):
`facet_range=price:Under 25:..25,25 to 50:25..50,50 and up:50..` on GET, or `"facet_ranges": [{"field": "price",
"ranges": [["Under 25", null, 25], ["25 to 50", 25, 50], ["50 and up", 50, null]]}]`. From is included, to isn't;
buckets may overlap. They come back under `facets.price` in the order asked, each with its count and bounds; filter
by one with `range=price:25..50`.

A results list that shows a title and a price needn't carry each document's body: `fields=title,price` (only
these; `"fields": [...]` as JSON) or `exclude_fields=body` (all but these). Highlights keep to the same fields, and
matching still uses the whole document. InstantSearch's `attributesToRetrieve` maps to `fields`.

Outside InstantSearch, any search takes `stats`: number fields to sum up over every match (`stats=price` on GET, or
`"stats": ["price"]`), and answers `"stats": {"price": {"count", "min", "max", "avg", "sum"}}`.

## 6. Make it better: relevance and analytics

- **Analytics** (`search_analytics`, admins): a week of searches, the top queries, the ones that found nothing, and
  the ones that found results nobody chose. `<seekmere-search>` reports which result was chosen; an app with its own UI
  sends `POST /v1/indexes/{name}/click {"q", "id", "position"}` (a member's token or a search key; `position`, 1 for
  the first result, gives the average click position). A purchase or sign-up that
  came from a search goes to `POST /v1/indexes/{name}/conversion {"q", "id", "user"}` (Seekmere's `conversion(q, id)`),
  and shows per query, as a total and per side of an A/B test.
- **Analytics tags** (Algolia's `analyticsTags`): split analytics by platform or segment. A search sends
  `"analytics_tags": ["ios", "plan:pro"]` (GET: `analytics_tags=ios,plan:pro`; at most 10, each 1 to 64 of
  `a-z 0-9 _ - : .`) and its answer carries a `query_id`: send it with the click or conversion
  (`{"id", "query_id"}`, `q` optional then) and the event counts under the same tags. A search key made with
  `"analytics_tags": ["web"]` tags every search with it; a page can add tags, never drop the key's. Every analytics
  answer takes `tags=ios,web` (all must match): `GET …/analytics`, `…/analytics.csv`, `…/experiment`; and `GET
  /v1/indexes/{name}/analytics/tags?days=7` (MCP `analytics_by_tag`, the console's tag chips and By tag table) gives
  each tag's searches, no-result rate and click-through. Bounded: 100 tag sets and 100 distinct tags per index a day;
  past that a search counts under `other` (in the breakdown, never matched by a filter). A query id is remembered for
  an hour on the server that answered the search.
- **Events** (`recent_events`, admins; `GET /v1/indexes/{name}/events?refused=1`): the latest 100 clicks and
  conversions this server received, each counted or refused with why (an id not in the index, or outside the key's
  filters): check your click wiring before trusting the analytics. In memory: a restart starts it again.
- **Export and usage** (admins): `GET /v1/indexes/{name}/analytics.csv?days=30` (the console's Download CSV, MCP
  `export_analytics`) is every query of the period for a spreadsheet, not just the top twenty. `GET
  /v1/indexes/{name}/usage?months=13` and `GET /v1/orgs/{org}/usage` (the console's Usage, MCP `usage`) give each
  calendar month's searches (a listing and a search key's count), documents written (by writes, a followed
  collection, a bucket or a crawl) and the most documents held. Kept 13 months; an org's months keep its deleted
  indexes' searches.
- **Why a result ranks where it does:** add `explain=true` to a search (members, not search keys). Each hit carries
  its score's breakdown: which words, typo and prefix variants, and synonyms matched in which field, and what each
  counted. The console's search has a "Why?" toggle.
- **Synonyms and rules** (`set_relevance`, admins, applied at once):

  ```sh
  curl -X PUT $SEARCH/v1/indexes/help/relevance -H "authorization: Bearer $TOKEN" -d '{
    "synonyms": [["sign in", "log in"], ["nyc", "new york"]],
    "one_way": [{"from": "phone", "to": ["pixel 9 pro", "galaxy"]}],
    "rules": [{"query": "refund", "pin": ["refund-policy"], "hide": ["old-refunds"]}]
  }'
  ```

  - Synonyms of up to four words match each other both ways, as phrases.
  - A one-way synonym (`one_way`; in the console, a line `phone => pixel 9 pro, galaxy`) lets a search for `from`
    find each of `to`, but not back: "galaxy" doesn't find every phone.
  - A rule pins documents to the top of one exact query, or hides them. `positions` puts a pinned one at a set
    place instead (`{"p6": 3}`: the third hit, Algolia's promote with a position; in the console, `pin p6@3`).
  - A rule can also change the search (Algolia's rule consequences): `filters` (keyword values), `ranges` (numbers,
    `[field, from or null, to or null]`, both ends included), `remove_words`, `replace` (words searched instead:
    `macbook` → `apple laptop`; a contains rule's words within the query) and `boost` (keyword values lifted
    without leaving the rest out, as `optional_filters`). `data` is anything the app shows
    when the rule matches, such as a banner, answered as `user_data` with the hits (InstantSearch's `userData`, at
    most 4 KB). For example, "cheap" anywhere in a query searches the rest under $50 and says so:

    ```json
    {"query": "cheap", "match": "contains", "remove_words": true, "ranges": [["price", null, 50]],
     "data": {"banner": "Everything here is under $50"}}
    ```

    In the console's Rules box: `contains cheap → range price:..50 | remove | data {"banner": "…"}`, or
    `macbook → replace apple laptop | boost brand:Apple`.
  - `redirect` sends a query to a page instead (Algolia's rule redirect): `{"query": "returns", "redirect":
    "/help/returns"}`, an `https://` or `http://` URL or a path starting with `/`. It's answered as `redirect` with
    the hits (which still come back), as `renderingContent.redirect.url` through the InstantSearch client, and the
    search box follows it on Enter after a cancelable `seekmere-redirect` event (cancel it to route the app
    itself). In the console: `returns → redirect /help/returns`.
- **Copying an index's setup** (to staging, another org or a new name): `GET /v1/indexes/{name}/config` (MCP
  `index_config`) returns its fields and relevance in the shape `PUT /v1/indexes/{name}` takes. Edit `org` if
  needed, then PUT it. Documents, sources and keys aren't copied; connect the source again and it fills the copy.

  ```sh
  curl $SEARCH/v1/indexes/help/config -H "authorization: Bearer $TOKEN" |
    curl -X PUT $SEARCH/v1/indexes/help-staging -H "authorization: Bearer $TOKEN" -d @-
  ```

### Try a change on some people first (A/B tests)

Not sure a synonym or a pinned result helps? Try it on a share of the people searching, and compare:

```sh
curl -X PUT $SEARCH/v1/indexes/help/experiment -H "authorization: Bearer $TOKEN" \
  -d '{"variant": {"synonyms": [["refund", "money back"]]}, "share": 20}'
curl $SEARCH/v1/indexes/help/experiment -H "authorization: Bearer $TOKEN"       # results so far
curl -X DELETE "$SEARCH/v1/indexes/help/experiment?keep=true" -H "authorization: Bearer $TOKEN"   # keep the winner
```

Only searches that carry a `user` token take part, and each token always gets the same side. `<seekmere-search>`
sends a token kept for the tab's session; the client takes `new Seekmere({ …, user })`; InstantSearch's `userToken`
is used. Report clicks with the same token. The results give each side's click-through and no-result rates, and a
verdict once each side has 100 searches and the difference is significant (p < 0.05). One experiment at a time; an
admin of the index's org starts and stops it.

## 7. Rebuild without downtime: aliases

Give apps an alias instead of an index's name, as Typesense's aliases and Algolia's moveIndex: `set_alias {alias:
"products", index: "products-v1"}` (`PUT /v1/aliases/products {"index": "products-v1"}`). Searches, multi-searches,
facets, suggestions, clicks and document writes by `products` reach `products-v1`, and a search key made for
`products` searches whichever index it names when it's used. To change fields or reindex, build `products-v2` (`copy_index {index:
"products-v1", to: "products-v2", add_keyword: ["brand"]}`, or `POST /v1/indexes/products-v1/copy {"to":
"products-v2", "definition": …}`, copies the documents and relevance in the background), check it, then `set_alias {alias: "products", index: "products-v2"}`: every app switches at once, and switching back undoes
it. Both indexes' histories record the switch. An alias stays in its org; names are shared with indexes; an index an
alias names can't be deleted until the alias moves; `delete_alias` takes the alias's keys with it. Analytics and
tuning stay per index. An admin of the org; within limits for an agent.

## Limits

- A search returns up to 1,000 hits; with a search key, 100.
- A write takes up to 10,000 documents.
- A facet lists up to 100 values.
- A vector has up to 4,096 dimensions.
- Vector search is exact, which is right up to a few hundred thousand vectors per index.
- Analytics are kept 30 days.
