Use Cases

Algolia Implementation:Claude Code 实战指南

了解algolia implementation:Claude Code 实战. 包含实用技巧和代码示例。

Algolia全文搜索を通过 Claude Code 构建

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: ['ja', 'en'],
  indexLanguages: ['ja', '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(`Indexed ${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集成