☕ XOPSSCHOOL — LEARNING MADE AFFORDABLE
Build the Skills Your Next Career Move Demands.
For the Price of One Coffee a Month.
Why spend hundreds on individual courses? Unlock an entire year of technical learning with one Coffee Pass.
US$4.90 /month
US$58.80/year
₹499 + GST/month
₹5,988 + GST/year
€4.90 /month
€58.80/year
12 Months of Access • Billed Annually • No Automatic Renewal
DevOps • Cloud • SRE • Kubernetes • Terraform • DevSecOps • AI • AIOps • MLOps • LLMOps • FinOps • GitOps • Platform Engineering & Much More
192
Premium Courses
1,085
Video Sessions
99
Ops Disciplines
86
Tool Courses
340
Assignments
227
Quizzes
✓ QR-Verifiable Certificates   ✓ Learn at Your Own Pace   ✓ Hands-on Learning   ✓ New Courses Included
Learn from real-world, instructor-led video sessions by
Rajesh Kumar
Principal Architect • Trainer • Mentor • 15+ Years of Industry Experience
☕ Get My Coffee Pass — Start Learning Today →
One Payment. Every Premium Course. One Full Year.
The best investment you can make is in the person you are becoming.

Elasticsearch Lab#2 – Bulk indexing document using mget & bulk api

This lab uses the Elasticsearch _mget API to fetch several documents in one request and the _bulk API to index, create, update and delete many documents in one request, including loading a whole NDJSON file. The commands in the example above were written for older typed versions of Elasticsearch, so this page also gives corrected versions that run on Elasticsearch 7.x and 8.x with security enabled.

Sample Data


$ wget https://gist.githubusercontent.com/devops-school/0a09b9e55efb45bcf397d501feb38965/raw/92179a491c6a717c70280619a8a6e3e64b2b0de3/customers_full.jsonCode language: JavaScript (javascript)

Reference

  • Sample Data & Query – https://github.com/devopsschool-demo-labs-projects/elasticsearch

What mget and bulk actually do

Despite the lab title, _mget does not index anything. It is a read API that returns several documents by ID in a single round trip, instead of sending one GET /index/_doc/id request per document. _bulk is the write API: it accepts many index, create, update and delete operations in one request, which is far faster than sending them one at a time.

The bulk body is NDJSON (newline-delimited JSON). Each operation is an action line, and for most actions a source line follows it. Every line, including the last one, must end with a newline character.

ActionSource lineBehaviour
indexFull documentCreates the document, or replaces it if the ID already exists
createFull documentCreates the document; that item fails with 409 if the ID exists
update{"doc": {...}} or a scriptPartially updates an existing document; fails with 404 if it is missing
deleteNoneDeletes the document by ID

What changed since the example above was written

The gist uses _type (mobiles, shoes, personal) and typed URLs such as /products/mobiles/_mget and /customers/personal/_bulk. Mapping types were limited to one per index in 6.x, deprecated in 7.x and removed in 8.x. On a current cluster these requests fail.

  • Elasticsearch 8.x: remove _type from every action line and request body, and drop the type segment from the URL (/products/_bulk, not /products/shoes/_bulk).
  • Elasticsearch 6.x and 7.x: an index can hold only one type. The lab indexes mobiles and then shoes into the same products index, and the second request is rejected with *final mapping would have more than 1 type*.
  • Security on by default in 8.x: port 9200 serves HTTPS and needs credentials. Plain curl localhost:9200 returns curl: (52) Empty reply from server or a 401 error.
  • The first _mget call uses the auto-generated ID nL_Fd3EBQb932Ywx993J, which only existed on the author's cluster. On your cluster it returns "found": false.

Connect to a secured cluster

Set a few shell variables once, so the commands below stay short. On first start, Elasticsearch 8.x prints the elastic password and generates http_ca.crt. Archive installs keep it in config/certs/ and package installs keep it in /etc/elasticsearch/certs/.

export ES_URL=https://localhost:9200
export ES_CA=/etc/elasticsearch/certs/http_ca.crt
export ELASTIC_PASSWORD='your-elastic-password'

curl -s --cacert "$ES_CA" -u "elastic:$ELASTIC_PASSWORD" "$ES_URL/_cluster/health?pretty"Code language: JavaScript (javascript)

Note: On a throwaway lab VM you can replace --cacert "$ES_CA" with -k to skip certificate verification. Do not do this against shared or production clusters. If you are on a 6.x/7.x cluster without security, use ES_URL=http://localhost:9200 and leave out --cacert and -u.

Corrected bulk examples

Run these before the mget examples so that documents 1 to 4 exist. The first request indexes documents with explicit IDs. The _index is in the action line, so the URL is just /_bulk.

curl -s --cacert "$ES_CA" -u "elastic:$ELASTIC_PASSWORD" -X POST "$ES_URL/_bulk?pretty" \
  -H 'Content-Type: application/x-ndjson' -d'
{ "index" : { "_index" : "products", "_id" : "1" } }
{ "name": "Adidas", "size": 10, "color": "white" }
{ "index" : { "_index" : "products", "_id" : "2" } }
{ "name": "Reebok", "size": 7, "color": "blue" }
{ "index" : { "_index" : "products", "_id" : "3" } }
{ "name": "Puma", "size": 9, "color": "black" }
{ "index" : { "_index" : "products", "_id" : "4" } }
{ "name": "New Balance", "size": 8, "color": "black" }
'Code language: PHP (php)

To let Elasticsearch generate IDs, put the index in the URL and send an empty action object:

curl -s --cacert "$ES_CA" -u "elastic:$ELASTIC_PASSWORD" -X POST "$ES_URL/products/_bulk?pretty" \
  -H 'Content-Type: application/x-ndjson' -d'
{ "index" : {} }
{ "name": "Puma", "size": 9, "color": "black" }
{ "index" : {} }
{ "name": "New Balance", "size": 8, "color": "black" }
'Code language: PHP (php)

Mixed operations can be sent in one request, as the gist intended. The gist's note to paste them one at a time is not needed. Elasticsearch runs the items in order, and each item succeeds or fails on its own.

curl -s --cacert "$ES_CA" -u "elastic:$ELASTIC_PASSWORD" -X POST "$ES_URL/products/_bulk?pretty" \
  -H 'Content-Type: application/x-ndjson' -d'
{ "delete" : { "_id" : "2" } }
{ "create" : { "_id" : "5" } }
{ "name": "Nike Power", "size": 12, "color": "black" }
{ "update" : { "_id" : "1" } }
{ "doc" : { "color" : "orange" } }
'Code language: PHP (php)

Run the mixed request a second time and the create item returns status 409 (version_conflict_engine_exception), because document 5 now exists. The delete item returns not_found. Both results are expected.

Corrected mget examples

Without types, each entry needs only _index and _id. You can also limit the fields returned with _source:

curl -s --cacert "$ES_CA" -u "elastic:$ELASTIC_PASSWORD" -X GET "$ES_URL/_mget?pretty" \
  -H 'Content-Type: application/json' -d'
{
  "docs": [
    { "_index": "products", "_id": "1" },
    { "_index": "products", "_id": "2", "_source": ["name", "color"] }
  ]
}
'Code language: PHP (php)

When every document is in the same index, put the index in the URL and use the shorter ids form:

curl -s --cacert "$ES_CA" -u "elastic:$ELASTIC_PASSWORD" -X GET "$ES_URL/products/_mget?pretty" \
  -H 'Content-Type: application/json' -d'{ "ids": ["1", "2", "3"] }'Code language: JavaScript (javascript)

The response contains a docs array in the same order as the request. If you ran the mixed bulk request first, document 2 was deleted. It comes back as "found": false instead of failing the whole request.

Loading a JSON file with the bulk API

  1. Download the sample file with one of the wget commands above, then look at the first two lines: head -n 2 customers_full.json. Line 1 must be an action line and line 2 a document.
  2. If the action lines contain "_type" and you are on 8.x, remove it, for example with sed -i 's/"_type" *: *"[^"]*" *, *//' customers_full.json. Then check the result with head again.
  3. Make sure the file ends with a newline: [ -n "$(tail -c1 customers_full.json)" ] && echo >> customers_full.json. This fixes the *must be terminated by a newline* error shown in the gist.
  4. Optionally create the index first with your own mappings. If you don't, it is created automatically with dynamic mappings.
  5. Send the file with --data-binary, not -d, and print only the error summary so a large response does not flood the terminal.
  6. Verify the document count.
curl -s --cacert "$ES_CA" -u "elastic:$ELASTIC_PASSWORD" -X PUT "$ES_URL/customers?pretty"

curl -s --cacert "$ES_CA" -u "elastic:$ELASTIC_PASSWORD" -X POST \
  "$ES_URL/customers/_bulk?refresh=wait_for&filter_path=errors,items.*.error" \
  -H 'Content-Type: application/x-ndjson' --data-binary @customers_full.json

curl -s --cacert "$ES_CA" -u "elastic:$ELASTIC_PASSWORD" "$ES_URL/_cat/indices/customers?v"
curl -s --cacert "$ES_CA" -u "elastic:$ELASTIC_PASSWORD" "$ES_URL/customers/_count?pretty"Code language: JavaScript (javascript)

A clean load prints {"errors":false}. -d @file strips newlines from the file, which corrupts NDJSON. --data-binary sends the bytes unchanged. The inline -d'...' examples work only because the newlines are typed into the command itself.

Note: The gist also posts sam.json, a file that is never created in the lab. Skip that command, or replace it with your own NDJSON file.

Reading the response and fixing common errors

A bulk request returns HTTP 200 even when some items fail. Always check the top-level "errors" flag, then look at the status and error of each entry in items.

ErrorCauseFix
The bulk request must be terminated by a newline [\n]The last line has no trailing newline, or -d @file stripped the newlinesAppend a newline and use --data-binary
Action/metadata line [1] contains an unknown parameter [_type]Typed bulk syntax sent to 8.xRemove _type from action lines and URLs
final mapping would have more than 1 typeTwo types sent to one index on 6.x/7.xUse one type per index, or better, a separate index per entity
curl: (52) Empty reply from serverPlain HTTP sent to an HTTPS port on 8.xUse https:// with --cacert and credentials
401 security_exceptionMissing or wrong credentialsPass -u elastic:password or an API key header
406 Content-Type header [...] is not supportedNo Content-Type headerAdd -H 'Content-Type: application/x-ndjson' (or application/json)
413 Request Entity Too LargeBody exceeds http.max_content_length (100 MB by default)Split the file into smaller requests

Best practices for bulk loading

  • Size batches by bytes, not by document count. Start with a few megabytes to around 15 MB per request, measure throughput, and adjust.
  • To split a large file, use an even line count so that action and source lines stay together: split -l 20000 customers_full.json part_. Make sure every part ends with a newline.
  • Use refresh=wait_for or refresh=true only in labs or small loads. For large imports, leave refresh off, or set index.refresh_interval to -1 during the load and restore it afterwards.
  • Use create instead of index when re-running a load must not overwrite existing documents.
  • Define mappings before loading production data. Dynamic mapping can guess field types wrongly, and a wrong type cannot be changed without reindexing.
  • Use a dedicated user or API key with write privileges on the target index instead of the elastic superuser, and keep passwords out of shell history.

Frequently asked questions

Can the mget API be used to index documents?

No. _mget only retrieves documents by ID. To index, update or delete many documents in one request, use _bulk.

Why does the bulk API return 200 even though some documents failed?

Each item in a bulk request succeeds or fails on its own, so the HTTP status describes the request as a whole. Check the top-level errors field and the status of each item to find failures.

Can I still use _type in Elasticsearch 8?

No. Mapping types were removed in 8.x, so _type in bulk or mget bodies and typed URLs such as /index/type/_bulk are rejected. Use one index per kind of data instead.

Why should I use –data-binary instead of -d with curl for bulk files?

curl -d @file strips carriage returns and newlines from the file, which breaks the NDJSON format the bulk API requires. --data-binary sends the file exactly as it is.

How big should a bulk request be?

There is no single correct size. Start with a few megabytes up to about 15 MB per request, measure indexing throughput, and adjust. Stay well below the http.max_content_length limit, which is 100 MB by default.

Related tutorials

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services — all in one place.

Explore Hospitals

Related Posts

Elasticsearch templates

An Elasticsearch index template holds the settings, mappings and aliases that Elasticsearch applies when it creates a new index or data stream backing index whose name matches…

Read More

Elasticsearch Lab#5 – Example of Popular Query

This lab creates an Elasticsearch index with a set number of primary shards and replicas, then runs the queries you'll use most often against it. The example…

Read More

Elasticsearch Lab#4 – DSL Query Collection Part#2

This lab covers the Elasticsearch full-text queries match, match_phrase and match_phrase_prefix, using the customers sample index. Below the gist you will find how these queries differ from…

Read More

Elasticsearch Lab#3 – DSL Query Collection Part#1

This lab covers the two ways to send a search to Elasticsearch's _search API: URI query parameters (?q=) and a JSON Query DSL request body. It goes…

Read More

Elastic Tutorial: Elasticsearch 8.X Installation & CRUD in Linux

This page shows how to install Elasticsearch 8.x from the official tar.gz archive on Linux, start it as a non-root user, and connect over HTTPS with the…

Read More

How to configure Elastic filebeat 8.3 with Elasticseach?

This guide shows how to install Filebeat 8.3 from the tarball, collect log files with the filestream input, and send them to an Elasticsearch 8 cluster that…

Read More