# POSTDATA Search — Developer Guide

> This guide is served at `https://sales-advancer.postdata.ai/guide`. Every search example below runs against our public demo
> index (≈4,900 products), so you can paste it into a terminal right now. Indexing examples need your own
> private key, which we issue when your account is set up.

## Overview

POSTDATA Search is a hosted search service for websites. You send us your content (products, articles,
listings — any JSON documents), and your visitors get fast, forgiving search over it:

- **Search-as-you-type.** Results update on every keystroke, typically in a few milliseconds of server time.
- **Typo tolerance.** `samsng tv` finds Samsung TVs; `headphnes` finds headphones.
- **Filters and facets.** Narrow by category, brand, price range or any field, with live counts.
- **Sorting, pagination and highlighting** of the matched words.
- **A drop-in widget.** One `<script>` tag adds a complete search box and results to any page.
- **Isolation.** Every website ("tenant") has its own private index. One tenant can never read another
  tenant's data.

There is nothing to install or run. You get two keys, push documents with a simple REST API, and either embed
the widget or call the search endpoint from your own front end.

**Live demo:** [https://sales-advancer.postdata.ai/demo](https://sales-advancer.postdata.ai/demo) · **Interactive API explorer:** [https://sales-advancer.postdata.ai/docs](https://sales-advancer.postdata.ai/docs)

## Quickstart

### 1. Get your keys

When we create your tenant you receive:

| Key | Looks like | Where it may live |
|---|---|---|
| **Private ingest key** | `sk_...` | Your server or CMS backend only. Never in a browser, app or public repo. |
| **Public search key** | `pk_...` | Anywhere, including web pages. It can only search your index. |

The examples below use these shell variables:

```bash
export API=https://sales-advancer.postdata.ai
export PUBLIC_KEY=pk_GYNXkqTwY1eIQa_-N0CZgpTxKaaDzIBm      # the demo index's public key; replace with yours
export PRIVATE_KEY=sk_your_private_key   # yours (not available for the demo)
```

### 2. Index your first documents

```bash
curl -X POST "$API/v1/documents/import" \
  -H "X-API-Key: $PRIVATE_KEY" \
  -H "Content-Type: application/json" \
  -d '[
    {"id": "sku-1001", "title": "Wireless Noise Cancelling Headphones", "brand": "Sony",
     "category": "Audio", "price": 199.99, "image": "https://example.com/img/1001.jpg"},
    {"id": "sku-1002", "title": "Portable Bluetooth Speaker", "brand": "JBL",
     "category": "Audio", "price": 89.00, "image": "https://example.com/img/1002.jpg"}
  ]'
```

```json
{"success": true, "imported": 2, "failed": 0, "errors": []}
```

Documents are searchable immediately.

### 3. Search

This runs against the demo index:

```bash
curl -G "$API/v1/search" \
  -H "X-API-Key: $PUBLIC_KEY" \
  --data-urlencode "q=wireless headphnes" \
  --data-urlencode "facet_by=brand,category" \
  --data-urlencode "per_page=3"
```

The typo `headphnes` still finds headphones. Response, shortened:

```json
{
  "found": 15,
  "out_of": 4887,
  "page": 1,
  "search_time_ms": 1,
  "took_ms": 6.17,
  "cached": false,
  "mode": "smart",
  "hits": [
    {
      "document": {"id": "1753608", "title": "iLive - On-Ear Wireless Headphones - Black", "brand": "iLive",
                   "category": "Audio", "price": 34.99,
                   "image": "https://img.bbystatic.com/BestBuy_US/images/products/1753/1753608_sa.jpg"},
      "highlight": {"title": {"snippet": "iLive - On-Ear <mark>Wireless</mark> <mark>Headphones</mark> - Black"}},
      "text_match": 1157451402721624187
    }
  ],
  "facet_counts": [
    {"field_name": "brand", "counts": [{"value": "Power Acoustik", "count": 3}, {"value": "iLive", "count": 1}]}
  ]
}
```

The same query with `mode=exact` (a typical exact-match site search) finds **0** results.

### 4. Embed the search widget

Paste this into any HTML page. It adds a search box with search-as-you-type (250 ms debounce), facets,
highlighting and response time:

```html
<div id="postdata-search"></div>
<script src="https://sales-advancer.postdata.ai/widget.js"
        data-key="pk_GYNXkqTwY1eIQa_-N0CZgpTxKaaDzIBm"
        data-facets="category,brand,price"
        defer></script>
```

The demo key only answers pages served from its allow-listed origins. For your own site, use your public key
and tell us the domains it will run on (see [CORS](#cors-allowed-origins)).

## Authentication and the two key types

Send the key in the `X-API-Key` header (or `Authorization: Bearer <key>`). For browser `GET` requests the
**public** key may also go in the `key` query parameter, which is what the widget does.

| | Private key `sk_...` | Public key `pk_...` |
|---|---|---|
| Search | ✅ | ✅ |
| Create, update and delete documents, bulk import, export | ✅ | ❌ `403 forbidden_key_type` |
| Read schema and usage | ✅ | ❌ |
| Safe in a browser | ❌ Never | ✅ |
| Allowed in a URL | ❌ (`400 private_key_in_url`) | ✅ |
| Limited by CORS allowed origins | n/a (server-to-server) | ✅ |

- Both keys are tied to **your** index on our side. No parameter can point a key at another tenant's data.
- If a key leaks, ask us to **rotate** it. The old key stops working immediately and you get a new one.
- Keep the private key in an environment variable or secret store. We store only a hash of it, so we cannot
  show it to you again. If it is lost, we rotate it.

### CORS (allowed origins)

Browsers send an `Origin` header. Requests with the public key from an origin that is not on your allow-list
are rejected with `403 origin_not_allowed`. Give us every origin the widget or your front end runs on, e.g.
`https://www.yourshop.com` and `https://yourshop.com`. Server-side requests (no `Origin` header) are not
affected.

## API reference

Base URL: `https://sales-advancer.postdata.ai`. All request and response bodies are JSON unless noted. The
[interactive explorer](https://sales-advancer.postdata.ai/docs) lists the same endpoints and lets you try them.

### Search

#### `GET /v1/search` · `POST /v1/search`

Public or private key.

| Parameter | Description | Example |
|---|---|---|
| `q` | Search text. `*` returns everything (useful with filters). | `q=samsng tv` |
| `query_by` | Fields to search, in priority order. Default: your index default (all text fields). | `title,brand,description` |
| `query_by_weights` | Relative weight per `query_by` field. | `4,2,1` |
| `filter_by` | Filter expression (see below). | `category:=Audio && price:[50..200]` |
| `facet_by` | Fields to return counts for. Numeric range facets are supported. | `brand,category` |
| `sort_by` | Up to 3 sort fields. `_text_match` is relevance. | `price:asc` |
| `page`, `per_page` | Pagination. `per_page` max 100, default 10. | `page=2&per_page=20` |
| `max_facet_values` | Values per facet, default 10. | `20` |
| `facet_query` | Search inside facet values. | `brand:sam` |
| `include_fields`, `exclude_fields` | Trim the returned documents. | `title,price,image` |
| `highlight_fields`, `highlight_full_fields` | Which fields to highlight. | `title` |
| `num_typos` | Typos tolerated per word (0–2), default 2. | `1` |
| `prefix` | Match partial last word (search-as-you-type), default `true`. | `false` |
| `group_by`, `group_limit` | Collapse results by a facet field. | `brand` |
| `mode` | `smart` (default) or `exact`: no typos, whole words only, all words required. Use it to compare. | `exact` |

**Filter syntax**

| Want | Write |
|---|---|
| Exact value | `brand:=Sony` |
| Any of several | ``brand:=[Sony,`Bose Inc`]`` (backticks around values with spaces or commas) |
| Not | `brand:!=Sony` |
| Number range (inclusive) | `price:[50..200]` |
| Comparison | `price:>100`, `rating:>=4` |
| Combine | `category:=Audio && price:<100`, `brand:=Sony \|\| brand:=Bose` |

**Price-range facet example (demo)**

```bash
curl -G "$API/v1/search" -H "X-API-Key: $PUBLIC_KEY" \
  --data-urlencode "q=tv" \
  --data-urlencode "facet_by=price(budget:[0,500],mid:[500,1500],premium:[1500,])" \
  --data-urlencode "filter_by=category:=\`TV & Home Theater\`" \
  --data-urlencode "sort_by=price:asc" --data-urlencode "per_page=5" \
  --data-urlencode "include_fields=title,price"
```

Range facet bands must be continuous (each band starts where the previous one ends).

**POST variant** with a JSON body (same parameters):

```bash
curl -X POST "$API/v1/search" -H "X-API-Key: $PUBLIC_KEY" -H "Content-Type: application/json" \
  -d '{"q": "dishwsher", "filter_by": "price:<1000", "sort_by": "price:desc", "per_page": 5}'
```

**Response fields:** `found` (total matches), `out_of` (documents in index), `page`, `hits[]` (each with
`document`, `highlight`, `text_match`), `facet_counts[]`, `search_time_ms` (engine time), `took_ms` (time
inside our API), `cached` (served from the 30-second cache of identical queries), `mode`.

### Documents (private key)

Every document needs a string `id` (1–255 characters, no backticks). If you send a number it is converted to a string.

#### `POST /v1/documents` — create

```bash
curl -X POST "$API/v1/documents" -H "X-API-Key: $PRIVATE_KEY" -H "Content-Type: application/json" \
  -d '{"id": "sku-1003", "title": "USB-C Charger 65W", "brand": "Anker", "category": "Accessories", "price": 39.99}'
```

`201` returns the stored document. `409 conflict` if the id exists. Add `?upsert=true` to replace instead.

#### `PUT /v1/documents/{id}` — create or replace (upsert)

```bash
curl -X PUT "$API/v1/documents/sku-1003" -H "X-API-Key: $PRIVATE_KEY" -H "Content-Type: application/json" \
  -d '{"title": "USB-C Charger 65W GaN", "brand": "Anker", "category": "Accessories", "price": 34.99}'
```

#### `PATCH /v1/documents/{id}` — partial update

```bash
curl -X PATCH "$API/v1/documents/sku-1003" -H "X-API-Key: $PRIVATE_KEY" -H "Content-Type: application/json" \
  -d '{"price": 29.99}'
```

Only the fields you send change. `404` if the document does not exist.

#### `GET /v1/documents/{id}` — fetch one

```bash
curl "$API/v1/documents/sku-1003" -H "X-API-Key: $PRIVATE_KEY"
```

#### `DELETE /v1/documents/{id}` — delete one

```bash
curl -X DELETE "$API/v1/documents/sku-1003" -H "X-API-Key: $PRIVATE_KEY"
```

#### `DELETE /v1/documents?filter_by=...` — delete many

```bash
curl -X DELETE -G "$API/v1/documents" -H "X-API-Key: $PRIVATE_KEY" --data-urlencode "filter_by=category:=Discontinued"
```

```json
{"num_deleted": 12}
```

#### `POST /v1/documents/import` — bulk import

Up to **10,000 documents per request**. Send either a JSON array (`Content-Type: application/json`) or
JSON Lines, one document per line (`Content-Type: application/x-ndjson`).

| `action` | Behaviour |
|---|---|
| `upsert` (default) | Create new ids, replace existing ones. Best for full or periodic syncs. |
| `create` | Fail for ids that already exist. |
| `update` | Partially update existing ids; fail for unknown ids. |

```bash
curl -X POST "$API/v1/documents/import?action=upsert" -H "X-API-Key: $PRIVATE_KEY" \
  -H "Content-Type: application/x-ndjson" --data-binary @products.jsonl
```

```json
{"success": false, "imported": 998, "failed": 2,
 "errors": [{"index": 17, "id": "sku-77", "error": "Field `price` must be a float."}]}
```

Bad documents don't block the rest of the batch. Check `failed` and `errors` (the first 100 are listed). If
the batch would push you over your plan's record limit, the **whole request** is rejected with `402`. For
large catalogues, send batches of 1,000–5,000.

#### `GET /v1/documents/export` — export everything

Streams all documents as JSON Lines. Your data is always yours to take with you.

```bash
curl "$API/v1/documents/export" -H "X-API-Key: $PRIVATE_KEY" -o export.jsonl
```

### Schema, settings and usage (private key)

#### `GET /v1/schema`

Lists the fields in your index, their types, which are facets, and the document count.

#### `PATCH /v1/schema` — add or drop fields, set default search fields

```bash
curl -X PATCH "$API/v1/schema" -H "X-API-Key: $PRIVATE_KEY" -H "Content-Type: application/json" \
  -d '{"fields": [{"name": "color", "type": "string", "facet": true}],
       "default_query_by": "title,brand,color,description"}'
```

To drop a field: `{"fields": [{"name": "color", "drop": true}]}`.

#### `GET /v1/usage`

```json
{"tenant_id": "yourshop", "plan": "starter", "month": "2026-11",
 "records": 812, "max_records": 1000, "peak_records": 840, "records_pct": 81.2,
 "searches": 4120, "monthly_searches": 20000, "searches_pct": 20.6, "ingest_operations": 37}
```

### Health

#### `GET /health`

No key needed. Returns `200 {"status": "ok", ...}` or `503` if a component is degraded.

## Document format and field types

A document is a flat or nested JSON object. Field types are detected automatically the first time a field
appears. For fields you want to filter, facet or sort on, ask us to declare them explicitly when your index is
created, or add them with `PATCH /v1/schema`.

| Type | JSON example | Notes |
|---|---|---|
| `string` | `"title": "Laptop"` | Full-text searchable. |
| `string[]` | `"tags": ["sale", "new"]` | Arrays of strings; facetable. |
| `int32`, `int64` | `"stock": 12` | Filter, sort, facet. |
| `float` | `"price": 19.99` | Filter, sort, range facets. |
| `bool` | `"in_stock": true` | Filter with `in_stock:true`. |
| `geopoint` | `"location": [43.65, -79.38]` | Lat/long for geo filters and sorting. |
| `object`, `object[]` | `"specs": {"ram": "16GB"}` | Nested fields addressable as `specs.ram`. |

Field options: `facet` (enable counts and exact filtering), `optional` (may be missing), `index: false`
(store and return, but don't search, e.g. image URLs), `sort` (enable sorting on strings).

Recommended product schema (what the demo uses):

```json
[
  {"name": "title",       "type": "string"},
  {"name": "description", "type": "string"},
  {"name": "brand",       "type": "string", "facet": true},
  {"name": "category",    "type": "string", "facet": true},
  {"name": "price",       "type": "float",  "facet": true},
  {"name": "image",       "type": "string", "index": false, "optional": true},
  {"name": "url",         "type": "string", "index": false, "optional": true}
]
```

Each document may be up to **100 KB**. Once a field's type is set, send that type consistently. A string in a
`float` field is rejected with a per-document error.

## Widget reference

```html
<div id="postdata-search"></div>
<script src="https://sales-advancer.postdata.ai/widget.js" data-key="pk_YOUR_PUBLIC_KEY" defer></script>
```

| Attribute | Default | Purpose |
|---|---|---|
| `data-key` | required | Your public key. |
| `data-target` | `#postdata-search` | CSS selector of the container. |
| `data-facets` | none | Facet sidebar, e.g. `category,brand,price`. |
| `data-price-field` | `price` | Numeric field shown as price and as range facet. |
| `data-price-ranges` | `0-25,25-100,100-250,250-500,500-1000,1000-` | Continuous price bands. |
| `data-title-field`, `data-description-field`, `data-image-field`, `data-url-field`, `data-brand-field`, `data-category-field` | `title`, `description`, `image`, `url`, `brand`, `category` | Map your field names. If a document has a `url`, its card links there. |
| `data-query-by` | index default | Fields to search. |
| `data-per-page` | `12` | Results per page. |
| `data-placeholder` | `Search products…` | Input placeholder. |
| `data-currency` | `$` | Currency symbol. |
| `data-compare` | `false` | `true` shows a toggle comparing with exact-match search side by side. |
| `data-show-timing` | `true` | Show engine and round-trip time in ms. |
| `data-debounce` | `250` | Milliseconds to wait after typing stops. |
| `data-theme` | `light` | `light`, `dark` or `auto`. |
| `data-accent` | `#4f46e5` | Accent colour. |

The widget renders inside a Shadow DOM, so your site's CSS won't break it and its CSS won't leak into your page.
For full control, call it from JavaScript:

```html
<script src="https://sales-advancer.postdata.ai/widget.js" defer></script>
<script>
  window.addEventListener("DOMContentLoaded", function () {
    var search = PostdataSearch.mount("#my-search", { key: "pk_YOUR_PUBLIC_KEY", facets: "brand,price", perPage: 24 });
    // search.search("headphones");  // run a query programmatically
  });
</script>
```

Or skip the widget and call `GET /v1/search` from your own front end with the public key.

## Plans and limits

| Plan | Indexed records | Searches per month (fair use) | Search rate per key | Ingest rate per key |
|---|---|---|---|---|
| Starter | up to 1,000 | 20,000 | 10/s (burst 20) | 10/s (burst 30) |
| Growth | up to 10,000 | 100,000 | 20/s (burst 40) | 20/s (burst 60) |
| Business | up to 50,000 | 500,000 | 50/s (burst 100) | 50/s (burst 150) |

> **Pricing:** _[PLACEHOLDER — to be provided by POSTDATA Search]_

- **Records** are the number of documents in your index at any moment. We also record the **monthly peak**.
  Adding documents beyond your plan returns `402 record_limit_exceeded`. Updating or re-upserting existing
  documents is always allowed.
- **Searches** are counted per tenant per calendar month (UTC), including repeated identical queries served
  from cache. At the monthly allowance, search returns `429 search_quota_exceeded` until the 1st of the next
  month or an upgrade. Search-as-you-type widgets wait 250 ms after typing stops, so one typed query usually
  counts as 1–3 searches.
- **Rate limits** protect everyone's latency. Above them you get `429 rate_limited` with a `Retry-After`
  header (seconds).
- Bulk import: 10,000 documents per request. Document size: 100 KB. `per_page`: 100.

## Errors

Errors always look like this:

```json
{"error": {"code": "record_limit_exceeded", "message": "The Starter plan allows 1000 records. ...",
           "details": {"plan": "starter", "max_records": 1000, "current_records": 990, "new_records_in_request": 25}}}
```

| HTTP | `code` | Meaning and what to do |
|---|---|---|
| 400 | `invalid_request`, `invalid_json`, `invalid_document`, `invalid_schema` | Fix the request; `message` says what is wrong. |
| 400 | `private_key_in_url` | Private keys must go in a header. Rotate the key if the URL was logged. |
| 400 | `no_searchable_fields` | Index documents first, or pass `query_by`. |
| 401 | `missing_api_key`, `invalid_api_key` | Send a valid key. Rotated keys are invalid immediately. |
| 402 | `record_limit_exceeded` | Plan record limit reached. Delete documents or upgrade. |
| 403 | `forbidden_key_type` | The public key was used for a private-only endpoint. |
| 403 | `origin_not_allowed` | The page's origin is not on your CORS allow-list. |
| 403 | `tenant_suspended` | Account suspended. Contact support. |
| 404 | `not_found` | Document or endpoint does not exist. |
| 409 | `conflict` | Document id already exists (on create). |
| 413 | `document_too_large`, `batch_too_large` | Split the document or batch. |
| 429 | `rate_limited` | Too many requests per second. Wait `Retry-After` seconds. |
| 429 | `search_quota_exceeded` | Monthly search allowance used up. |
| 502 / 503 | `engine_error`, `engine_unavailable` | Temporary. Retry with backoff. |

## Data and security

- **Tenant isolation.** Each tenant has its own search index. Your keys are bound to your index on our server.
  The index is never chosen by a request parameter, and query features that could reference other indexes
  are blocked. An automated test proves on every deployment that one tenant's public and private keys cannot
  find, read, change or delete another tenant's documents.
- **Keys.** Private keys are stored only as a SHA-256 hash. Public keys are search-only and restricted to your
  allowed origins. Keys can be rotated at any time.
- **Encryption in transit.** All traffic is HTTPS (TLS certificates from Let's Encrypt, renewed
  automatically; HSTS enabled). The search engine itself is not reachable from the internet.
- **Hosting location.** Hetzner Cloud, Ashburn, Virginia, USA (us-east).
- **Backups.** A full snapshot of all indexes and account data is taken daily and kept for 7 days.
  _[PLACEHOLDER: off-site backup location and retention, once configured.]_
- **Your data stays yours.** Export everything at any time with `GET /v1/documents/export`. On termination
  your index is deleted. _[PLACEHOLDER: deletion timeline and backup expiry wording.]_
- **What we store.** Only the documents you send, plus per-month counters (searches, peak records). We don't
  log search queries beyond standard web-server access logs, which are rotated. _[PLACEHOLDER: confirm log
  retention period.]_
- _[PLACEHOLDER: Data Processing Agreement / privacy policy link.]_

## Support

- Email: support@postdata.ai _[PLACEHOLDER: confirm address]_
- Support hours: _[PLACEHOLDER]_
- Status page: _[PLACEHOLDER]_

Include your tenant id and, for API problems, the request (without the private key) and the full error response.

## Service level (SLA)

> _[PLACEHOLDER — to be completed by POSTDATA Search. Nothing in this section is a commitment yet.]_

| Item | Commitment |
|---|---|
| Monthly uptime target | _[PLACEHOLDER]_ |
| Measurement method | _[PLACEHOLDER]_ |
| Scheduled maintenance window and notice | _[PLACEHOLDER]_ |
| Support response time (by severity) | _[PLACEHOLDER]_ |
| Service credits | _[PLACEHOLDER]_ |
| Exclusions | _[PLACEHOLDER]_ |
