Elasticsearch Cheatsheet: Perintah & Tips Penting

Perintah Elasticsearch untuk pencarian, indeks, dan analitik

Konten Halaman

Elasticsearch adalah mesin pencari dan analitik terdistribusi yang kuat yang dibangun berdasarkan Apache Lucene. Cheatsheet komprehensif ini mencakup perintah penting, praktik terbaik, dan referensi cepat untuk bekerja dengan klaster Elasticsearch.

elasticsearch

Catatan: Kebanyakan contoh dalam panduan ini menggunakan cURL untuk permintaan HTTP. Jika Anda baru dengan cURL atau membutuhkan referensi cepat untuk opsi lanjutan, lihat cURL Cheatsheet kami untuk teknik permintaan HTTP baris perintah yang terperinci.

Manajemen Klaster

Periksa Kesehatan Klaster

Semua perintah dalam bagian ini menggunakan cURL untuk berinteraksi dengan REST API Elasticsearch. Anda dapat menyesuaikan permintaan ini dengan header tambahan, otentikasi, dan opsi lainnya sesuai kebutuhan.

# Pemeriksaan kesehatan dasar
curl -X GET "localhost:9200/_cluster/health?pretty"

# Kesehatan klaster rinci dengan informasi shard
curl -X GET "localhost:9200/_cluster/health?level=shards&pretty"

# Periksa informasi node
curl -X GET "localhost:9200/_cat/nodes?v"

# Periksa pengaturan klaster
curl -X GET "localhost:9200/_cluster/settings?pretty"

Operasi Node

# Daftar semua node
curl -X GET "localhost:9200/_cat/nodes?v&h=name,node.role,heap.percent,ram.percent,cpu,load_1m"

# Statistik node
curl -X GET "localhost:9200/_nodes/stats?pretty"

# Thread panas (pemecahan masalah)
curl -X GET "localhost:9200/_nodes/hot_threads"

Manajemen Indeks

Membuat dan Menghapus Indeks

# Membuat indeks
curl -X PUT "localhost:9200/my_index?pretty"

# Membuat indeks dengan pengaturan
curl -X PUT "localhost:9200/my_index" -H 'Content-Type: application/json' -d'
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1
  }
}
'

# Menghapus indeks
curl -X DELETE "localhost:9200/my_index?pretty"

# Daftar semua indeks
curl -X GET "localhost:9200/_cat/indices?v"

# Statistik indeks
curl -X GET "localhost:9200/my_index/_stats?pretty"

Pemetaan Indeks

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

# Dapatkan pemetaan
curl -X GET "localhost:9200/products/_mapping?pretty"

# Perbarui pemetaan (tambahkan bidang)
curl -X PUT "localhost:9200/products/_mapping" -H 'Content-Type: application/json' -d'
{
  "properties": {
    "category": { "type": "keyword" }
  }
}
'

Template Indeks

# Membuat template indeks
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" }
      }
    }
  }
}
'

# Daftar template
curl -X GET "localhost:9200/_index_template?pretty"

Operasi Dokumen (CRUD)

Membuat Dokumen

# Indeks dokumen dengan ID yang dihasilkan secara otomatis
curl -X POST "localhost:9200/products/_doc?pretty" -H 'Content-Type: application/json' -d'
{
  "name": "Laptop",
  "price": 999.99,
  "tags": ["electronics", "computers"]
}
'

# Indeks dokumen dengan ID tertentu
curl -X PUT "localhost:9200/products/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
  "name": "Laptop",
  "price": 999.99
}
'

# Pemetaan massal
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 }
'

Membaca Dokumen

# Dapatkan dokumen berdasarkan ID
curl -X GET "localhost:9200/products/_doc/1?pretty"

# Dapatkan beberapa dokumen
curl -X GET "localhost:9200/_mget?pretty" -H 'Content-Type: application/json' -d'
{
  "docs": [
    { "_index": "products", "_id": "1" },
    { "_index": "products", "_id": "2" }
  ]
}
'

# Periksa apakah dokumen ada
curl -I "localhost:9200/products/_doc/1"

Memperbarui Dokumen

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

# Perbarui dengan skrip
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 (perbarui atau sisipkan)
curl -X POST "localhost:9200/products/_update/1?pretty" -H 'Content-Type: application/json' -d'
{
  "doc": {
    "price": 899.99
  },
  "doc_as_upsert": true
}
'

Menghapus Dokumen

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

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

Query Pencarian

Pencarian Dasar

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

# Query cocok
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "match": {
      "name": "laptop"
    }
  }
}
'

# Query multi-cocok
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "multi_match": {
      "query": "laptop gaming",
      "fields": ["name", "description"]
    }
  }
}
'

Query Level Kata

# Query kata (cocok tepat)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "term": {
      "tags": "electronics"
    }
  }
}
'

# Query kata-kata (nilai ganda)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "terms": {
      "tags": ["electronics", "computers"]
    }
  }
}
'

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

# Query eksis
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "exists": {
      "field": "description"
    }
  }
}
'

Query Boolean

# Query boolean (harus, seharusnya, harus tidak, 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" }}
      ]
    }
  }
}
'

Pencarian Lanjutan

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

# Query fuzzy (toleransi typo)
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"
    }
  }
}
'

Agregasi

Agregasi Metric

# Rata-rata, jumlah, minimum, maksimum
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" }}
  }
}
'

# Agregasi statistik
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "size": 0,
  "aggs": {
    "price_stats": {
      "stats": { "field": "price" }
    }
  }
}
'

Agregasi Bucket

# Agregasi terms (kelompokkan)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "size": 0,
  "aggs": {
    "popular_tags": {
      "terms": {
        "field": "tags",
        "size": 10
      }
    }
  }
}
'

# Agregasi rentang
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 }
        ]
      }
    }
  }
}
'

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

Agregasi Nested

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

Pengurutan dan Pemilahan

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

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

# Pencarian setelah (untuk pemilahan dalam)
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"]
}
'

Pemilihan Bidang dan Pemunculan

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

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

Alias Indeks

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

# Beralih alias ke indeks baru (tanpa downtime)
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" }}
  ]
}
'

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

Reindex

# Reindex dari satu indeks ke indeks lain
curl -X POST "localhost:9200/_reindex?pretty" -H 'Content-Type: application/json' -d'
{
  "source": {
    "index": "old_products"
  },
  "dest": {
    "index": "new_products"
  }
}
'

# Reindex dengan 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 dan Cadangan

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

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

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

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

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

Optimasi Kinerja

Pengaturan Indeks

# Nonaktifkan refresh selama pemetaan massal
curl -X PUT "localhost:9200/products/_settings?pretty" -H 'Content-Type: application/json' -d'
{
  "index": {
    "refresh_interval": "-1"
  }
}
'

# Aktifkan kembali setelah pemetaan massal
curl -X PUT "localhost:9200/products/_settings?pretty" -H 'Content-Type: application/json' -d'
{
  "index": {
    "refresh_interval": "1s"
  }
}
'

# Merge paksa (optimasi)
curl -X POST "localhost:9200/products/_forcemerge?max_num_segments=1&pretty"

Pembersihan Cache

# Bersihkan semua cache
curl -X POST "localhost:9200/_cache/clear?pretty"

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

Pemantauan dan Pemecahan Masalah

# Tugas yang menunggu
curl -X GET "localhost:9200/_cat/pending_tasks?v"

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

# Informasi segment
curl -X GET "localhost:9200/_cat/segments?v"

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

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

Contoh Klien Python

from elasticsearch import Elasticsearch

# Koneksi ke Elasticsearch
es = Elasticsearch(['http://localhost:9200'])

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

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

# Pemetaan massal
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)

Contoh Klien JavaScript/Node.js

Klien JavaScript Elasticsearch menyediakan cara yang aman secara tipe untuk berinteraksi dengan klaster Anda. Untuk aplikasi produksi, pertimbangkan penggunaan TypeScript untuk keamanan tipe yang lebih baik dan penyelesaian otomatis. Lihat TypeScript Cheatsheet kami untuk praktik terbaik tentang definisi tipe dan antarmuka.

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

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

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

// Pemetaan massal
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 });
}

Contoh TypeScript dengan Pengetikan Kuat

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);
}

Praktik Terbaik

Desain Indeks

  • Pertahankan ukuran shard antara 20-50GB untuk kinerja optimal
  • Gunakan manajemen siklus indeks (ILM) untuk data time-series
  • Rancang pemetaan dengan hati-hati sebelum mengindeks data
  • Gunakan tipe bidang yang tepat (keyword vs text, format tanggal)
  • Nonaktifkan _source untuk dokumen besar jika tidak diperlukan

Optimasi Query

  • Gunakan filter daripada query ketika penilaian tidak diperlukan
  • Pilih query level kata untuk data terstruktur
  • Gunakan bool query untuk menggabungkan beberapa kondisi secara efisien
  • Implementasikan pemilahan dengan search_after untuk pemilahan dalam
  • Cache filter yang sering digunakan

Kinerja Indeks

  • Gunakan API bulk untuk indeks batch (1000-5000 dokumen per permintaan)
  • Nonaktifkan refresh selama operasi indeks
  • Tingkatkan index.refresh_interval selama indeks berat
  • Gunakan beberapa thread/pekerja untuk indeks paralel
  • Pertimbangkan penggunaan routing untuk distribusi shard yang lebih baik

Manajemen Klaster

  • Pantau kesehatan klaster secara berkala
  • Tetapkan konfigurasi replika yang tepat
  • Gunakan node master khusus untuk klaster besar
  • Implementasikan strategi cadangan yang tepat dengan snapshot
  • Pantau penggunaan heap JVM (pertahankan di bawah 75%)

Keamanan

  • Aktifkan otentikasi dan otorisasi (X-Pack Security)
  • Gunakan HTTPS untuk deployment produksi (konfigurasikan cURL dengan opsi --cacert, --cert, dan --key untuk SSL/TLS)
  • Implementasikan kontrol akses berbasis peran
  • Pembaruan keamanan rutin dan patch
  • Enkripsi data di tempat dan dalam transit

Kasus Penggunaan Umum

Pencarian Teks Lengkap

Elasticsearch sangat unggul dalam pencarian teks lengkap dengan fitur seperti:

  • Penilaian relevansi
  • Cocok fuzzy
  • Cocok frasa
  • Penanganan sinonim
  • Dukungan multi-bahasa

Analitik Log (ELK Stack)

  • Kumpulkan log dengan Logstash/Filebeat
  • Indeks dan cari log di Elasticsearch
  • Visualisasikan dengan dashboard Kibana
  • Atur peringatan untuk anomali

Pencarian E-commerce

  • Pencarian katalog produk
  • Navigasi terstruktur dengan agregasi
  • Auto-complete dan saran
  • Hasil pencarian yang disesuaikan

Pemantauan Kinerja Aplikasi

  • Indeks metrik aplikasi
  • Dashboard pemantauan real-time
  • Deteksi anomali
  • Analisis tren kinerja

Tautan Berguna

Sumber Daya Elasticsearch Resmi

Cheatsheet dan Panduan Terkait