Use Cases

Algolia 全文搜索实战:Claude Code 集成指南

使用 Claude Code 集成 Algolia,从索引设计到 React InstantSearch UI 的完整实战教程,包含可直接复用的代码示例。

用 Claude Code 构建 Algolia 全文搜索

Algolia 是一款响应速度达到毫秒级的搜索引擎 SaaS,原生支持拼写纠错、分面搜索、个性化排序等高阶搜索能力,能让你轻松打造出色的搜索体验。借助 Claude Code,从索引设计到搜索 UI 的实现都可以一气呵成。

索引设计与数据导入

> 帮我设计 Algolia 的商品索引,
> 并写一个导入脚本,要求中文和英文都能正常搜索。
// src/scripts/index-products.ts
import algoliasearch from 'algoliasearch';

const client = algoliasearch(
  process.env.ALGOLIA_APP_ID!,
  process.env.ALGOLIA_ADMIN_KEY!
);

const index = client.initIndex('products');

// 索引配置
await index.setSettings({
  searchableAttributes: [
    'name',
    'description',
    'category',
    'brand',
    'tags',
  ],
  attributesForFaceting: [
    'searchable(category)',
    'searchable(brand)',
    'price_range',
    'filterOnly(in_stock)',
  ],
  customRanking: ['desc(popularity)', 'asc(price)'],
  queryLanguages: ['zh', 'en'],
  indexLanguages: ['zh', 'en'],
  // 中文分词相关配置
  ignorePlurals: true,
  removeStopWords: true,
});

// 数据导入
interface Product {
  objectID: string;
  name: string;
  description: string;
  category: string;
  brand: string;
  price: number;
  price_range: string;
  in_stock: boolean;
  tags: string[];
  popularity: number;
  image_url: string;
}

const products: Product[] = await fetchProductsFromDB();

// 分批写入索引(每批 1000 条)
const batchSize = 1000;
for (let i = 0; i < products.length; i += batchSize) {
  const batch = products.slice(i, i + batchSize);
  await index.saveObjects(batch);
  console.log(`已索引 ${i + batch.length} / ${products.length}`);
}

用 React InstantSearch 搭建搜索 UI

> 用 React InstantSearch 写一个搜索页面,
> 要有分面筛选、高亮和分页。
// src/components/SearchPage.tsx
import {
  InstantSearch,
  SearchBox,
  Hits,
  RefinementList,
  Pagination,
  Highlight,
  Stats,
  Configure,
} from 'react-instantsearch';
import algoliasearch from 'algoliasearch/lite';

const searchClient = algoliasearch(
  process.env.NEXT_PUBLIC_ALGOLIA_APP_ID!,
  process.env.NEXT_PUBLIC_ALGOLIA_SEARCH_KEY!
);

function Hit({ hit }: { hit: any }) {
  return (
    <article className="p-4 border rounded-lg">
      <img
        src={hit.image_url}
        alt={hit.name}
        className="w-full h-48 object-cover rounded"
      />
      <h3 className="text-lg font-bold mt-2">
        <Highlight attribute="name" hit={hit} />
      </h3>
      <p className="text-gray-600 text-sm mt-1">
        <Highlight attribute="description" hit={hit} />
      </p>
      <div className="flex justify-between items-center mt-2">
        <span className="text-indigo-600 font-bold">
          ¥{hit.price.toLocaleString()}
        </span>
        <span className="text-sm text-gray-500">{hit.brand}</span>
      </div>
    </article>
  );
}

export default function SearchPage() {
  return (
    <InstantSearch searchClient={searchClient} indexName="products">
      <Configure hitsPerPage={12} />
      <div className="max-w-6xl mx-auto p-6">
        <SearchBox
          placeholder="搜索商品..."
          className="mb-6"
        />
        <Stats />
        <div className="grid grid-cols-4 gap-6 mt-4">
          <aside>
            <h4 className="font-bold mb-2">分类</h4>
            <RefinementList attribute="category" />
            <h4 className="font-bold mt-4 mb-2">品牌</h4>
            <RefinementList attribute="brand" searchable />
            <h4 className="font-bold mt-4 mb-2">价格区间</h4>
            <RefinementList attribute="price_range" />
          </aside>
          <main className="col-span-3">
            <Hits hitComponent={Hit} className="grid grid-cols-3 gap-4" />
            <Pagination className="mt-6" />
          </main>
        </div>
      </div>
    </InstantSearch>
  );
}

索引同步

数据库发生变更时,需要有一套机制把数据同步到 Algolia。

// src/services/algolia-sync.ts
import algoliasearch from 'algoliasearch';

const client = algoliasearch(
  process.env.ALGOLIA_APP_ID!,
  process.env.ALGOLIA_ADMIN_KEY!
);
const index = client.initIndex('products');

export async function onProductCreated(product: Product) {
  await index.saveObject({ ...product, objectID: product.id });
}

export async function onProductUpdated(product: Product) {
  await index.partialUpdateObject({
    objectID: product.id,
    ...product,
  });
}

export async function onProductDeleted(productId: string) {
  await index.deleteObject(productId);
}

总结

把 Algolia 的高速搜索能力和 Claude Code 结合起来,短时间内就能交付一套生产级的搜索功能。如果你还想继续完善,可以参考 搜索功能实现指南性能优化

想深入了解 Algolia,请移步 Algolia 官方文档

#Claude Code #Algolia #全文搜索 #搜索UI #SaaS集成

让你的 Claude Code 工作流更上一层楼

50 个经过实战检验的提示词模板,现在就能复制粘贴到 Claude Code 中使用。

免费

免费 PDF:5 分钟看懂 Claude Code 速查表

关键命令、快捷键与提示词示例,整理在一页可打印的 A4 纸上。

下载 PDF
M

本文作者

Masa

深度使用 Claude Code 的工程师。运营 claudecode-lab.com——一个涵盖 10 种语言、超过 2,000 页内容的科技媒体。