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

# How It Works

> Understanding DocSearch's architecture and search flow

DocSearch is built on Algolia's powerful search infrastructure, combining a web crawler, search API, and customizable UI components to deliver instant search for documentation sites.

## Architecture Overview

DocSearch consists of three main components that work together:

<Steps>
  <Step title="Web Crawler">
    The Algolia Crawler extracts content from your documentation pages using configurable CSS selectors and builds a searchable index.
  </Step>

  <Step title="Algolia Search Index">
    Your documentation content is stored in an Algolia index, optimized for fast, typo-tolerant search with ranking and filtering capabilities.
  </Step>

  <Step title="Search UI Components">
    React or JavaScript components integrate into your site, providing a modal search interface with keyboard shortcuts and AI-powered answers.
  </Step>
</Steps>

## Search Flow

When a user searches your documentation, here's what happens:

```mermaid theme={null}
sequenceDiagram
    User->>DocSearch UI: Types query
    DocSearch UI->>Algolia API: Search request
    Algolia API->>Index: Query processing
    Index->>Algolia API: Ranked results
    Algolia API->>DocSearch UI: JSON response
    DocSearch UI->>User: Display results
```

### 1. Query Input

As users type in the search box, DocSearch sends queries to Algolia with debouncing to optimize performance:

```tsx theme={null}
import { DocSearch } from '@docsearch/react';

function App() {
  return (
    <DocSearch
      appId="YOUR_APP_ID"
      apiKey="YOUR_SEARCH_API_KEY"
      indexName="YOUR_INDEX_NAME"
    />
  );
}
```

### 2. Search Processing

Algolia processes the query using:

* **Typo tolerance**: Handles misspellings automatically
* **Prefix matching**: Returns results as you type
* **Ranking algorithm**: Orders results by relevance
* **Highlighting**: Emphasizes matching terms

### 3. Results Rendering

Results are grouped by hierarchy level (headings, content) and displayed in the modal:

```typescript theme={null}
interface DocSearchHit {
  objectID: string;
  content: string | null;
  url: string;
  hierarchy: {
    lvl0: string | null;
    lvl1: string | null;
    lvl2: string | null;
    lvl3: string | null;
    lvl4: string | null;
    lvl5: string | null;
    lvl6: string | null;
  };
}
```

## Component Integration

DocSearch integrates with your site through a React provider pattern:

```tsx theme={null}
import { DocSearch as DocSearchProvider } from '@docsearch/core';
import { DocSearchModal } from '@docsearch/react';

function DocSearchComponent(props) {
  return (
    <DocSearchProvider {...props}>
      <DocSearchInner {...props} />
    </DocSearchProvider>
  );
}
```

The provider manages:

* **Modal state**: Open/closed status
* **Keyboard shortcuts**: Cmd+K, / to open
* **Search queries**: Input and results
* **Navigation**: Moving between results
* **Ask AI state**: Toggle between search and AI modes

<Note>
  The DocSearch component is fully accessible with ARIA attributes and keyboard navigation support.
</Note>

## State Management

DocSearch uses React hooks to manage state:

```typescript theme={null}
export type DocSearchState = 'modal-askai' | 'modal-search' | 'ready' | 'sidepanel';

export interface DocSearchContext {
  docsearchState: DocSearchState;
  isAskAiActive: boolean;
  isModalActive: boolean;
  openModal: () => void;
  closeModal: () => void;
  onAskAiToggle: (active: boolean) => void;
}
```

### State Transitions

<Accordion title="State Diagram">
  ```
  ready → modal-search (user opens search)
  modal-search → modal-askai (user activates Ask AI)
  modal-askai → modal-search (user returns to search)
  modal-search → ready (user closes modal)
  modal-search → sidepanel (Ask AI on desktop with sidepanel support)
  ```
</Accordion>

## Programmatic API

You can control DocSearch programmatically using refs:

```tsx theme={null}
import { DocSearch } from '@docsearch/react';
import { useRef } from 'react';
import type { DocSearchRef } from '@docsearch/core';

function App() {
  const searchRef = useRef<DocSearchRef>(null);

  return (
    <>
      <button onClick={() => searchRef.current?.open()}>
        Open Search
      </button>
      <button onClick={() => searchRef.current?.openAskAi()}>
        Ask AI
      </button>
      <DocSearch
        ref={searchRef}
        appId="YOUR_APP_ID"
        apiKey="YOUR_SEARCH_API_KEY"
        indexName="YOUR_INDEX_NAME"
      />
    </>
  );
}
```

### Available Methods

<CodeGroup>
  ```typescript Ref API theme={null}
  interface DocSearchRef {
    /** Opens the search modal */
    open: () => void;
    /** Closes the search modal */
    close: () => void;
    /** Opens Ask AI mode */
    openAskAi: (initialMessage?: InitialAskAiMessage) => void;
    /** Opens the sidepanel directly */
    openSidepanel: (initialMessage?: InitialAskAiMessage) => void;
    /** Component ready state */
    readonly isReady: boolean;
    /** Modal open state */
    readonly isOpen: boolean;
    /** Sidepanel open state */
    readonly isSidepanelOpen: boolean;
  }
  ```
</CodeGroup>

## Search Parameters

Customize search behavior with parameters:

```typescript theme={null}
import { DocSearch } from '@docsearch/react';

<DocSearch
  appId="YOUR_APP_ID"
  apiKey="YOUR_SEARCH_API_KEY"
  indexName="YOUR_INDEX_NAME"
  searchParameters={{
    hitsPerPage: 20,
    attributesToRetrieve: ['hierarchy', 'content', 'url'],
    distinct: true,
    facetFilters: ['version:v3', 'language:en'],
  }}
/>
```

<Info>
  Search parameters are passed directly to the Algolia search client for advanced query customization.
</Info>

## Multi-Index Search

Search across multiple indices for versioned documentation:

```tsx theme={null}
<DocSearch
  appId="YOUR_APP_ID"
  apiKey="YOUR_SEARCH_API_KEY"
  indices={[
    {
      name: 'docs_v4',
      searchParameters: { facetFilters: ['version:v4'] }
    },
    {
      name: 'docs_v3',
      searchParameters: { facetFilters: ['version:v3'] }
    }
  ]}
/>
```

## Performance Optimizations

DocSearch includes several optimizations:

* **Debounced queries**: Reduces API calls while typing
* **Request caching**: Stores recent results
* **Lazy loading**: Components load on demand
* **Virtual scrolling**: Efficient rendering of large result sets
* **Prefetching**: Loads resources on hover

<Warning>
  The DocSearch component requires a valid Algolia API key and app ID. Keep your search API key public-safe (search-only permissions).
</Warning>

## Next Steps

<CardGroup cols={2}>
  <Card title="Indexing" icon="spider-web" href="/concepts/indexing">
    Learn how the crawler indexes your documentation
  </Card>

  <Card title="Ask AI" icon="sparkles" href="/concepts/ask-ai">
    Enable AI-powered answers for your search
  </Card>

  <Card title="Styling" icon="palette" href="/concepts/styling">
    Customize the appearance of DocSearch
  </Card>

  <Card title="API Reference" icon="code" href="/api/configuration">
    Explore all configuration options
  </Card>
</CardGroup>
