示例与扩展
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
这些示例支持交互操作。点击按钮打开搜索模态框并尝试输入查询。
基本关键词搜索
使用默认配置搭配您的索引凭证即可。适用于典型文档站点、博客以及任何符合 DocSearch 索引规范的网站。
<DocSearch
appId="PMZUYBQDAK"
apiKey="24b09689d5b4223813d9b8e48563c8f6"
indexName="docsearch"
insights={true}
translations={{ button: { buttonText: 'keyword search (demo)' } }}
/>
Ask AI:AI 辅助回答
添加 Algolia AskAI 可获取基于索引内容生成的综合答案。通过 searchParameters 中的 facetFilters、filters、attributesToRetrieve、restrictSearchableAttributes 和 distinct 参数限定 LLM 上下文范围。
<DocSearch
appId="PMZUYBQDAK"
apiKey="24b09689d5b4223813d9b8e48563c8f6"
indexName="docsearch"
askAi={{
assistantId: 'askAIDemo',
searchParameters: {
facetFilters: ['language:en'],
},
}}
insights={true}
translations={{ button: { buttonText: 'search with askai (demo)' } }}
/>
自定义命中结果渲染 (hitComponent)
替换默认命中结果标记以适配您的品牌风格和布局。以下是一个自定义组件的最小实现示例。
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)' } }}
/>;
在新标签页打开链接
默认情况下,DocSearch 在当前窗口打开搜索结果链接。若需在新标签页打开,必须同时使用自定义 hitComponent 和 navigator 属性来统一处理点击与键盘导航。
// 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)' } }}
/>;
警告
注意:仅使用带 target="_blank" 的 hitComponent 可支持鼠标点击,但键盘导航(方向键 + Enter)需配合 navigator 属性才能在新标签页中稳定打开链接。