Claude Code for Meilisearch: Instant Search with Typo Tolerance — Claude Skills 360 Blog
Blog / AI / Claude Code for Meilisearch: Instant Search with Typo Tolerance
AI

Claude Code for Meilisearch: Instant Search with Typo Tolerance

Published: July 10, 2027
Read time: 6 min read
By: Claude Skills 360

Meilisearch delivers instant, typo-tolerant full-text search — new MeiliSearch({ host, apiKey }) initializes the client. client.index("products").search(query, { filter, sort, limit, attributesToHighlight }) searches with sub-50ms responses. index.addDocuments(docs) indexes documents (must have an id field by default). index.updateSettings({ searchableAttributes, filterableAttributes, sortableAttributes, rankingRules }) configures the index. Filters: filter: "category = 'shoes' AND price < 100", facets: facets: ["brand", "category"]. Sorting: sort: ["price:asc"]. Highlighting: attributesToHighlight: ["title", "description"] adds _formatted with <em> tags. Geosearch: documents with _geo: { lat, lng } enable filter: "_geoRadius(lat, lng, distance)" and sort: ["_geoPoint(lat,lng):asc"]. Synonyms: index.updateSynonyms({ tv: ["television", "screen"] }). React integration: <InstantSearch searchClient={searchClient} indexName="products"> with <SearchBox>, <Hits>, <RefinementList>, <Pagination> from react-instantsearch. Claude Code generates Meilisearch instant search UIs, faceted navigation, and multi-index federation.

CLAUDE.md for Meilisearch

## Meilisearch Stack
- Version: meilisearch >= 0.40, react-instantsearch >= 7.x (if using React UI)
- Init: const client = new MeiliSearch({ host: process.env.MEILISEARCH_HOST!, apiKey: process.env.MEILISEARCH_API_KEY! })
- Search: const results = await client.index("products").search(query, { limit: 20, attributesToHighlight: ["title"], filter: "inStock = true" })
- Index docs: await client.index("products").addDocuments(docs) — each doc needs a primary key (default: "id")
- Settings: await index.updateSettings({ searchableAttributes: ["title","description"], filterableAttributes: ["category","price"], sortableAttributes: ["price","createdAt"] })
- Results: results.hits (array), results.totalHits, results.processingTimeMs, results.facetDistribution
- Facets: add facets: ["category","brand"] to search options; results.facetDistribution gives counts

Meilisearch Client

// lib/meilisearch/client.ts — Meilisearch SDK with typed helpers
import { MeiliSearch, type SearchParams, type SearchResponse } from "meilisearch"

const client = new MeiliSearch({
  host: process.env.MEILISEARCH_HOST!,
  apiKey: process.env.MEILISEARCH_API_KEY!,
})

export type ProductDoc = {
  id: string
  title: string
  description: string
  category: string
  brand: string
  price: number
  inStock: boolean
  tags: string[]
  _geo?: { lat: number; lng: number }
}

export type SearchOptions = {
  query?: string
  filters?: string
  sort?: string[]
  facets?: string[]
  page?: number
  hitsPerPage?: number
  highlightFields?: string[]
}

export type SearchResult<T> = {
  hits: (T & { _formatted?: Partial<T> })[]
  totalHits: number
  page: number
  hitsPerPage: number
  processingMs: number
  facets?: Record<string, Record<string, number>>
}

/** Search an index with full options */
export async function searchIndex<T extends Record<string, unknown>>(
  indexName: string,
  options: SearchOptions = {},
): Promise<SearchResult<T>> {
  const {
    query = "",
    filters,
    sort,
    facets,
    page = 1,
    hitsPerPage = 20,
    highlightFields,
  } = options

  const params: SearchParams = {
    limit: hitsPerPage,
    offset: (page - 1) * hitsPerPage,
    ...(filters ? { filter: filters } : {}),
    ...(sort ? { sort } : {}),
    ...(facets ? { facets } : {}),
    ...(highlightFields
      ? { attributesToHighlight: highlightFields, highlightPreTag: "<mark>", highlightPostTag: "</mark>" }
      : {}),
  }

  const index = client.index(indexName)
  const response = (await index.search(query, params)) as SearchResponse<T>

  return {
    hits: response.hits,
    totalHits: response.totalHits ?? response.hits.length,
    page,
    hitsPerPage,
    processingMs: response.processingTimeMs,
    facets: response.facetDistribution,
  }
}

/** Add or replace documents */
export async function indexDocuments<T extends { id: string }>(
  indexName: string,
  documents: T[],
): Promise<void> {
  const index = client.index(indexName)
  const task = await index.addDocuments(documents)
  await client.waitForTask(task.taskUid)
}

/** Update documents (partial) */
export async function updateDocuments<T extends { id: string }>(
  indexName: string,
  documents: Partial<T & { id: string }>[],
): Promise<void> {
  const index = client.index(indexName)
  const task = await index.updateDocuments(documents as any)
  await client.waitForTask(task.taskUid)
}

/** Delete documents by IDs */
export async function deleteDocuments(indexName: string, ids: string[]): Promise<void> {
  const index = client.index(indexName)
  const task = await index.deleteDocuments(ids)
  await client.waitForTask(task.taskUid)
}

/** Configure index settings */
export async function configureIndex(
  indexName: string,
  settings: {
    searchable?: string[]
    filterable?: string[]
    sortable?: string[]
    rankingRules?: string[]
    synonyms?: Record<string, string[]>
    stopWords?: string[]
    typoTolerance?: { minWordSizeForTypos?: { oneTypo?: number; twoTypos?: number } }
  },
): Promise<void> {
  const index = client.index(indexName)
  const tasks: number[] = []

  if (settings.searchable || settings.filterable || settings.sortable || settings.rankingRules || settings.typoTolerance) {
    const task = await index.updateSettings({
      ...(settings.searchable ? { searchableAttributes: settings.searchable } : {}),
      ...(settings.filterable ? { filterableAttributes: settings.filterable } : {}),
      ...(settings.sortable ? { sortableAttributes: settings.sortable } : {}),
      ...(settings.rankingRules ? { rankingRules: settings.rankingRules } : {}),
      ...(settings.typoTolerance ? { typoTolerance: settings.typoTolerance } : {}),
    })
    tasks.push(task.taskUid)
  }

  if (settings.synonyms) {
    const task = await index.updateSynonyms(settings.synonyms)
    tasks.push(task.taskUid)
  }

  if (settings.stopWords) {
    const task = await index.updateStopWords(settings.stopWords)
    tasks.push(task.taskUid)
  }

  await Promise.all(tasks.map((uid) => client.waitForTask(uid)))
}

/** Geosearch: find documents near a location */
export async function geoSearch<T extends Record<string, unknown>>(
  indexName: string,
  lat: number,
  lng: number,
  radiusMeters: number,
  query = "",
  limit = 20,
): Promise<SearchResult<T>> {
  const index = client.index(indexName)
  const response = (await index.search(query, {
    filter: `_geoRadius(${lat}, ${lng}, ${radiusMeters})`,
    sort: [`_geoPoint(${lat},${lng}):asc`],
    limit,
  })) as SearchResponse<T>

  return {
    hits: response.hits,
    totalHits: response.totalHits ?? response.hits.length,
    page: 1,
    hitsPerPage: limit,
    processingMs: response.processingTimeMs,
  }
}

/** Multi-index federated search */
export async function federatedSearch(
  query: string,
  indexes: Array<{ name: string; limit?: number }>,
): Promise<Record<string, unknown[]>> {
  const results = await Promise.all(
    indexes.map(async ({ name, limit = 5 }) => {
      const index = client.index(name)
      const res = await index.search(query, { limit })
      return [name, res.hits] as const
    }),
  )

  return Object.fromEntries(results)
}

export { client }

Index Setup Script

// scripts/setup-meilisearch.ts — create and configure indexes
import { client, configureIndex, indexDocuments, type ProductDoc } from "../lib/meilisearch/client"

async function setup() {
  // Create products index (will no-op if it exists)
  await client.createIndex("products", { primaryKey: "id" }).catch(() => {})

  // Configure settings
  await configureIndex("products", {
    searchable: ["title", "description", "brand", "tags"],
    filterable: ["category", "brand", "price", "inStock", "_geo"],
    sortable: ["price", "createdAt", "_geo"],
    rankingRules: [
      "words",
      "typo",
      "proximity",
      "attribute",
      "sort",
      "exactness",
    ],
    synonyms: {
      tv: ["television", "monitor", "screen"],
      phone: ["smartphone", "mobile", "cell phone"],
    },
    stopWords: ["the", "a", "an", "of", "and", "or"],
    typoTolerance: {
      minWordSizeForTypos: { oneTypo: 4, twoTypos: 8 },
    },
  })

  // Seed sample documents
  const products: ProductDoc[] = [
    {
      id: "prod-1",
      title: "Wireless Noise-Canceling Headphones",
      description: "Premium over-ear headphones with 30h battery",
      category: "electronics",
      brand: "SoundPro",
      price: 299,
      inStock: true,
      tags: ["audio", "wireless", "anc"],
    },
    {
      id: "prod-2",
      title: "Running Shoes - Men's",
      description: "Lightweight performance running shoes",
      category: "shoes",
      brand: "SpeedRun",
      price: 129,
      inStock: true,
      tags: ["running", "fitness", "sport"],
    },
  ]

  await indexDocuments("products", products)
  console.log("Meilisearch setup complete")
}

setup().catch(console.error)

React InstantSearch UI

// components/search/ProductSearch.tsx — react-instantsearch faceted search
"use client"
import { instantMeiliSearch } from "@meilisearch/instant-meilisearch"
import {
  InstantSearch,
  SearchBox,
  Hits,
  RefinementList,
  SortBy,
  Pagination,
  Highlight,
  useInstantSearch,
} from "react-instantsearch"
import type { Hit } from "instantsearch.js"
import type { ProductDoc } from "@/lib/meilisearch/client"

const searchClient = instantMeiliSearch(
  process.env.NEXT_PUBLIC_MEILISEARCH_HOST!,
  process.env.NEXT_PUBLIC_MEILISEARCH_SEARCH_KEY!, // public search-only key
)

function ProductHit({ hit }: { hit: Hit<ProductDoc> }) {
  return (
    <article className="rounded-lg border p-4 hover:shadow-md transition-shadow">
      <h3 className="font-semibold text-gray-900">
        <Highlight attribute="title" hit={hit} />
      </h3>
      <p className="text-sm text-gray-500 mt-1">
        <Highlight attribute="description" hit={hit} />
      </p>
      <div className="flex items-center justify-between mt-3">
        <span className="text-indigo-600 font-bold">${hit.price}</span>
        <span
          className={`text-xs px-2 py-1 rounded-full ${
            hit.inStock ? "bg-green-100 text-green-700" : "bg-red-100 text-red-700"
          }`}
        >
          {hit.inStock ? "In Stock" : "Out of Stock"}
        </span>
      </div>
    </article>
  )
}

function SearchStats() {
  const { results } = useInstantSearch()
  if (!results?.__isArtificial && results?.nbHits !== undefined) {
    return (
      <p className="text-sm text-gray-500">
        {results.nbHits.toLocaleString()} results in {results.processingTimeMS}ms
      </p>
    )
  }
  return null
}

export default function ProductSearch() {
  return (
    <InstantSearch searchClient={searchClient} indexName="products" future={{ preserveSharedStateOnUnmount: true }}>
      <div className="max-w-6xl mx-auto p-6">
        {/* Search box */}
        <SearchBox
          classNames={{
            root: "mb-6",
            input: "w-full rounded-xl border border-gray-300 px-4 py-3 text-lg focus:ring-2 focus:ring-indigo-500 focus:border-transparent",
            submitIcon: "hidden",
            resetIcon: "hidden",
          }}
          placeholder="Search products…"
        />

        <div className="flex gap-8">
          {/* Sidebar facets */}
          <aside className="w-56 shrink-0">
            <div className="mb-6">
              <h4 className="font-semibold text-gray-700 mb-2 text-sm uppercase tracking-wide">Category</h4>
              <RefinementList
                attribute="category"
                classNames={{
                  item: "flex items-center gap-2 py-1",
                  label: "text-sm text-gray-600 cursor-pointer",
                  count: "ml-auto text-xs text-gray-400 bg-gray-100 px-1.5 py-0.5 rounded",
                  checkbox: "rounded",
                }}
              />
            </div>

            <div className="mb-6">
              <h4 className="font-semibold text-gray-700 mb-2 text-sm uppercase tracking-wide">Brand</h4>
              <RefinementList attribute="brand" limit={8} showMore />
            </div>
          </aside>

          {/* Results */}
          <main className="flex-1">
            <div className="flex items-center justify-between mb-4">
              <SearchStats />
              <SortBy
                items={[
                  { label: "Relevance", value: "products" },
                  { label: "Price: Low→High", value: "products:price:asc" },
                  { label: "Price: High→Low", value: "products:price:desc" },
                ]}
                classNames={{
                  select: "rounded-lg border border-gray-300 px-3 py-1.5 text-sm",
                }}
              />
            </div>

            <Hits
              hitComponent={ProductHit}
              classNames={{ list: "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4" }}
            />

            <div className="mt-8 flex justify-center">
              <Pagination
                classNames={{
                  item: "px-3 py-1 rounded border mx-0.5",
                  selectedItem: "bg-indigo-600 text-white border-indigo-600",
                }}
              />
            </div>
          </main>
        </div>
      </div>
    </InstantSearch>
  )
}

Next.js Search API Route

// app/api/search/products/route.ts — server-side Meilisearch with auth
import { NextResponse } from "next/server"
import { z } from "zod"
import { searchIndex } from "@/lib/meilisearch/client"

const SearchSchema = z.object({
  q: z.string().default(""),
  category: z.string().optional(),
  brand: z.string().optional(),
  minPrice: z.coerce.number().optional(),
  maxPrice: z.coerce.number().optional(),
  inStock: z.coerce.boolean().optional(),
  sort: z.enum(["price:asc", "price:desc", "relevance"]).default("relevance"),
  page: z.coerce.number().int().min(1).default(1),
})

export async function GET(req: Request) {
  const { searchParams } = new URL(req.url)
  const params = SearchSchema.parse(Object.fromEntries(searchParams))

  // Build Meilisearch filter string
  const filters: string[] = []
  if (params.category) filters.push(`category = "${params.category}"`)
  if (params.brand) filters.push(`brand = "${params.brand}"`)
  if (params.minPrice !== undefined) filters.push(`price >= ${params.minPrice}`)
  if (params.maxPrice !== undefined) filters.push(`price <= ${params.maxPrice}`)
  if (params.inStock !== undefined) filters.push(`inStock = ${params.inStock}`)

  const results = await searchIndex("products", {
    query: params.q,
    filters: filters.join(" AND ") || undefined,
    sort: params.sort === "relevance" ? undefined : [params.sort],
    facets: ["category", "brand"],
    highlightFields: ["title", "description"],
    page: params.page,
    hitsPerPage: 24,
  })

  return NextResponse.json(results)
}

For the Typesense alternative when needing on-premise deployment with a more permissive open-source license (GPL-3 vs Meilisearch’s SSPL), multi-tenant rate limiting per API key, or specific Typesense Cloud managed hosting — Typesense and Meilisearch are nearly identical in features, with Meilisearch having a slightly simpler configuration API and better geosearch, see the Typesense guide. For the Algolia alternative when needing a fully-managed enterprise search service with AI-powered ranking, A/B testing, personalization, and multi-region replication without operating any infrastructure — Algolia is the leading managed search SaaS while Meilisearch is the top open-source self-hosted option with an identical react-instantsearch integration, see the Algolia guide. The Claude Skills 360 bundle includes Meilisearch skill sets covering instant search, faceted navigation, and geosearch. Start with the free tier to try instant search generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free