Algolia search integration

From findscripter/everything-skills · View interactive version

Algolia search integration is an AI agent skill from the GitHub repository findscripter/everything-skills. 当为 Web/前端应用接入 Algolia 即时搜索、构建索引同步管道或调优相关性时使用;做 InstantSearch/SSR 集成、批量与增量索引、API Key 安全分发、可搜索属性与自定义排序、分面过滤与自动补全的落地方案;不适用于自建 ES/向量检索或非 Algolia 搜索后端。触发词:algolia、instantsearch、搜索索引、typeahead、faceted search

How to use this skill

Skill file

何时使用

适用:

不该用(负边界):

步骤

  1. 划分客户端:前端只用「搜索专用 Key」+ algoliasearch/lite;写操作(索引、配置、生成 Secured Key)一律放服务端,用 Admin Key。
  2. 设计记录结构:每条记录必须有唯一 objectID;日期用时间戳(getTime())以便排序;剔除不需要检索的字段。
  3. 建立索引同步:优先增量更新(partialUpdateObject),批量写用 saveObjects(每批 1K–10K 条 / ≤10MB);删除用 deleteObjects(ids) 而非 deleteBy。
  4. 配置索引设置:searchableAttributes(按重要性排序)、attributesForFaceting、customRanking(叠加业务指标),并加同义词与 Rules。
  5. 接入前端:普通 SPA 用 <InstantSearch>;Next.js SSR 用 <InstantSearchNext> 并 export const dynamic = 'force-dynamic'。
  6. 加分面与排序:分面属性须先在 attributesForFaceting 声明;多维排序用 replica 副本索引(如 products_price_asc)。
  7. 加自动补全:用 @algolia/autocomplete-js 或内置 Autocomplete widget,建议启用 Query Suggestions 索引。
  8. 校验上线:确认无 Admin Key 进入前端、无硬编码凭据、无循环单条索引、无频繁全量重建。

指令

// lib/algolia.ts
import algoliasearch from 'algoliasearch/lite';
export const searchClient = algoliasearch(
  process.env.NEXT_PUBLIC_ALGOLIA_APP_ID!,
  process.env.NEXT_PUBLIC_ALGOLIA_SEARCH_KEY!  // 仅搜索 Key
);
export const INDEX_NAME = 'products';
const index = adminClient.initIndex('products');
const BATCH_SIZE = 1000;
for (let i = 0; i < records.length; i += BATCH_SIZE) {
  await index.saveObjects(records.slice(i, i + BATCH_SIZE));
}
await index.partialUpdateObject({ objectID, price, updatedAt: Date.now() });
await index.partialUpdateObject({
  objectID, viewCount: { _operation: 'Increment', value: 1 },
});
await tempIndex.saveObjects(/* ... */);
await adminClient.copyIndex('products', 'products_temp', { scope: ['settings','synonyms','rules'] });
await adminClient.moveIndex('products_temp', 'products');
adminClient.generateSecuredApiKey(searchKey, {
  filters: `userId:${userId}`,
  validUntil: Math.floor(Date.now()/1000) + 3600,
  restrictIndices: ['user_documents'],
});
await index.setSettings({
  searchableAttributes: ['name','brand','category','description'],
  attributesForFaceting: ['category','brand','filterOnly(inStock)','searchable(tags)'],
  customRanking: ['desc(popularity)','desc(rating)','desc(createdAt)'],
  typoTolerance: true, minWordSizefor1Typo: 4, minWordSizefor2Typos: 8,
  attributesToHighlight: ['name','description'],
});

示例

前端即时搜索(React InstantSearch + Hooks):

'use client';
import { InstantSearch, SearchBox, Hits, Configure } from 'react-instantsearch';
import { searchClient, INDEX_NAME } from '@/lib/algolia';

export function ProductSearch() {
  return (
    <InstantSearch searchClient={searchClient} indexName={INDEX_NAME}>
      <Configure hitsPerPage={20} />
      <SearchBox placeholder="搜索产品..." />
      <Hits hitComponent={Hit} />
    </InstantSearch>
  );
}

自定义 Hooks:useSearchBox(输入/refine)、useHits(结果)、useRefinementList(分面)、usePagination(分页)、useInstantSearch(全局状态/status)。

分面 + 多维排序(排序需 replica 副本索引):

<SortBy items={[
  { label: '相关性', value: 'products' },
  { label: '价格升序', value: 'products_price_asc' },
  { label: '评分', value: 'products_rating_desc' },
]} />
<HierarchicalMenu attributes={['categories.lvl0','categories.lvl1','categories.lvl2']} />
<RefinementList attribute="brand" searchable showMore limit={5} />
<RangeInput attribute="price" />
// 副本: products_price_asc → customRanking: ['asc(price)']

Next.js SSR:用 <InstantSearchNext> 替换 <InstantSearch>,并设 export const dynamic = 'force-dynamic' 保证结果新鲜。

注意事项

互见


采编自 sickn33/antigravity-awesome-skills(MIT)。原始来源标注为 vibeship-spawner-skills(Apache 2.0)。

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.