Elasticsearch-Cheatsheet: Wichtige Befehle & Tipps
Elasticsearch-Befehle für Suche, Indexierung und Analysen
Elasticsearch ist ein leistungsstarkes verteiltes Such- und Analyse-Engine, das auf Apache Lucene basiert. Dieses umfassende Cheat-Sheet behandelt wesentliche Befehle, Best Practices und schnelle Referenzen für die Arbeit mit Elasticsearch-Clustern.

Hinweis: Die meisten Beispiele in dieser Anleitung verwenden cURL für HTTP-Anfragen. Wenn Sie neu bei cURL sind oder eine schnelle Referenz für erweiterte Optionen benötigen, besuchen Sie unseren cURL Cheatsheet für detaillierte Command-Line-HTTP-Anfragen-Techniken.
Cluster-Verwaltung
Cluster-Status prüfen
Alle Befehle in diesem Abschnitt verwenden cURL, um mit der REST-API von Elasticsearch zu interagieren. Sie können diese Anfragen mit zusätzlichen Headern, Authentifizierung und anderen Optionen nach Bedarf anpassen.
# Grundlegende Statusprüfung
curl -X GET "localhost:9200/_cluster/health?pretty"
# Detaillierter Cluster-Status mit Shard-Informationen
curl -X GET "localhost:9200/_cluster/health?level=shards&pretty"
# Knoteninformationen abrufen
curl -X GET "localhost:9200/_cat/nodes?v"
# Cluster-Einstellungen prüfen
curl -X GET "localhost:9200/_cluster/settings?pretty"
Knoten-Operationen
# Alle Knoten auflisten
curl -X GET "localhost:9200/_cat/nodes?v&h=name,node.role,heap.percent,ram.percent,cpu,load_1m"
# Knoten-Statistiken
curl -X GET "localhost:9200/_nodes/stats?pretty"
# Heiße Threads (Fehlerbehebung)
curl -X GET "localhost:9200/_nodes/hot_threads"
Index-Verwaltung
Indizes erstellen und löschen
# Index erstellen
curl -X PUT "localhost:9200/my_index?pretty"
# Index mit Einstellungen erstellen
curl -X PUT "localhost:9200/my_index" -H 'Content-Type: application/json' -d'
{
"settings": {
"number_of_shards": 3,
"number_of_replicas": 1
}
}
'
# Index löschen
curl -X DELETE "localhost:9200/my_index?pretty"
# Alle Indizes auflisten
curl -X GET "localhost:9200/_cat/indices?v"
# Index-Statistiken
curl -X GET "localhost:9200/my_index/_stats?pretty"
Index-Mappings
# Mapping definieren
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"
}
}
}
}
'
# Mapping abrufen
curl -X GET "localhost:9200/products/_mapping?pretty"
# Mapping aktualisieren (Feld hinzufügen)
curl -X PUT "localhost:9200/products/_mapping" -H 'Content-Type: application/json' -d'
{
"properties": {
"category": { "type": "keyword" }
}
}
'
Index-Vorlagen
# Index-Vorlage erstellen
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" }
}
}
}
}
'
# Vorlagen auflisten
curl -X GET "localhost:9200/_index_template?pretty"
Dokument-Operationen (CRUD)
Dokumente erstellen
# Dokument mit automatisch generierter ID indizieren
curl -X POST "localhost:9200/products/_doc?pretty" -H 'Content-Type: application/json' -d'
{
"name": "Laptop",
"price": 999.99,
"tags": ["electronics", "computers"]
}
'
# Dokument mit spezifischer ID indizieren
curl -X PUT "localhost:9200/products/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
"name": "Laptop",
"price": 999.99
}
'
# Massenindizierung
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 }
'
Dokumente lesen
# Dokument per ID abrufen
curl -X GET "localhost:9200/products/_doc/1?pretty"
# Mehrere Dokumente abrufen
curl -X GET "localhost:9200/_mget?pretty" -H 'Content-Type: application/json' -d'
{
"docs": [
{ "_index": "products", "_id": "1" },
{ "_index": "products", "_id": "2" }
]
}
'
# Prüfen, ob Dokument existiert
curl -I "localhost:9200/products/_doc/1"
Dokumente aktualisieren
# Dokument aktualisieren
curl -X POST "localhost:9200/products/_update/1?pretty" -H 'Content-Type: application/json' -d'
{
"doc": {
"price": 899.99
}
}
'
# Aktualisierung mit Skript
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 (Aktualisieren oder Einfügen)
curl -X POST "localhost:9200/products/_update/1?pretty" -H 'Content-Type: application/json' -d'
{
"doc": {
"price": 899.99
},
"doc_as_upsert": true
}
'
Dokumente löschen
# Löschen per ID
curl -X DELETE "localhost:9200/products/_doc/1?pretty"
# Löschen per Abfrage
curl -X POST "localhost:9200/products/_delete_by_query?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"match": {
"name": "old"
}
}
}
'
Suchabfragen
Grundlegende Suche
# Alle Treffer
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"match_all": {}
}
}
'
# Match-Abfrage
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"match": {
"name": "laptop"
}
}
}
'
# Multi-Match-Abfrage
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"multi_match": {
"query": "laptop gaming",
"fields": ["name", "description"]
}
}
}
'
Term-Level-Abfragen
# Term-Abfrage (exakte Übereinstimmung)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"term": {
"tags": "electronics"
}
}
}
'
# Terms-Abfrage (mehrere Werte)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"terms": {
"tags": ["electronics", "computers"]
}
}
}
'
# Bereichsabfrage
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"range": {
"price": {
"gte": 100,
"lte": 1000
}
}
}
}
'
# Exists-Abfrage
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"exists": {
"field": "description"
}
}
}
'
Boole’sche Abfragen
# Bool-Abfrage (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" }}
]
}
}
}
'
Erweiterte Suche
# Wildcard-Abfrage
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"wildcard": {
"name": "lap*"
}
}
}
'
# Fuzzy-Abfrage (Rechtschreibfehler-Toleranz)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"fuzzy": {
"name": {
"value": "laptpo",
"fuzziness": "AUTO"
}
}
}
}
'
# Präfix-Abfrage
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"prefix": {
"name": "lap"
}
}
}
'
Aggregationen
Metrik-Aggregationen
# Durchschnitt, Summe, Minimum, Maximum
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" }}
}
}
'
# Statistik-Aggregation
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"size": 0,
"aggs": {
"price_stats": {
"stats": { "field": "price" }
}
}
}
'
Bucket-Aggregationen
# Terms-Aggregation (Gruppieren nach)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"size": 0,
"aggs": {
"popular_tags": {
"terms": {
"field": "tags",
"size": 10
}
}
}
}
'
# Bereichsaggregation
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 }
]
}
}
}
}
'
# Datums-Histogramm
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"
}
}
}
}
'
Verschachtelte Aggregationen
# Verschachtelte Aggregationen
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" }
}
}
}
}
}
'
Sortierung und Paginierung
# Sortieren nach Feld
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": { "match_all": {} },
"sort": [
{ "price": { "order": "desc" }},
{ "_score": { "order": "desc" }}
]
}
'
# Paginierung mit 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 (für tiefe Paginierung)
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"]
}
'
Feldauswahl und Hervorhebung
# Wählen Sie spezifische Felder aus
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": { "match_all": {} },
"_source": ["name", "price"]
}
'
# Hervorhebung
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"match": { "description": "gaming laptop" }
},
"highlight": {
"fields": {
"description": {}
}
}
}
'
Index-Aliasse
# Alias erstellen
curl -X POST "localhost:9200/_aliases?pretty" -H 'Content-Type: application/json' -d'
{
"actions": [
{ "add": { "index": "products_v1", "alias": "products" }}
]
}
'
# Alias zu neuem Index wechseln (keine Ausfallzeit)
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" }}
]
}
'
# Aliasse auflisten
curl -X GET "localhost:9200/_cat/aliases?v"
Neuindizierung
# Neuindizierung von einem Index in einen anderen
curl -X POST "localhost:9200/_reindex?pretty" -H 'Content-Type: application/json' -d'
{
"source": {
"index": "old_products"
},
"dest": {
"index": "new_products"
}
}
'
# Neuindizierung mit Abfrage
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 und Backups
# Snapshot-Repository registrieren
curl -X PUT "localhost:9200/_snapshot/my_backup?pretty" -H 'Content-Type: application/json' -d'
{
"type": "fs",
"settings": {
"location": "/mount/backups/my_backup"
}
}
'
# Snapshot erstellen
curl -X PUT "localhost:9200/_snapshot/my_backup/snapshot_1?wait_for_completion=true&pretty"
# Snapshot wiederherstellen
curl -X POST "localhost:9200/_snapshot/my_backup/snapshot_1/_restore?pretty"
# Snapshots auflisten
curl -X GET "localhost:9200/_snapshot/my_backup/_all?pretty"
# Snapshot löschen
curl -X DELETE "localhost:9200/_snapshot/my_backup/snapshot_1?pretty"
Leistungsoptimierung
Index-Einstellungen
# Deaktivieren Sie das Aktualisieren während des Massenindexierens
curl -X PUT "localhost:9200/products/_settings?pretty" -H 'Content-Type: application/json' -d'
{
"index": {
"refresh_interval": "-1"
}
}
'
# Reaktivieren nach Massenindexierung
curl -X PUT "localhost:9200/products/_settings?pretty" -H 'Content-Type: application/json' -d'
{
"index": {
"refresh_interval": "1s"
}
}
'
# Erzwingen Sie das Zusammenführen (Optimieren)
curl -X POST "localhost:9200/products/_forcemerge?max_num_segments=1&pretty"
Cache-Leeren
# Alle Caches leeren
curl -X POST "localhost:9200/_cache/clear?pretty"
# Spezifischen Cache leeren
curl -X POST "localhost:9200/products/_cache/clear?query=true&pretty"
Überwachung und Fehlerbehebung
# Ausstehende Aufgaben
curl -X GET "localhost:9200/_cat/pending_tasks?v"
# Thread-Pool-Statistiken
curl -X GET "localhost:9200/_cat/thread_pool?v"
# Segmentinformationen
curl -X GET "localhost:9200/_cat/segments?v"
# Wiederherstellungsinformationen
curl -X GET "localhost:9200/_cat/recovery?v&h=index,stage,time"
# Aufgaben-API
curl -X GET "localhost:9200/_tasks?detailed=true&pretty"
Python-Client-Beispiele
from elasticsearch import Elasticsearch
# Verbindung zu Elasticsearch herstellen
es = Elasticsearch(['http://localhost:9200'])
# Dokument indizieren
doc = {
'name': 'Laptop',
'price': 999.99,
'tags': ['electronics']
}
es.index(index='products', id=1, document=doc)
# Suche
resp = es.search(index='products', query={'match': {'name': 'laptop'}})
for hit in resp['hits']['hits']:
print(hit['_source'])
# Massenindexierung
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)
JavaScript/Node.js-Client-Beispiele
Der Elasticsearch-JavaScript-Client bietet eine typensichere Möglichkeit, mit Ihrem Cluster zu interagieren. Für Produktionsanwendungen sollten Sie TypeScript für eine bessere Typensicherheit und Autovervollständigung verwenden. Sehen Sie sich unseren TypeScript-Cheatsheet für Best Practices zu Typdefinitionen und Schnittstellen an.
const { Client } = require('@elastic/elasticsearch');
const client = new Client({ node: 'http://localhost:9200' });
// Dokument indizieren
async function indexDoc() {
await client.index({
index: 'products',
id: 1,
document: {
name: 'Laptop',
price: 999.99
}
});
}
// Suche
async function search() {
const result = await client.search({
index: 'products',
query: {
match: { name: 'laptop' }
}
});
console.log(result.hits.hits);
}
// Massenindexierung
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 });
}
TypeScript-Beispiel mit starker Typisierung
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 Practices
Index-Design
- Halten Sie die Shard-Größe zwischen 20-50GB für optimale Leistung
- Verwenden Sie Index-Lifecycle-Management (ILM) für Zeitreihendaten
- Entwerfen Sie Mappings sorgfältig, bevor Sie Daten indizieren
- Verwenden Sie geeignete Feldtypen (Keyword vs. Text, Datumsformate)
- Deaktivieren Sie
_sourcefür große Dokumente, wenn nicht benötigt
Abfrageoptimierung
- Verwenden Sie Filter statt Abfragen, wenn Bewertung nicht benötigt wird
- Bevorzugen Sie term-level-Abfragen für strukturierte Daten
- Verwenden Sie
bool-Abfrage, um mehrere Bedingungen effizient zu kombinieren - Implementieren Sie Pagination mit
search_afterfür tiefe Seiten - Cachen Sie häufig verwendete Filter
Indexierungsleistung
- Verwenden Sie die Bulk-API für Batch-Indexierung (1000-5000 Dokumente pro Anfrage)
- Deaktivieren Sie das Aktualisieren während Bulk-Operationen
- Erhöhen Sie
index.refresh_intervalwährend der intensiven Indexierung - Verwenden Sie mehrere Threads/Worker für parallele Indexierung
- Berücksichtigen Sie die Verwendung von Routing für eine bessere Shard-Verteilung
Cluster-Verwaltung
- Überwachen Sie die Cluster-Gesundheit regelmäßig
- Richten Sie eine angemessene Replikakonfiguration ein
- Verwenden Sie dedizierte Master-Knoten für große Cluster
- Implementieren Sie eine angemessene Backup-Strategie mit Snapshots
- Überwachen Sie die JVM-Heap-Nutzung (halten Sie sie unter 75%)
Sicherheit
- Aktivieren Sie Authentifizierung und Autorisierung (X-Pack Security)
- Verwenden Sie HTTPS für Produktionsbereitstellungen (konfigurieren Sie cURL mit
--cacert,--certund--keyOptionen für SSL/TLS) - Implementieren Sie eine angemessene rollenbasierte Zugriffskontrolle
- Regelmäßige Sicherheitsupdates und Patches
- Verschlüsseln Sie Daten im Ruhezustand und während der Übertragung
Häufige Anwendungsfälle
Volltextsuche
Elasticsearch glänzt bei der Volltextsuche mit Funktionen wie:
- Relevanzbewertung
- Fuzzy-Matching
- Phrasen-Matching
- Synonymbehandlung
- Mehrsprachige Unterstützung
Log-Analyse (ELK-Stack)
- Sammeln Sie Logs mit Logstash/Filebeat
- Indizieren und durchsuchen Sie Logs in Elasticsearch
- Visualisieren Sie mit Kibana-Dashboards
- Richten Sie Warnungen für Anomalien ein
E-Commerce-Suche
- Produktkatalogsuche
- Facettierte Navigation mit Aggregationen
- Autovervollständigung und Vorschläge
- Personalisierte Suchergebnisse
Anwendungsleistungsüberwachung
- Indizieren Sie Anwendungsmetriken
- Echtzeit-Überwachungsdashboards
- Anomalieerkennung
- Leistungs-Trendanalyse
Nützliche Links
Offizielle Elasticsearch-Ressourcen
- Offizielle Elasticsearch-Dokumentation
- Elasticsearch-API-Referenz
- Query-DSL-Leitfaden
- Elasticsearch-Python-Client
- Elasticsearch-JavaScript-Client
- Elastic-Stack-Übersicht
- Elasticsearch-Leistungsoptimierung
- Index-Lifecycle-Management
Verwandte Cheatsheets & Leitfäden
- cURL-Cheatsheet - Wesentlich für das Beherrschen von HTTP-Anfragen an die Elasticsearch-REST-API
- TypeScript-Cheatsheet: Kernkonzepte & Best Practices - Bauen Sie typensichere Elasticsearch-Client-Anwendungen