pattern/persistence/search-index
- Bun
- Elasticsearch
- Elasticsearch client
- TypeScript
- Docker
Cópia dos dados num motor de busca, modelada para consulta (prefixo, sem acento, filtros); o banco segue como fonte da verdade e o índice é reconstruível.
pattern/persistence/search-index
Cenário
No extrato, "sao" acha "Drogaria São Paulo" e "Padaria São José" entre os PIX.
Planta
Fluxo3 passos — reproduza para seguir o fluxo
Como funciona
4passos
Cópia dos dados num motor de busca, modelada para consulta (prefixo, sem acento, filtros)
Esconde cada passo: lembre antes de tocar para revelar.
Mapping explícito dynamic: strict
merchant com edge n-gram, lowercase e asciifolding; busca com analyzer standard
Bulk com _id fixo: recarga não duplica
Texto em must, tipo em filter (sem score, cacheado)
Trade-offs
O que se ganha, o que se paga
Vantagens
Busca por prefixo sem acento em ms
Filtros cacheados
Custos
Cópia com segundos de atraso
Mais um cluster para operar
Código
pattern/persistence/search-index
6 arquivos./
src/
Executar com Docker
./docker.shuntil curl -sf http://localhost:9200/_cluster/health >/dev/null 2>&1; do sleep 1; donebun install# dependênciasbun run demo# roda o cenáriodocker rm -f search-index-searchSaída: “sao” acha TX-0 Drogaria São Paulo R$ 10.00 e TX-1 Padaria São José R$ 35.50.
Código
src/demo.ts// Demo: the bank's transactions are copied into Elasticsearch with an autocomplete analyzer; typing "sao" finds "São".
import { Client, HttpConnection } from "@elastic/elasticsearch";
// HttpConnection (node:http) instead of the default undici pool, which Bun does not fully implement.
const client = new Client({ node: Bun.env.SEARCH_INDEX_ELASTICSEARCH_URL ?? "http://localhost:9200", Connection: HttpConnection });
const index = `transactions_${Date.now()}`;
type TransactionDocument = { id: string; type: string; merchant: string; amountCents: number };
await client.cluster.health({ wait_for_status: "yellow", timeout: "30s" });
await client.indices.create({
index,
settings: {
number_of_shards: 1,
number_of_replicas: 0,
// Edge n-grams at index time, with asciifolding so "sao" finds "São"; the query side stays standard.
analysis: {
filter: { autocomplete_filter: { type: "edge_ngram", min_gram: 2, max_gram: 15 } },
analyzer: { autocomplete_analyzer: { type: "custom", tokenizer: "standard", filter: ["lowercase", "asciifolding", "autocomplete_filter"] } },
},
},
mappings: {
// An undeclared field fails the write instead of silently widening the mapping.
dynamic: "strict",
properties: {
id: { type: "keyword" },
type: { type: "keyword" },
merchant: { type: "text", analyzer: "autocomplete_analyzer", search_analyzer: "standard", fields: { raw: { type: "keyword" } } },
amountCents: { type: "long" },
},
},
});
// The ledger stays the source of truth; the index is a rebuildable copy, loaded in bulk with a fixed _id.
const merchants = ["Drogaria São Paulo", "Padaria São José", "Mercado Livre", "Posto Ipiranga"];
const documents: TransactionDocument[] = merchants.map((merchant, sequence) => ({ id: `TX-${sequence}`, type: "pix", merchant, amountCents: 1_000 + sequence * 2_550 }));
await client.bulk({ refresh: true, operations: documents.flatMap((document) => [{ index: { _index: index, _id: document.id } }, document]) });
// must scores the text; the yes/no condition goes to filter, unscored and cached.
const response = await client.search<TransactionDocument>({ index, query: { bool: { must: [{ match: { merchant: "sao" } }], filter: [{ term: { type: "pix" } }] } } });
for (const hit of response.hits.hits) console.log(` [SEARCH "sao"] ${hit._source!.id} ${hit._source!.merchant} R$ ${(hit._source!.amountCents / 100).toFixed(2)}`);
await client.indices.delete({ index });
await client.close();
Nível
introdutório
3/13
Domínio financeiro
Padrões do catálogo que implementa
Infraestrutura
Elasticsearchmotor de busca
elasticsearch:8.15.0:9200
Variáveis de ambiente
Relações
Onde ele se encaixa
Por que se relacionam
Teste rápido
Qual padrão vem antes de Search Index?
Busca textual fora do banco. Abrir Sharding e Particionamento
Seu progresso
0/157 estudados
Fica salvo só neste navegador.