Elasticsearch-Referentie: Essentiële Commando's en Tips

Elasticsearch-commando's voor zoeken, indexeren en analyse

Inhoud

Elasticsearch is een krachtige gedistribueerde zoek- en analyse-engine gebouwd op Apache Lucene. Dit uitgebreide naslagwerk dekt essentiële commando’s, best practices en snelle referenties voor het werken met Elasticsearch-clusters.

elasticsearch

Opmerking: De meeste voorbeelden in deze gids gebruiken cURL voor HTTP-aanvragen. Als u nieuw bent in cURL of een snelle referentie nodig heeft voor geavanceerde opties, bekijk dan onze cURL Naslagwerk voor gedetailleerde technieken voor HTTP-aanvragen via de commandoregel.

Clusterbeheer

Clustergezondheid controleren

Alle commando’s in deze sectie gebruiken cURL om met Elasticsearch REST API te communiceren. U kunt deze aanvragen aanpassen met extra headers, authenticatie en andere opties naar behoefte.

# Basisgezondheidscontrole
curl -X GET "localhost:9200/_cluster/health?pretty"

# Gedetailleerde clustergezondheid met shard-informatie
curl -X GET "localhost:9200/_cluster/health?level=shards&pretty"

# Node-informatie controleren
curl -X GET "localhost:9200/_cat/nodes?v"

# Cluster-instellingen controleren
curl -X GET "localhost:9200/_cluster/settings?pretty"

Node-bewerkingen

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

# Node-statistieken
curl -X GET "localhost:9200/_nodes/stats?pretty"

# Actieve threads (voor probleemoplossing)
curl -X GET "localhost:9200/_nodes/hot_threads"

Indexbeheer

Indices maken en verwijderen

# Index maken
curl -X PUT "localhost:9200/my_index?pretty"

# Index maken met instellingen
curl -X PUT "localhost:9200/my_index" -H 'Content-Type: application/json' -d'
{
  "settings": {
    "number_of_shards": 3,
    "number_of_replicas": 1
  }
}
'

# Index verwijderen
curl -X DELETE "localhost:9200/my_index?pretty"

# Alle indices tonen
curl -X GET "localhost:9200/_cat/indices?v"

# Index-statistieken
curl -X GET "localhost:9200/my_index/_stats?pretty"

Index-mappings

# Mapping definiëren
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 ophalen
curl -X GET "localhost:9200/products/_mapping?pretty"

# Mapping bijwerken (veld toevoegen)
curl -X PUT "localhost:9200/products/_mapping" -H 'Content-Type: application/json' -d'
{
  "properties": {
    "category": { "type": "keyword" }
  }
}
'

Index-templates

# Index-template maken
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" }
      }
    }
  }
}
'

# Templates tonen
curl -X GET "localhost:9200/_index_template?pretty"

Document-bewerkingen (CRUD)

Documenten maken

# Document indexeren met automatisch gegenereerd ID
curl -X POST "localhost:9200/products/_doc?pretty" -H 'Content-Type: application/json' -d'
{
  "name": "Laptop",
  "price": 999.99,
  "tags": ["electronics", "computers"]
}
'

# Document indexeren met specifiek ID
curl -X PUT "localhost:9200/products/_doc/1?pretty" -H 'Content-Type: application/json' -d'
{
  "name": "Laptop",
  "price": 999.99
}
'

# Bulk-indexing
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": "Muis", "price": 29.99 }
'

Documenten lezen

# Document ophalen op ID
curl -X GET "localhost:9200/products/_doc/1?pretty"

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

# Controleren of document bestaat
curl -I "localhost:9200/products/_doc/1"

Documenten bijwerken

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

# Bijwerken met 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 (bijwerken of invoegen)
curl -X POST "localhost:9200/products/_update/1?pretty" -H 'Content-Type: application/json' -d'
{
  "doc": {
    "price": 899.99
  },
  "doc_as_upsert": true
}
'

Documenten verwijderen

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

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

Zoekopdrachten

Basiszoeken

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

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

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

Term-niveau queries

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

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

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

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

Boolean queries

# Bool query (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" }}
      ]
    }
  }
}
'

Geavanceerd zoeken

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

# Fuzzy query (fouttolerantie)
curl -X GET "localhost:9200/products/_search?pretty" -H 'Content-Type: application/json' -d'
{
  "query": {
    "fuzzy": {
      "name": {
        "value": "laptpo",
        "fuzziness": "AUTO"
      }
    }
  }
}
'

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

Aggregaties

Metriek-aggregaties

# Gemiddelde, som, min, max
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" }}
  }
}
'

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

Bucket-aggregaties

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

# Range-aggregatie
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 }
        ]
      }
    }
  }
}
'

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

Geneste aggregaties

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

Sorteren en Paginatie

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

# Paginatie met 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 (voor diepe paginatie)
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"]
}
'

Veldselectie en Highlighting

# Specifieke velden selecteren
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": {}
    }
  }
}
'

Index-aliases

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

# Alias overschakelen naar nieuwe index (zonder 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" }}
  ]
}
'

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

Reindexeren

# Reindexeren van één index naar een andere
curl -X POST "localhost:9200/_reindex?pretty" -H 'Content-Type: application/json' -d'
{
  "source": {
    "index": "old_products"
  },
  "dest": {
    "index": "new_products"
  }
}
'

# Reindexeren met 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 en Back-ups

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

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

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

# Snapshots tonen
curl -X GET "localhost:9200/_snapshot/my_backup/_all?pretty"

# Snapshot verwijderen
curl -X DELETE "localhost:9200/_snapshot/my_backup/snapshot_1?pretty"

Prestatie-optimalisatie

Index-instellingen

# Refresh uitschakelen tijdens bulk-indexing
curl -X PUT "localhost:9200/products/_settings?pretty" -H 'Content-Type: application/json' -d'
{
  "index": {
    "refresh_interval": "-1"
  }
}
'

# Opnieuw inschakelen na bulk-indexing
curl -X PUT "localhost:9200/products/_settings?pretty" -H 'Content-Type: application/json' -d'
{
  "index": {
    "refresh_interval": "1s"
  }
}
'

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

Cache wissen

# Alle caches wissen
curl -X POST "localhost:9200/_cache/clear?pretty"

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

Monitoring en Probleemoplossing

# In afwachting staande taken
curl -X GET "localhost:9200/_cat/pending_tasks?v"

# Thread pool-statistieken
curl -X GET "localhost:9200/_cat/thread_pool?v"

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

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

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

Python-clientvoorbeelden

from elasticsearch import Elasticsearch

# Verbinden met Elasticsearch
es = Elasticsearch(['http://localhost:9200'])

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

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

# Bulk-indexing
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-clientvoorbeelden

De Elasticsearch JavaScript-client biedt een typeveilige manier om met uw cluster te communiceren. Voor productie-applicaties is het raadzaam om TypeScript te gebruiken voor betere typeveiligheid en automatische voltooijing. Zie ons TypeScript Naslagwerk voor best practices voor type-definities en interfaces.

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

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

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

// Bulk-indexing
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-voorbeeld met sterke typen

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-ontwerp

  • Houd de shard-grootte tussen de 20-50GB voor optimale prestaties
  • Gebruik index life cycle management (ILM) voor tijdreeksdata
  • Ontwerp mappings zorgvuldig voordat u data indexeert
  • Gebruik de juiste veldtypen (keyword vs text, datumformaten)
  • Schakel _source uit voor grote documenten als dit niet nodig is

Query-optimalisatie

  • Gebruik filters in plaats van queries wanneer scoring niet nodig is
  • Gebruik liever term-niveau queries voor gestructureerde data
  • Gebruik bool query om meerdere voorwaarden efficiënt te combineren
  • Implementeer paginatie met search_after voor diepe paginatie
  • Cache veelgebruikte filters

Indexeringsprestaties

  • Gebruik de Bulk API voor batch-indexing (1000-5000 docs per aanvraag)
  • Schakel refresh uit tijdens bulk-bewerkingen
  • Verhoog index.refresh_interval tijdens zware indexering
  • Gebruik meerdere threads/workers voor parallelle indexering
  • Overweeg routing voor een betere shard-distributie

Clusterbeheer

  • Monitor clustergezondheid regelmatig
  • Stel een juiste replica-configuratie in
  • Gebruik dedicated master-nodes voor grote clusters
  • Implementeer een goede back-upstrategie met snapshots
  • Monitor JVM-heap-gebruik (onder de 75% houden)

Beveiliging

  • Schakel authenticatie en autorisatie in (X-Pack Security)
  • Gebruik HTTPS voor productie-implementaties (configureer cURL met --cacert, --cert en --key opties voor SSL/TLS)
  • Implementeer een juiste rolgebaseerde toegangscontrole
  • Regiereveiligingsupdates en patches
  • Versleutel data zowel op rust als in transitie

Gebruiksscenario’s

Volledige tekstzoeken

Elasticsearch excelleert in volledig tekstzoeken met functies zoals:

Loganalyse (ELK Stack)

  • Verzamel logs met Logstash/Filebeat
  • Indexeer en zoek logs in Elasticsearch
  • Visualiseer met Kibana-dashboards
  • Stel alerts in voor anomalieën

E-commerce zoeken

  • Productcatalogus zoeken
  • Gefacetteerde navigatie met aggregaties
  • Auto-completering en suggesties
  • Gepersonaliseerde zoekresultaten

Applicatieprestatie monitoring

  • Indexeer applicatiemetrics
  • Dashboards voor real-time monitoring
  • Anomaliedetectie
  • Analyse van prestatietrends

Officiële Elasticsearch-bronnen

Gerelateerde naslagwerken & gidsen

Abonneren

Ontvang nieuwe berichten over systemen, infrastructuur en AI-engineering.