Use Cases

Implementation d'Algolia avec Claude Code

Apprenez l'implementation d'Algolia avec Claude Code. Conseils pratiques et exemples de code inclus.

Construire une recherche plein texte avec Algolia en utilisant Claude Code

Algolia est un moteur de recherche SaaS offrant des temps de reponse de l’ordre de la milliseconde. Il permet d’implementer facilement des experiences de recherche avancees comme la tolerance aux fautes de frappe, la recherche a facettes et la personnalisation. Avec Claude Code, vous pouvez progresser efficacement de la conception de l’index a la construction de l’UI de recherche.

Conception de l’index et ingestion des donnees

> Concois un index Algolia et cree un script pour ingerer les donnees produits.
> Inclus le support de la recherche multilingue.
// 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');

// Configuration de l'index
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'],
  // Tokenisation multilingue
  ignorePlurals: true,
  removeStopWords: true,
});

// Ingestion des donnees
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();

// Ingestion par lots dans l'index (1000 enregistrements a la fois)
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(`Indexes ${i + batch.length} / ${products.length}`);
}

Construction de l’UI de recherche avec React InstantSearch

> Cree une page de recherche avec React InstantSearch.
> Avec facettes, mise en surbrillance et pagination.
// 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="Rechercher des produits..."
          className="mb-6"
        />
        <Stats />
        <div className="grid grid-cols-4 gap-6 mt-4">
          <aside>
            <h4 className="font-bold mb-2">Categorie</h4>
            <RefinementList attribute="category" />
            <h4 className="font-bold mt-4 mb-2">Marque</h4>
            <RefinementList attribute="brand" searchable />
            <h4 className="font-bold mt-4 mb-2">Gamme de prix</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>
  );
}

Synchronisation de l’index

Un mecanisme est necessaire pour synchroniser les modifications de la base de donnees avec 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);
}

Summary

En combinant la recherche haute vitesse d’Algolia avec Claude Code, vous pouvez construire une fonctionnalite de recherche de niveau production en peu de temps. Consultez egalement le guide d’implementation de la recherche et l’optimisation des performances.

Pour plus de details sur Algolia, consultez la documentation officielle d’Algolia.

#Claude Code #Algolia #recherche plein texte #UI de recherche #integration SaaS