Pular para o conteúdo

Search Index

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.

passos
4
arquivos
6
testes
0
tecnologias
5

Cenário

No extrato, "sao" acha "Drogaria São Paulo" e "Padaria São José" entre os PIX.

Planta

Fluxo
3/3
Transações do livro- fonte da verdadeBulk com _id fixoíndice transactionsApp do clientebusca sao, filtro pix
3

3 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.

  1. 1

    Mapping explícito dynamic: strict

  2. 2

    merchant com edge n-gram, lowercase e asciifolding; busca com analyzer standard

  3. 3

    Bulk com _id fixo: recarga não duplica

  4. 4

    Texto em must, tipo em filter (sem score, cacheado)

Trade-offs

O que se ganha, o que se paga

2 vantagenscada ganho tem um preço2 custos

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

./

  • .env.exampleinfra
  • docker.shinfra
  • package.jsoninfra
  • README.md
  • tsconfig.jsoninfra

src/

  • demo.tsdemo

Executar com Docker

  1. ./docker.sh
  2. until curl -sf http://localhost:9200/_cluster/health >/dev/null 2>&1; do sleep 1; done
  3. bun install# dependências
  4. bun run demo# roda o cenário
  5. docker rm -f search-index-search

Saída: “sao” acha TX-0 Drogaria São Paulo R$ 10.00 e TX-1 Padaria São José R$ 35.50.

Requisitos
BunDocker
Sobe junto
Elasticsearch

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

Linhas de TypeScript
38
Tipo
B — um serviço (docker.sh)

Domínio financeiro

  • PIX
  • Extrato

Padrões do catálogo que implementa

Infraestrutura

  • Elasticsearchmotor de busca

    elasticsearch:8.15.0:9200

Variáveis de ambiente

SEARCH_INDEX_ELASTICSEARCH_URL
http://localhost:9200
Elasticsearch node the indexer writes to and the search reads from.

Por que se relacionam

Teste rápido

Qual padrão vem antes de Search Index?

Próximo projeto, Dados & PersistênciaSharding e Particionamento
Esc

↑ ↓ navegarEnter abrir239 resultados