Saltar al contenido principal
Versión: Estable (v4.x)

Examples and extensions

Traducción Beta No Oficial

Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →

These examples are interactive. Click a button to open the modal and try a query.

Búsqueda básica por palabras clave

Use the default experience with your index credentials. This works great for typical docs, blogs, and any site with a DocSearch-compliant index.

<DocSearch
appId="PMZUYBQDAK"
apiKey="24b09689d5b4223813d9b8e48563c8f6"
indexName="docsearch"
insights={true}
translations={{ button: { buttonText: 'keyword search (demo)' } }}
/>

id: examples title: Ejemplos y extensiones description: Demostraciones en vivo que muestran cómo usar y extender DocSearch más allá de casos de uso exclusivos de documentación.

Ask AI: Respuestas asistidas por IA

Add Algolia Ask AI to get synthesized answers grounded in your indexed content. You can scope the LLM context using searchParameters like facetFilters, filters, attributesToRetrieve,restrictSearchableAttributes, and distinct.

<DocSearch
appId="PMZUYBQDAK"
apiKey="24b09689d5b4223813d9b8e48563c8f6"
indexName="docsearch"
askAi={{
assistantId: 'askAIDemo',
searchParameters: {
facetFilters: ['language:en'],
},
}}
insights={true}
translations={{ button: { buttonText: 'search with askai (demo)' } }}
/>

id: examples title: Ejemplos y extensiones description: Demostraciones en vivo que muestran cómo usar y extender DocSearch más allá de casos de uso exclusivos de documentación.

Panel lateral: chat de IA persistente

El panel lateral ofrece una interfaz de chat persistente anclada al costado de la página, ideal para sitios de documentación donde los usuarios quieren hacer preguntas de seguimiento sin perder su lugar. Busca el botón en la esquina inferior derecha de la pantalla para probar la demostración.

<DocSearchSidepanel
appId="PMZUYBQDAK"
apiKey="24b09689d5b4223813d9b8e48563c8f6"
indexName="docsearch"
assistantId="askAIDemo"
/>

id: examples title: Ejemplos y extensiones description: Demostraciones en vivo que muestran cómo usar y extender DocSearch más allá de casos de uso exclusivos de documentación.

API Componible: DocSearchButton + DocSearchModal

Usa la API Componible para renderizar el botón y el modal como componentes separados. Esto te da control explícito sobre dónde se renderiza cada elemento y cuándo se carga el código del modal.

import { DocSearch } from '@docsearch/core';
import { DocSearchButton, DocSearchModal } from '@docsearch/modal';

import '@docsearch/css/style.css';

<DocSearch>
<DocSearchButton translations={{ buttonText: 'Composable search (demo)' }} />
<DocSearchModal
appId="PMZUYBQDAK"
indexName="docsearch"
apiKey="a00716d83c64f6c61905c078b7d5ab66"
askAi={{
assistantId: 'ccdec697-e3fe-465b-a1c3-657e7bf18aef',
agentStudio: true,
}}
/>
</DocSearch>;

id: examples title: Ejemplos y extensiones description: Demostraciones en vivo que muestran cómo usar y extender DocSearch más allá de casos de uso exclusivos de documentación.

Renderizado personalizado de resultados (hitComponent)

Replace the default hit markup to match your brand and layout. Below is a minimal example of a custom component.

function CustomHit({ hit }) {
// render a compact, branded hit card
return (
<a
href={hit.url}
style={{ display: 'block', padding: '12px 16px', textDecoration: 'none' }}
>
<div style={{ display: 'flex', gap: 12 }}>
<div
style={{
width: 40,
height: 40,
backgroundColor: '#e3f2fd',
borderRadius: 6,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
fontWeight: 600,
color: '#1976d2',
}}
>
{hit.type?.toUpperCase?.() || 'DOC'}
</div>
<div style={{ minWidth: 0 }}>
<div
style={{
fontWeight: 600,
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
{hit.hierarchy?.lvl1 || 'untitled'}
</div>
{hit.hierarchy?.lvl2 && (
<div
style={{
color: '#666',
whiteSpace: 'nowrap',
overflow: 'hidden',
textOverflow: 'ellipsis',
}}
>
{hit.hierarchy.lvl2}
</div>
)}
{hit.content && (
<div style={{ color: '#888', marginTop: 4 }}>{hit.content}</div>
)}
</div>
</div>
</a>
);
}

<DocSearch
appId="PMZUYBQDAK"
apiKey="24b09689d5b4223813d9b8e48563c8f6"
indexName="docsearch"
hitComponent={CustomHit}
insights={true}
translations={{ button: { buttonText: 'custom hits (demo)' } }}
/>;

id: examples title: Ejemplos y extensiones description: Demostraciones en vivo que muestran cómo usar y extender DocSearch más allá de casos de uso exclusivos de documentación.

Abrir enlaces en nuevas pestañas

Por defecto, DocSearch abre los enlaces de resultados en la misma ventana. Si necesitas que se abran en nuevas pestañas, debes usar tanto un hitComponent personalizado como la propiedad navigator para manejar consistentemente clics y navegación por teclado.

// Custom hit component with target="_blank"
function HitWithNewTab({ hit, children }) {
return (
<a href={hit.url} target="_blank" rel="noopener noreferrer">
{children}
</a>
);
}

// Navigator configuration to handle keyboard navigation
const newTabNavigator = {
navigate: ({ itemUrl }) => window.open(itemUrl, '_blank'),
navigateNewTab: ({ itemUrl }) => window.open(itemUrl, '_blank'),
navigateNewWindow: ({ itemUrl }) => window.open(itemUrl, '_blank'),
};

<DocSearch
appId="PMZUYBQDAK"
apiKey="24b09689d5b4223813d9b8e48563c8f6"
indexName="docsearch"
hitComponent={HitWithNewTab}
navigator={newTabNavigator}
insights={true}
translations={{ button: { buttonText: 'open in new tabs (demo)' } }}
/>;

advertencia

Nota: Usar solo hitComponent con target="_blank" funciona para clics de ratón, pero la navegación por teclado (flechas + Enter) requiere la propiedad navigator para abrir enlaces en nuevas pestañas consistentemente.


id: examples title: Ejemplos y extensiones description: Demostraciones en vivo que muestran cómo usar y extender DocSearch más allá de casos de uso exclusivos de documentación.

Trae tu propia estructura de datos con transformItems

DocSearch is not limited to DocSearch-like records. Use transformItems to adapt any record shape into the internal structure DocSearch expects. This lets you build search for apps, help centers, changelogs, or any custom content.

The snippet below maps a non-standard record to the internal format. Try it live:

<DocSearch
appId="PMZUYBQDAK"
apiKey="24b09689d5b4223813d9b8e48563c8f6"
indexName="crawler_doc"
askAi={{ assistantId: 'askAIDemo' }}
searchParameters={{
attributesToRetrieve: ['*'],
attributesToSnippet: ['*'],
hitsPerPage: 20,
}}
transformItems={(items) =>
items.map((item) => ({
objectID: item.objectID,
content: item.content ?? '',
url: item.domain + item.path,
hierarchy: {
lvl0: (item.breadcrumb || []).join(' > ') ?? '',
lvl1: item.h1 ?? '',
lvl2: item.h2 ?? '',
lvl3: null,
lvl4: null,
lvl5: null,
lvl6: null,
},
url_without_anchor: item.domain + item.path,
type: 'content',
anchor: null,
_highlightResult: item._highlightResult,
_snippetResult: item._snippetResult,
}))
}
insights={true}
translations={{ button: { buttonText: 'transform items (demo)' } }}
/>

id: examples title: Ejemplos y extensiones description: Demostraciones en vivo que muestran cómo usar y extender DocSearch más allá de casos de uso exclusivos de documentación.

Consejos

  • Instrumentación: activa insights para enviar análisis de uso e iterar sobre la relevancia.

  • Ask AI scoping: use facetFilters, filters, attributesToRetrieve, restrictSearchableAttributes, and distinct to control AI context and improve answer quality.

  • Customization: use hitComponent, transformItems, and translations to make DocSearch feel native to any product surface.