> ## Documentation Index
> Fetch the complete documentation index at: https://nikita-shkoda.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Client

> Thin wrapper around the official typesense Ruby gem. Single-search and federated multi-search with URL/common cache knobs and normalized errors.

Related: <a href="/projects/search-engine-for-typesense/v30/relation">Relation</a>, <a href="/projects/search-engine-for-typesense/v30/multi-search">Multi-search</a>, <a href="/projects/search-engine-for-typesense/v30/dx">DX</a>

## SearchEngine::Client

A thin wrapper around the official <code>typesense</code> Ruby gem that provides single-search and federated multi-search. It enforces that cache knobs live in URL/common params (never in per-search bodies) and normalizes gem/network failures into <code>SearchEngine::Errors</code>.

### Usage

Prefer `SearchEngine.client` to get the configured client instance. It respects
`SearchEngine.config.client` when set, returns `OfflineClient` in test mode, or
creates a new `Client` instance:

```ruby theme={null}
client = SearchEngine.client
client.search(collection: "books", params: { q: "milk", query_by: "name" },
              url_opts: { use_cache: true })
client.multi_search(
  searches: [
    { collection: "books", q: "milk", query_by: "name", per_page: 5 },
    { collection: "authors", q: "mil", query_by: "name", per_page: 3 }
  ],
  url_opts: { use_cache: true, cache_ttl: 30 }
)
```

You can also instantiate `SearchEngine::Client` directly when you need a specific
instance:

```ruby theme={null}
client = SearchEngine::Client.new
client.search(collection: "books", params: { q: "milk", query_by: "name" },
              url_opts: { use_cache: true })
```

Top-level convenience returning raw:

```ruby theme={null}
SearchEngine.multi_search_raw(
  common: { query_by: SearchEngine.config.default_query_by }
) do |m|
  m.add :books, SearchEngine::Book.per(5)
  m.add :authors, SearchEngine::Author.per(3)
end

# Clear server-side cache (Typesense `/operations/cache/clear`)
SearchEngine::Cache.clear
```

<Info>
  Note: The default Typesense client connection timeout is 60 minutes, to avoid aborting long-running writes. You can override it, and you can introduce retry jitter by using a Range for <code>retries\[:backoff]</code>. See <a href="/projects/search-engine-for-typesense/v30/configuration#timeouts--retries">Configuration</a>.
</Info>

Example override:

```ruby theme={null}
SearchEngine.configure do |c|
  c.timeout_ms = 3_600_000
  c.retries = { attempts: 3, backoff: 10.0..60.0 }
end
```

### Cache management

* <code>SearchEngine::Cache.clear</code> issues a <code>POST /operations/cache/clear</code>
  via the client and returns the symbolized Typesense response. Call it after
  large imports or schema changes when you need fresh cached results immediately.
* Emits <code>search\_engine.cache.clear</code> (see <a href="/projects/search-engine-for-typesense/v30/observability">Observability</a>)
  so subscribers/loggers capture cadence and duration; uses <code>SearchEngine.client</code>
  so injected clients and test mode are honored.
* Reference: <a href="https://typesense.org/docs/29.0/api/cluster-operations.html#clear-cache" target="_blank">Typesense cluster operations → Clear cache</a>.

### Operations helper (`SearchEngine.operations`)

Use the convenience wrapper when you need instrumented, redacted operational calls (no request body needed):

```ruby theme={null}
SearchEngine.operations.metrics   # GET /metrics.json
SearchEngine.operations.stats     # GET /stats.json
SearchEngine.operations.health    # GET /health
```

* Accepts optional `client:` for dependency injection; otherwise uses
  `SearchEngine.client` (respects injected clients, test mode, or builds a new
  instance).
* Emits `search_engine.operations.*` events; payloads are redacted and safe for dashboards/health checks.

### Client helper (`SearchEngine.client`)

Use `SearchEngine.client` to access the configured client instance. It follows
this precedence:

1. Returns `SearchEngine.config.client` if explicitly set (e.g., `StubClient`)
2. Returns `SearchEngine::Test::OfflineClient` if `test_mode?` is true
3. Otherwise creates and returns a new `SearchEngine::Client` instance

This helper ensures consistent client access across the codebase and respects
test mode automatically.

### Request flow

```mermaid theme={null}
sequenceDiagram
  participant App
  participant SE as SearchEngine::Client
  participant TS as Typesense::Client
  participant API as Typesense HTTP API
  App->>SE: search(collection, params, url_opts)
  SE->>SE: validate & merge defaults
  SE->>TS: call search (URL/common cache params)
  TS->>API: POST /collections/:c/documents/search?use_cache&cache_ttl
  API-->>TS: 2xx JSON or non‑2xx
  TS-->>SE: normalized response or error
  alt success
    SE-->>App: parsed JSON
  else error
    SE-->>App: raise SearchEngine::Errors::*
  end
```

### URL/common params vs body

| Parameter   | Location    |
| ----------- | ----------- |
| `use_cache` | URL/Common  |
| `cache_ttl` | URL/Common  |
| `q`         | Body/Params |
| `query_by`  | Body/Params |
| `filter_by` | Body/Params |
| `per_page`  | Body/Params |

### Errors

Public errors are exposed via <code>SearchEngine::Errors</code>:

* <code>Timeout</code>: request exceeded timeout budget
* <code>Connection</code>: DNS/socket/TLS/connect failures
* <code>Api</code>: non‑2xx Typesense responses (carries <code>status</code> and <code>body</code>)
* <code>InvalidParams</code>: wrapper pre‑call validation problems

See <code>lib/search\_engine/errors.rb</code> for details.

### Internals boundary

* <code>SearchEngine::Client::RequestBuilder</code> assembles concrete request shapes (HTTP method, path, body) from compiled params. It has no network concerns.
* <code>SearchEngine::Client::HttpAdapter</code> executes an assembled request using the injected <code>Typesense::Client</code>. It has no knowledge of Typesense domain semantics.
* These roles clarify responsibilities; there is no change to public behavior.

#### Troubleshooting

* <strong>Timeout / Connection</strong>: Check host/port/protocol and network reachability.
* <strong>API errors</strong>: Inspect <code>status</code> and server body. 4xx are not retried; 5xx/429 may be transient.

## API Reference

### Collection Management

* <code>create\_collection(schema)</code>: Create a physical collection.
* <code>update\_collection(name, schema)</code>: PATCH an existing collection (add/drop fields) without reindexing when Typesense deems the change compatible.
* <code>delete\_collection(name, timeout\_ms: nil)</code>: Delete a collection.
* <code>retrieve\_collection\_schema(name)</code>: Fetch schema for a physical collection.
* <code>list\_collections</code>: List all collections.
* <code>upsert\_alias(alias, physical)</code>: Point an alias to a physical collection.
* <code>resolve\_alias(alias)</code>: Get the physical name for an alias.

### Document Operations

* <code>create\_document(collection:, document:)</code>: Create a single document.
* <code>retrieve\_document(collection:, id:)</code>: Fetch a document by ID.
* <code>update\_document(collection:, id:, fields:)</code>: Partially update a document.
* <code>delete\_document(collection:, id:)</code>: Delete a document by ID.
* <code>import\_documents(collection:, jsonl:, action: :upsert)</code>: Bulk import.
* <code>delete\_documents\_by\_filter(collection:, filter\_by:)</code>: Delete by query.
* <code>update\_documents\_by\_filter(collection:, filter\_by:, fields:)</code>: Update by query.

### Server Operations

* <code>health</code>: Check server health.
* <code>metrics</code>: Retrieve metrics (JSON).
* <code>stats</code>: Retrieve stats (JSON).
* <code>list\_api\_keys</code>: List configured API keys.
* <code>clear\_cache</code>: Clear server-side cache.

### Synonyms & Stopwords

* <code>synonyms\_upsert(collection:, id:, terms:)</code>
* <code>synonyms\_list(collection:)</code>
* <code>synonyms\_get(collection:, id:)</code>
* <code>synonyms\_delete(collection:, id:)</code>
* <code>stopwords\_upsert(collection:, id:, terms:)</code>
* <code>stopwords\_list(collection:)</code>
* <code>stopwords\_get(collection:, id:)</code>
* <code>stopwords\_delete(collection:, id:)</code>

Backlinks: <a href="/projects/search-engine-for-typesense/v30/index">Home</a>

See <a href="/projects/search-engine-for-typesense/v30/observability">Observability</a> for emitted events and compact logging.
