Scheda di riferimento per Elasticsearch: comandi essenziali e consigli

Comandi Elasticsearch per la ricerca, l'indicizzazione e l'analisi

Indice

Elasticsearch è un potente motore di ricerca e analisi distribuito basato su Apache Lucene. Questa guida completa copre comandi essenziali, best practice e riferimenti rapidi per lavorare con i cluster Elasticsearch.

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 la nostra Scheda di Riferimento cURL per tecniche dettagliate di richiesta 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. Puoi personalizzare queste richieste con header aggiuntivi, autenticazione e altre opzioni secondo le necessità.

# Controllo di base dello stato
curl -X GET "localhost:9200/_cluster/health?pretty"

# Stato del cluster dettagliato con informazioni sui shard
curl -X GET "localhost:9200/_cluster/health?level=shards&pretty"

# Verifica delle informazioni sui nodi
curl -X GET "localhost:9200/_cat/nodes?v"

# Verifica delle 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 Eliminazione degli Indici

# Crea indice
curl -X PUT "localhost:9200/my_index?pretty"

# Crea 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
  }
}
'

# Elimina 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 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 mappatura
curl -X GET "localhost:9200/products/_mapping?pretty"

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

Template degli Indici

# Crea template 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 template
curl -X GET "localhost:9200/_index_template?pretty"

Operazioni sui Documenti (CRUD)

Creazione Documenti

# Indica 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"]
}
'

# Indica 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 Documenti

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

# Ottieni più 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 il documento esiste
curl -I "localhost:9200/products/_doc/1"

Aggiornamento Documenti

# Aggiorna 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
}
'

Eliminazione Documenti

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

# Elimina 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 Base

# Match 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 (multipli valori)
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 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 (raggruppa 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 temporale
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 nidificate

# Aggregazioni nidificate
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": {} }
}
'

# Ricerca dopo (per paginazione profonda)
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 Campi ed Evidenziazione

# Seleziona campi specifici
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": { "match_all": {} },
  "_source": ["name", "price"]
}
'

# Evidenziazione
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 alias
curl -X POST "localhost:9200/_aliases?pretty" -H 'Content-Type: application/json' -d'
{
  "actions": [
    { "add": { "index": "products_v1", "alias": "products" }}
  ]
}
'

# Sposta alias su nuovo indice (senza tempi di inattività)
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 alias
curl -X GET "localhost:9200/_cat/aliases?v"

Reindicizzazione

# Reindicizza da un indice all'altro
curl -X POST "localhost:9200/_reindex?pretty" -H 'Content-Type: application/json' -d'
{
  "source": {
    "index": "old_products"
  },
  "dest": {
    "index": "new_products"
  }
}
'

# Reindicizza 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"
  }
}
'

Snapshot e Backup

# Registra repository 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 snapshot
curl -X PUT "localhost:9200/_snapshot/my_backup/snapshot_1?wait_for_completion=true&pretty"

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

# Elenco snapshot
curl -X GET "localhost:9200/_snapshot/my_backup/_all?pretty"

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

Ottimizzazione delle Prestazioni

Impostazioni dell’Indice

# Disabilita refresh durante l'indicizzazione in blocco
curl -X PUT "localhost:9200/products/_settings?pretty" -H 'Content-Type: application/json' -d'
{
  "index": {
    "refresh_interval": "-1"
  }
}
'

# Riabilita dopo l'indicizzazione in blocco
curl -X PUT "localhost:9200/products/_settings?pretty" -H 'Content-Type: application/json' -d'
{
  "index": {
    "refresh_interval": "1s"
  }
}
'

# Forza merge (ottimizza)
curl -X POST "localhost:9200/products/_forcemerge?max_num_segments=1&pretty"

Cancellazione della Cache

# Cancella tutte le cache
curl -X POST "localhost:9200/_cache/clear?pretty"

# Cancella cache specifica
curl -X POST "localhost:9200/products/_cache/clear?query=true&pretty"

Monitoraggio e Risoluzione dei Problemi

# Task in attesa
curl -X GET "localhost:9200/_cat/pending_tasks?v"

# Statistiche pool thread
curl -X GET "localhost:9200/_cat/thread_pool?v"

# Informazioni segmenti
curl -X GET "localhost:9200/_cat/segments?v"

# Informazioni recupero
curl -X GET "localhost:9200/_cat/recovery?v&h=index,stage,time"

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

Esempi Client Python

from elasticsearch import Elasticsearch

# Connetti a Elasticsearch
es = Elasticsearch(['http://localhost:9200'])

# Indica 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 Client JavaScript/Node.js

Il client JavaScript di Elasticsearch fornisce un modo type-safe per interagire con il tuo cluster. Per applicazioni in produzione, considera l’uso di TypeScript per una migliore sicurezza dei tipi e il completamento automatico. Consulta la nostra Scheda di Riferimento TypeScript per le migliori pratiche su definizioni di tipo e interfacce.

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

// Indica 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 Tipizzazione 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 dell’Indice

  • Mantieni la dimensione dello shard tra 20-50GB per prestazioni ottimali
  • Utilizza la gestione del ciclo di vita degli indici (ILM) per i dati time-series
  • Progetta attentamente le mappature prima di indicizzare i dati
  • Usa i tipi di campo appropriati (keyword vs text, formati data)
  • Disabilita _source per documenti grandi se non necessario

Ottimizzazione delle Query

  • Usa filtri invece di query quando il punteggio non è necessario
  • Preferisci query a livello di termine per dati strutturati
  • Usa la query bool per combinare efficientemente più condizioni
  • Implementa la paginazione con search_after per la paginazione profonda
  • Metti in cache i filtri usati frequentemente

Prestazioni di Indicizzazione

  • Usa l’API bulk per l’indicizzazione in blocco (1000-5000 documenti per richiesta)
  • Disabilita il refresh durante le operazioni bulk
  • Aumenta index.refresh_interval durante l’indicizzazione pesante
  • Usa più thread/lavoratori per l’indicizzazione parallela
  • Considera l’uso del routing per una migliore distribuzione degli shard

Gestione del Cluster

  • Monitora regolarmente lo stato del cluster
  • Configura adeguatamente i replica
  • Usa nodi master dedicati per cluster grandi
  • Implementa una strategia di backup corretta con snapshot
  • Monitora l’utilizzo dell’heap JVM (mantienilo sotto il 75%)

Sicurezza

  • Abilita autenticazione e autorizzazione (X-Pack Security)
  • Usa HTTPS per le implementazioni in produzione (configura cURL con le opzioni --cacert, --cert e --key per SSL/TLS)
  • Implementa un controllo degli accessi basato sui ruoli appropriato
  • Esegui aggiornamenti e patch di sicurezza regolari
  • Cripta i dati a riposo e in transito

Casi d’Uso Comuni

Ricerca Full-Text

Elasticsearch eccelle nella ricerca full-text con funzionalità come:

Analisi Log (Stack ELK)

  • Raccogli log con Logstash/Filebeat
  • Indica e cerca log in Elasticsearch
  • Visualizza con dashboard di Kibana
  • Configura alert per anomalie

Ricerca E-commerce

  • Ricerca catalogo prodotti
  • Navigazione a faccette con aggregazioni
  • Auto-completamento e suggerimenti
  • Risultati di ricerca personalizzati

Monitoraggio Prestazioni Applicazioni

  • Indica metriche delle applicazioni
  • Dashboard di monitoraggio in tempo reale
  • Rilevamento anomalie
  • Analisi delle tendenze delle prestazioni

Risorse Ufficiali Elasticsearch

Schede di Riferimento e Guide Correlate

Iscriviti

Ricevi nuovi articoli su sistemi, infrastruttura e ingegneria AI.