Elasticsearch Cheatsheet: Comandi essenziali e consigli
Comandi di Elasticsearch per la ricerca, l'indicizzazione e l'analisi
Elasticsearch è un potente motore di ricerca e analisi distribuito costruito su Apache Lucene. Questo completo riferimento rapido copre comandi essenziali, best practice e riferimenti rapidi per lavorare con i cluster Elasticsearch.

Nota: La maggior parte degli esempi in questa guida utilizza cURL per le richieste HTTP. Se sei nuovo a cURL o hai bisogno di un riferimento rapido per opzioni avanzate, consulta il nostro cURL Cheatsheet per tecniche dettagliate per le richieste HTTP da riga di comando.
Gestione del Cluster
Verifica dello Stato del Cluster
Tutti i comandi in questa sezione utilizzano cURL per interagire con l’API REST di Elasticsearch. È possibile personalizzare queste richieste con ulteriori intestazioni, autenticazione e altre opzioni come necessario.
# Controllo di base
curl -X GET "localhost:9200/_cluster/health?pretty"
# Dettagliato stato del cluster con informazioni sui shard
curl -X GET "localhost:9200/_cluster/health?level=shards&pretty"
# Verifica informazioni sui nodi
curl -X GET "localhost:9200/_cat/nodes?v"
# Verifica le impostazioni del cluster
curl -X GET "localhost:9200/_cluster/settings?pretty"
Operazioni sui Nodi
# Elenco di tutti i nodi
curl -X GET "localhost:9200/_cat/nodes?v&h=name,node.role,heap.percent,ram.percent,cpu,load_1m"
# Statistiche dei nodi
curl -X GET "localhost:9200/_nodes/stats?pretty"
# Thread caldi (risoluzione dei problemi)
curl -X GET "localhost:9200/_nodes/hot_threads"
Gestione degli Indici
Creazione e Cancellazione degli Indici
# Crea un indice
curl -X PUT "localhost:9200/my_index?pretty"
# Crea un indice con impostazioni
curl -X PUT "localhost:9200/my_index" -H 'Content-Type: application/json' -d'
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1
}
}
'
# Cancella un indice
curl -X DELETE "localhost:9200/my_index?pretty"
# Elenco di tutti gli indici
curl -X GET "localhost:9200/_cat/indices?v"
# Statistiche dell'indice
curl -X GET "localhost:9200/my_index/_stats?pretty"
Mappature degli Indici
# Definisci la mappatura
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"
}
}
}
}
'
# Ottieni la mappatura
curl -X GET "localhost:9200/products/_mapping?pretty"
# Aggiorna la mappatura (aggiungi un campo)
curl -X PUT "localhost:9200/products/_mapping" -H 'Content-Type: application/json' -d'
{
"properties": {
"category": { "type": "keyword" }
}
}
'
Modelli di Indice
# Crea un modello di indice
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" }
}
}
}
}
'
# Elenco dei modelli
curl -X GET "localhost:9200/_index_template?pretty"
Operazioni sui Documenti (CRUD)
Creazione di Documenti
# Indice di un documento con ID generato automaticamente
curl -X POST "localhost:9200/products/_doc?pretty" -H 'Content-Type: application/json' -d'
{
"name": "Laptop",
"price": 999.99,
"tags": ["electronics", "computers"]
}
'
# Indice di un documento con ID specifico
curl -X PUT "localhost:9200/products/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
"name": "Laptop",
"price": 999.99
}
'
# Indicizzazione in blocco
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 }
'
Lettura di Documenti
# Ottieni un documento per ID
curl -X GET "localhost:9200/products/_doc/1?pretty"
# Ottieni diversi documenti
curl -X GET "localhost:9200/_mget?pretty" -H 'Content-Type: application/json' -d'
{
"docs": [
{ "_index": "products", "_id": "1" },
{ "_index": "products", "_id": "2" }
]
}
'
# Verifica se un documento esiste
curl -I "localhost:9200/products/_doc/1"
Aggiornamento di Documenti
# Aggiorna un documento
curl -X POST "localhost:9200/products/_update/1?pretty" -H 'Content-Type: application/json' -d'
{
"doc": {
"price": 899.99
}
}
'
# Aggiorna con 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 (aggiorna o inserisci)
curl -X POST "localhost:9200/products/_update/1?pretty" -H 'Content-Type: application/json' -d'
{
"doc": {
"price": 899.99
},
"doc_as_upsert": true
}
'
Cancellazione di Documenti
# Cancella per ID
curl -X DELETE "localhost:9200/products/_doc/1?pretty"
# Cancella per query
curl -X POST "localhost:9200/products/_delete_by_query?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"match": {
"name": "old"
}
}
}
'
Query di Ricerca
Ricerca di Base
# Trova tutto
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"match_all": {}
}
}
'
# Query match
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"match": {
"name": "laptop"
}
}
}
'
# Query multi-match
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"multi_match": {
"query": "laptop gaming",
"fields": ["name", "description"]
}
}
}
'
Query a Livello di Termine
# Query term (corrispondenza esatta)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"term": {
"tags": "electronics"
}
}
}
'
# Query terms (valori multipli)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"terms": {
"tags": ["electronics", "computers"]
}
}
}
'
# Query range
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"range": {
"price": {
"gte": 100,
"lte": 1000
}
}
}
}
'
# Query exists
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"exists": {
"field": "description"
}
}
}
'
Query Booleane
# Query 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" }}
]
}
}
}
'
Ricerca Avanzata
# Query wildcard
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"wildcard": {
"name": "lap*"
}
}
}
'
# Query fuzzy (tolleranza agli errori di battitura)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"fuzzy": {
"name": {
"value": "laptpo",
"fuzziness": "AUTO"
}
}
}
}
'
# Query prefix
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"prefix": {
"name": "lap"
}
}
}
'
Aggregazioni
Aggregazioni Metriche
# Media, somma, minimo, massimo
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" }}
}
}
'
# Aggregazione stats
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"size": 0,
"aggs": {
"price_stats": {
"stats": { "field": "price" }
}
}
}
'
Aggregazioni Bucket
# Aggregazione terms (gruppo per)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"size": 0,
"aggs": {
"popular_tags": {
"terms": {
"field": "tags",
"size": 10
}
}
}
}
'
# Aggregazione range
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 }
]
}
}
}
}
'
# Istogramma per 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"
}
}
}
}
'
Aggregazioni Nested
# Aggregazioni nested
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" }
}
}
}
}
}
'
Ordinamento e Paginazione
# Ordina per 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" }}
]
}
'
# Paginazione con 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 (per paginazione avanzata)
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"]
}
'
Selezione dei Campi e Highlighting
# Seleziona campi specifici
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": { "match_all": {} },
"_source": ["name", "price"]
}
'
# Highlighting
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"match": { "description": "gaming laptop" }
},
"highlight": {
"fields": {
"description": {}
}
}
}
'
Alias degli Indici
# Crea un alias
curl -X POST "localhost:9200/_aliases?pretty" -H 'Content-Type: application/json' -d'
{
"actions": [
{ "add": { "index": "products_v1", "alias": "products" }}
]
}
'
# Passa l'alias a un nuovo indice (senza interruzioni)
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" }}
]
}
'
# Elenco degli alias
curl -X GET "localhost:9200/_cat/aliases?v"
Reindex
# Reindex da un indice a un altro
curl -X POST "localhost:9200/_reindex?pretty" -H 'Content-Type: application/json' -d'
{
"source": {
"index": "old_products"
},
"dest": {
"index": "new_products"
}
}
'
# Reindex con query
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
# Registra il repository dei snapshot
curl -X PUT "localhost:9200/_snapshot/my_backup?pretty" -H 'Content-Type: application/json' -d'
{
"type": "fs",
"settings": {
"location": "/mount/backups/my_backup"
}
}
'
# Crea un snapshot
curl -X PUT "localhost:9200/_snapshot/my_backup/snapshot_1?wait_for_completion=true&pretty"
# Ripristina un snapshot
curl -X POST "localhost:9200/_snapshot/my_backup/snapshot_1/_restore?pretty"
# Elenco dei snapshot
curl -X GET "localhost:9200/_snapshot/my_backup/_all?pretty"
# Cancella un snapshot
curl -X DELETE "localhost:9200/_snapshot/my_backup/snapshot_1?pretty"
Ottimizzazione delle Prestazioni
Impostazioni degli Indici
# Disattiva il refresh durante l'indicizzazione in blocco
curl -X PUT "localhost:9200/products/_settings?pretty" -H 'Content-Type: application/json' -d'
{
"index": {
"refresh_interval": "-1"
}
}
'
# Riattiva dopo l'indicizzazione in blocco
curl -X PUT "localhost:9200/products/_settings?pretty" -H 'Content-Type: application/json' -d'
{
"index": {
"refresh_interval": "1s"
}
}
'
# Forza il merge (ottimizza)
curl -X POST "localhost:9200/products/_forcemerge?max_num_segments=1&pretty"
Pulizia della Cache
# Pulisci tutte le cache
curl -X POST "localhost:9200/_cache/clear?pretty"
# Pulisci una cache specifica
curl -X POST "localhost:9200/products/_cache/clear?query=true&pretty"
Monitoraggio e Risoluzione dei Problemi
# Compiti pendenti
curl -X GET "localhost:9200/_cat/pending_tasks?v"
# Statistiche del thread pool
curl -X GET "localhost:9200/_cat/thread_pool?v"
# Informazioni sui segmenti
curl -X GET "localhost:9200/_cat/segments?v"
# Informazioni sul recupero
curl -X GET "localhost:9200/_cat/recovery?v&h=index,stage,time"
# API dei compiti
curl -X GET "localhost:9200/_tasks?detailed=true&pretty"
Esempi del Client Python
from elasticsearch import Elasticsearch
# Connetti a Elasticsearch
es = Elasticsearch(['http://localhost:9200'])
# Indice di un documento
doc = {
'name': 'Laptop',
'price': 999.99,
'tags': ['electronics']
}
es.index(index='products', id=1, document=doc)
# Ricerca
resp = es.search(index='products', query={'match': {'name': 'laptop'}})
for hit in resp['hits']['hits']:
print(hit['_source'])
# Indicizzazione in blocco
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)
Esempi del Client JavaScript/Node.js
Il client JavaScript di Elasticsearch fornisce un modo type-safe per interagire con il tuo cluster. Per applicazioni di produzione, considera l’uso di TypeScript per una maggiore sicurezza dei tipi e completamento automatico. Vedi il nostro TypeScript Cheatsheet per best practice sui tipi di definizione e interfacce.
const { Client } = require('@elastic/elasticsearch');
const client = new Client({ node: 'http://localhost:9200' });
// Indice di un documento
async function indexDoc() {
await client.index({
index: 'products',
id: 1,
document: {
name: 'Laptop',
price: 999.99
}
});
}
// Ricerca
async function search() {
const result = await client.search({
index: 'products',
query: {
match: { name: 'laptop' }
}
});
console.log(result.hits.hits);
}
// Indicizzazione in blocco
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 });
}
Esempio TypeScript con Typing 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);
}
Best Practice
Progettazione degli Indici
- Mantieni la dimensione dei shard tra 20-50GB per prestazioni ottimali
- Usa la gestione del ciclo di vita degli indici (ILM) per i dati a serie temporale
- Progetta le mappature con attenzione prima dell’indicizzazione dei dati
- Usa i tipi di campo appropriati (keyword vs text, formati data)
- Disattiva
_sourceper documenti grandi se non necessario
Ottimizzazione delle Query
- Usa i filtri invece delle query quando non è necessario il punteggio
- Preferisci le query a livello di termine per i dati strutturati
- Usa la query
boolper combinare efficacemente diverse condizioni - Implementa la paginazione con
search_afterper la paginazione avanzata - Cachizza i filtri frequentemente utilizzati
Prestazioni dell’Indicizzazione
- Usa l’API bulk per l’indicizzazione in batch (1000-5000 documenti per richiesta)
- Disattiva il refresh durante le operazioni di indicizzazione
- Aumenta
index.refresh_intervaldurante l’indicizzazione intensiva - Usa diversi thread/lavoratori per l’indicizzazione parallela
- Considera l’uso del routing per una distribuzione migliore dei shard
Gestione del Cluster
- Monitora regolarmente lo stato del cluster
- Configura correttamente il numero di repliche
- Usa nodi master dedicati per i cluster grandi
- Implementa una strategia di backup appropriata con snapshot
- Monitora l’uso della memoria JVM (mantieni sotto il 75%)
Sicurezza
- Abilita autenticazione e autorizzazione (X-Pack Security)
- Usa HTTPS per le distribuzioni in produzione (configura cURL con
--cacert,--certe--keyper SSL/TLS) - Implementa il controllo degli accessi basato sui ruoli
- Aggiornamenti e patch di sicurezza regolari
- Crittografa i dati a riposo e in transito
Caso d’Uso Comuni
Ricerca Testuale Completa
Elasticsearch eccelle nella ricerca testuale completa con funzionalità come:
- Punteggio di rilevanza
- Corrispondenza fuzzy
- Corrispondenza di frase
- Gestione di sinonimi
- Supporto multilingua
Analisi dei Log (Stack ELK)
- Raccogli i log con Logstash/Filebeat
- Indicizza e cerca i log in Elasticsearch
- Visualizza con dashboard di Kibana
- Configura allarmi per anomalie
Ricerca E-commerce
- Ricerca nel catalogo dei prodotti
- Navigazione con filtri tramite aggregazioni
- Auto-complete e suggerimenti
- Risultati di ricerca personalizzati
Monitoraggio delle Prestazioni delle Applicazioni
- Indicizza le metriche delle applicazioni
- Dashboard di monitoraggio in tempo reale
- Rilevamento di anomalie
- Analisi delle tendenze delle prestazioni
Link Utili
Risorse Elasticsearch Ufficiali
- Documentazione Ufficiale di Elasticsearch
- Riferimento API di Elasticsearch
- Guida al Query DSL
- Client Python di Elasticsearch
- Client JavaScript di Elasticsearch
- Panoramica dell’Elastic Stack
- Ottimizzazione delle Prestazioni di Elasticsearch
- Gestione del Ciclo di Vita degli Indici
Altri Riferimenti e Guide
- cURL Cheatsheet - Essenziale per padroneggiare le richieste HTTP all’API REST di Elasticsearch
- TypeScript Cheatsheet: Concetti di Base e Best Practice - Costruisci applicazioni client Elasticsearch con sicurezza dei tipi