Folha de Dicas do Elasticsearch: Comandos Essenciais & Dicas

Comandos do Elasticsearch para busca, indexação e análise

Conteúdo da página

Elasticsearch é um poderoso motor de busca e análise distribuído construído sobre o Apache Lucene. Este cheatsheet abrangente abrange comandos essenciais, melhores práticas e referências rápidas para trabalhar com clusters Elasticsearch.

elasticsearch

Nota: A maioria dos exemplos neste guia usa o cURL para solicitações HTTP. Se você for novo no cURL ou precisar de uma referência rápida para opções avançadas, consulte nossa cURL Cheatsheet para técnicas detalhadas de solicitações HTTP na linha de comando.

Gerenciamento de Cluster

Verificar Saúde do Cluster

Todos os comandos nesta seção usam o cURL para interagir com a API REST do Elasticsearch. Você pode personalizar essas solicitações com cabeçalhos adicionais, autenticação e outras opções conforme necessário.

# Verificação básica de saúde
curl -X GET "localhost:9200/_cluster/health?pretty"

# Saúde do cluster detalhada com informações de shard
curl -X GET "localhost:9200/_cluster/health?level=shards&pretty"

# Verificar informações do nó
curl -X GET "localhost:9200/_cat/nodes?v"

# Verificar configurações do cluster
curl -X GET "localhost:9200/_cluster/settings?pretty"

Operações de Nó

# Listar todos os nós
curl -X GET "localhost:9200/_cat/nodes?v&h=name,node.role,heap.percent,ram.percent,cpu,load_1m"

# Estatísticas do nó
curl -X GET "localhost:9200/_nodes/stats?pretty"

# Threads quentes (solução de problemas)
curl -X GET "localhost:9200/_nodes/hot_threads"

Gerenciamento de Índices

Criar e Excluir Índices

# Criar índice
curl -X PUT "localhost:9200/my_index?pretty"

# Criar índice com configurações
curl -X PUT "localhost:9200/my_index" -H 'Content-Type: application/json' -d'
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1
  }
}
'

# Excluir índice
curl -X DELETE "localhost:9200/my_index?pretty"

# Listar todos os índices
curl -X GET "localhost:9200/_cat/indices?v"

# Estatísticas do índice
curl -X GET "localhost:9200/my_index/_stats?pretty"

Mapeamentos de Índice

# Definir mapeamento
curl -X PUT "localhost:9200/products" -H 'Content-Type: application/json' -d'
{
  "mappings": {
    "properties": {
      "name": { "type": "text" },
      "price": { "type": "float" },
      "created_at": { "type": "date" },
      "tags": { "type": "keyword" },
      "description": { 
        "type": "text",
        "analyzer": "english"
      }
    }
  }
}
'

# Obter mapeamento
curl -X GET "localhost:9200/products/_mapping?pretty"

# Atualizar mapeamento (adicionar campo)
curl -X PUT "localhost:9200/products/_mapping" -H 'Content-Type: application/json' -d'
{
  "properties": {
    "category": { "type": "keyword" }
  }
}
'

Modelos de Índice

# Criar modelo de índice
curl -X PUT "localhost:9200/_index_template/logs_template" -H 'Content-Type: application/json' -d'
{
  "index_patterns": ["logs-*"],
  "template": {
    "settings": {
      "number_of_shards": 1
    },
    "mappings": {
      "properties": {
        "timestamp": { "type": "date" },
        "message": { "type": "text" },
        "level": { "type": "keyword" }
      }
    }
  }
}
'

# Listar modelos
curl -X GET "localhost:9200/_index_template?pretty"

Operações de Documentos (CRUD)

Criar Documentos

# Indexar documento com ID gerado automaticamente
curl -X POST "localhost:9200/products/_doc?pretty" -H 'Content-Type: application/json' -d'
{
  "name": "Laptop",
  "price": 999.99,
  "tags": ["electronics", "computers"]
}
'

# Indexar documento com ID específico
curl -X PUT "localhost:9200/products/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
  "name": "Laptop",
  "price": 999.99
}
'

# Indexação em lote
curl -X POST "localhost:9200/_bulk?pretty" -H 'Content-Type: application/json' -d'
{ "index": { "_index": "products", "_id": "1" }}
{ "name": "Laptop", "price": 999.99 }
{ "index": { "_index": "products", "_id": "2" }}
{ "name": "Mouse", "price": 29.99 }
'

Ler Documentos

# Obter documento por ID
curl -X GET "localhost:9200/products/_doc/1?pretty"

# Obter múltiplos documentos
curl -X GET "localhost:9200/_mget?pretty" -H 'Content-Type: application/json' -d'
{
  "docs": [
    { "_index": "products", "_id": "1" },
    { "_index": "products", "_id": "2" }
  ]
}
'

# Verificar se o documento existe
curl -I "localhost:9200/products/_doc/1"

Atualizar Documentos

# Atualizar documento
curl -X POST "localhost:9200/products/_update/1?pretty" -H 'Content-Type: application/json' -d'
{
  "doc": {
    "price": 899.99
  }
}
'

# Atualizar com script
curl -X POST "localhost:9200/products/_update/1?pretty" -H 'Content-Type: application/json' -d'
{
  "script": {
    "source": "ctx._source.price *= params.discount",
    "params": {
      "discount": 0.9
    }
  }
}
'

# Upsert (atualizar ou inserir)
curl -X POST "localhost:9200/products/_update/1?pretty" -H 'Content-Type: application/json' -d'
{
  "doc": {
    "price": 899.99
  },
  "doc_as_upsert": true
}
'

Excluir Documentos

# Excluir por ID
curl -X DELETE "localhost:9200/products/_doc/1?pretty"

# Excluir por consulta
curl -X POST "localhost:9200/products/_delete_by_query?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "match": {
      "name": "old"
    }
  }
}
'

Consultas de Busca

Busca Básica

# Correspondência total
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "match_all": {}
  }
}
'

# Consulta de correspondência
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "match": {
      "name": "laptop"
    }
  }
}
'

# Consulta de correspondência múltipla
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "multi_match": {
      "query": "laptop gaming",
      "fields": ["name", "description"]
    }
  }
}
'

Consultas de Nível de Termo

# Consulta de termo (correspondência exata)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "term": {
      "tags": "electronics"
    }
  }
}
'

# Consulta de termos (vários valores)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "terms": {
      "tags": ["electronics", "computers"]
    }
  }
}
'

# Consulta de intervalo
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "range": {
      "price": {
        "gte": 100,
        "lte": 1000
      }
    }
  }
}
'

# Consulta de existência
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "exists": {
      "field": "description"
    }
  }
}
'

Consultas Booleanas

# Consulta bool (must, should, must_not, filter)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "bool": {
      "must": [
        { "match": { "name": "laptop" }}
      ],
      "filter": [
        { "range": { "price": { "gte": 500 }}}
      ],
      "should": [
        { "term": { "tags": "gaming" }}
      ],
      "must_not": [
        { "term": { "tags": "refurbished" }}
      ]
    }
  }
}
'

Busca Avançada

# Consulta de wildcard
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "wildcard": {
      "name": "lap*"
    }
  }
}
'

# Consulta fuzzy (tolerância a erros de digitação)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "fuzzy": {
      "name": {
        "value": "laptpo",
        "fuzziness": "AUTO"
      }
    }
  }
}
'

# Consulta de prefixo
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "prefix": {
      "name": "lap"
    }
  }
}
'

Agregações

Agregações Métricas

# Média, soma, mínimo, máximo
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "size": 0,
  "aggs": {
    "avg_price": { "avg": { "field": "price" }},
    "max_price": { "max": { "field": "price" }},
    "min_price": { "min": { "field": "price" }},
    "total_sales": { "sum": { "field": "price" }}
  }
}
'

# Agregação de estatísticas
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "size": 0,
  "aggs": {
    "price_stats": {
      "stats": { "field": "price" }
    }
  }
}
'

Agregações de Buckets

# Agregação de termos (agrupar por)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "size": 0,
  "aggs": {
    "popular_tags": {
      "terms": {
        "field": "tags",
        "size": 10
      }
    }
  }
}
'

# Agregação de intervalo
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "size": 0,
  "aggs": {
    "price_ranges": {
      "range": {
        "field": "price",
        "ranges": [
          { "to": 50 },
          { "from": 50, "to": 100 },
          { "from": 100 }
        ]
      }
    }
  }
}
'

# Histograma de data
curl -X GET "localhost:9200/logs/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "size": 0,
  "aggs": {
    "logs_over_time": {
      "date_histogram": {
        "field": "timestamp",
        "calendar_interval": "day"
      }
    }
  }
}
'

Agregações Aninhadas

# Agregações aninhadas
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "size": 0,
  "aggs": {
    "categories": {
      "terms": { "field": "category" },
      "aggs": {
        "avg_price": {
          "avg": { "field": "price" }
        }
      }
    }
  }
}
'

Ordenação e paginação

# Ordenar por campo
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": { "match_all": {} },
  "sort": [
    { "price": { "order": "desc" }},
    { "_score": { "order": "desc" }}
  ]
}
'

# Paginação com from/size
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "from": 0,
  "size": 10,
  "query": { "match_all": {} }
}
'

# Search after (para paginação profunda)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "size": 10,
  "query": { "match_all": {} },
  "sort": [{ "price": "asc" }, { "_id": "asc" }],
  "search_after": [100, "product_123"]
}
'

Seleção de campos e destaque

# Selecionar campos específicos
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": { "match_all": {} },
  "_source": ["name", "price"]
}
'

# Destaque
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "match": { "description": "gaming laptop" }
  },
  "highlight": {
    "fields": {
      "description": {}
    }
  }
}
'

Aliases de Índice

# Criar alias
curl -X POST "localhost:9200/_aliases?pretty" -H 'Content-Type: application/json' -d'
{
  "actions": [
    { "add": { "index": "products_v1", "alias": "products" }}
  ]
}
'

# Alternar alias para um novo índice (sem tempo de inatividade)
curl -X POST "localhost:9200/_aliases?pretty" -H 'Content-Type: application/json' -d'
{
  "actions": [
    { "remove": { "index": "products_v1", "alias": "products" }},
    { "add": { "index": "products_v2", "alias": "products" }}
  ]
}
'

# Listar aliases
curl -X GET "localhost:9200/_cat/aliases?v"

Reindexação

# Reindexar de um índice para outro
curl -X POST "localhost:9200/_reindex?pretty" -H 'Content-Type: application/json' -d'
{
  "source": {
    "index": "old_products"
  },
  "dest": {
    "index": "new_products"
  }
}
'

# Reindexar com consulta
curl -X POST "localhost:9200/_reindex?pretty" -H 'Content-Type: application/json' -d'
{
  "source": {
    "index": "products",
    "query": {
      "range": {
        "price": { "gte": 100 }
      }
    }
  },
  "dest": {
    "index": "expensive_products"
  }
}
'

Snapshots e Backup

# Registrar repositório de snapshot
curl -X PUT "localhost:9200/_snapshot/my_backup?pretty" -H 'Content-Type: application/json' -d'
{
  "type": "fs",
  "settings": {
    "location": "/mount/backups/my_backup"
  }
}
'

# Criar snapshot
curl -X PUT "localhost:9200/_snapshot/my_backup/snapshot_1?wait_for_completion=true&pretty"

# Restaurar snapshot
curl -X POST "localhost:9200/_snapshot/my_backup/snapshot_1/_restore?pretty"

# Listar snapshots
curl -X GET "localhost:9200/_snapshot/my_backup/_all?pretty"

# Excluir snapshot
curl -X DELETE "localhost:9200/_snapshot/my_backup/snapshot_1?pretty"

Otimização de Desempenho

Configurações de Índice

# Desativar refresh durante indexação em lote
curl -X PUT "localhost:9200/products/_settings?pretty" -H 'Content-Type: application/json' -d'
{
  "index": {
    "refresh_interval": "-1"
  }
}
'

# Reativar após indexação em lote
curl -X PUT "localhost:9200/products/_settings?pretty" -H 'Content-Type: application/json' -d'
{
  "index": {
    "refresh_interval": "1s"
  }
}
'

# Forçar mesclagem (otimizar)
curl -X POST "localhost:9200/products/_forcemerge?max_num_segments=1&pretty"

Limpeza de Cache

# Limpar todos os caches
curl -X POST "localhost:9200/_cache/clear?pretty"

# Limpar cache específico
curl -X POST "localhost:9200/products/_cache/clear?query=true&pretty"

Monitoramento e Solução de Problemas

# Tarefas pendentes
curl -X GET "localhost:9200/_cat/pending_tasks?v"

# Estatísticas da pool de threads
curl -X GET "localhost:9200/_cat/thread_pool?v"

# Informações de segmento
curl -X GET "localhost:9200/_cat/segments?v"

# Informações de recuperação
curl -X GET "localhost:9200/_cat/recovery?v&h=index,stage,time"

# API de tarefas
curl -X GET "localhost:9200/_tasks?detailed=true&pretty"

Exemplos do Cliente Python

from elasticsearch import Elasticsearch

# Conectar ao Elasticsearch
es = Elasticsearch(['http://localhost:9200'])

# Indexar documento
doc = {
    'name': 'Laptop',
    'price': 999.99,
    'tags': ['electronics']
}
es.index(index='products', id=1, document=doc)

# Buscar
resp = es.search(index='products', query={'match': {'name': 'laptop'}})
for hit in resp['hits']['hits']:
    print(hit['_source'])

# Indexação em lote
from elasticsearch.helpers import bulk

actions = [
    {
        '_index': 'products',
        '_id': i,
        '_source': {'name': f'Product {i}', 'price': i * 10}
    }
    for i in range(1000)
]
bulk(es, actions)

Exemplos do Cliente JavaScript/Node.js

O cliente JavaScript do Elasticsearch fornece uma maneira segura de tipo para interagir com seu cluster. Para aplicações de produção, considere usar TypeScript para melhor segurança de tipo e autocompletar. Veja nossa TypeScript Cheatsheet para melhores práticas sobre definições de tipo e interfaces.

const { Client } = require('@elastic/elasticsearch');
const client = new Client({ node: 'http://localhost:9200' });

// Indexar documento
async function indexDoc() {
  await client.index({
    index: 'products',
    id: 1,
    document: {
      name: 'Laptop',
      price: 999.99
    }
  });
}

// Buscar
async function search() {
  const result = await client.search({
    index: 'products',
    query: {
      match: { name: 'laptop' }
    }
  });
  console.log(result.hits.hits);
}

// Indexação em lote
async function bulkIndex() {
  const operations = [];
  for (let i = 0; i < 1000; i++) {
    operations.push({ index: { _index: 'products', _id: i } });
    operations.push({ name: `Product ${i}`, price: i * 10 });
  }
  await client.bulk({ operations });
}

Exemplo TypeScript com Tipagem Forte

import { Client } from '@elastic/elasticsearch';

interface Product {
  name: string;
  price: number;
  tags?: string[];
  created_at?: Date;
}

const client = new Client({ node: 'http://localhost:9200' });

async function indexProduct(product: Product, id: number): Promise<void> {
  await client.index<Product>({
    index: 'products',
    id: id.toString(),
    document: product
  });
}

async function searchProducts(query: string): Promise<Product[]> {
  const result = await client.search<Product>({
    index: 'products',
    query: {
      match: { name: query }
    }
  });
  
  return result.hits.hits.map(hit => hit._source as Product);
}

Boas Práticas

Design de Índice

  • Mantenha o tamanho do shard entre 20-50GB para desempenho ótimo
  • Use o gerenciamento de ciclo de vida de índice (ILM) para dados de série temporal
  • Projete os mapeamentos com cuidado antes de indexar dados
  • Use tipos de campo apropriados (keyword vs text, formatos de data)
  • Desative _source para documentos grandes se não for necessário

Otimização de Consultas

  • Use filtros em vez de consultas quando não for necessário pontuação
  • Prefira consultas de nível de termo para dados estruturados
  • Use a consulta bool para combinar eficientemente múltiplas condições
  • Implemente paginação com search_after para paginação profunda
  • Cache filtros frequentemente usados

Desempenho de Indexação

  • Use a API de indexação em lote para indexação em lote (1000-5000 documentos por solicitação)
  • Desative o refresh durante operações de indexação em lote
  • Aumente index.refresh_interval durante indexação intensiva
  • Use múltiplos threads/trabalhadores para indexação paralela
  • Considere usar roteamento para melhor distribuição de shard

Gerenciamento de Cluster

  • Monitore a saúde do cluster regularmente
  • Configure a replicação apropriada
  • Use nós mestres dedicados para clusters grandes
  • Implemente uma estratégia adequada de backup com snapshots
  • Monitore o uso da memória JVM (mantenha abaixo de 75%)

Segurança

  • Ative autenticação e autorização (X-Pack Security)
  • Use HTTPS para implantações em produção (configure o cURL com --cacert, --cert e --key para SSL/TLS)
  • Implemente controle de acesso baseado em papel
  • Atualizações e patches de segurança regulares
  • Criptografe dados em repouso e em trânsito

Casos de Uso Comuns

Busca de Texto Completo

O Elasticsearch destaca-se na busca de texto completo com recursos como:

  • Pontuação de relevância
  • Correspondência fuzzy
  • Correspondência de frase
  • Tratamento de sinônimos
  • Suporte multilíngue

Análise de Log (Pilha ELK)

  • Coletar logs com Logstash/Filebeat
  • Indexar e buscar logs no Elasticsearch
  • Visualizar com dashboards do Kibana
  • Configurar alertas para anomalias

Busca de E-commerce

  • Busca no catálogo de produtos
  • Navegação facetada com agregações
  • Autocompleto e sugestões
  • Resultados de busca personalizados

Monitoramento de Desempenho de Aplicativos

  • Indexar métricas de aplicativos
  • Dashboards de monitoramento em tempo real
  • Detecção de anomalias
  • Análise de tendências de desempenho

Recursos Oficiais do Elasticsearch

Cheatsheets e Guias Relacionados