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.
| Action | Source line | Behaviour |
|---|---|---|
index | Full document | Creates the document, or replaces it if the ID already exists |
create | Full document | Creates the document; that item fails with 409 if the ID exists |
update | {"doc": {...}} or a script | Partially updates an existing document; fails with 404 if it is missing |
delete | None | Deletes 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
_typefrom 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
mobilesand thenshoesinto the sameproductsindex, 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:9200returnscurl: (52) Empty reply from serveror a 401 error. - The first
_mgetcall uses the auto-generated IDnL_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
- Download the sample file with one of the
wgetcommands 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. - If the action lines contain
"_type"and you are on 8.x, remove it, for example withsed -i 's/"_type" *: *"[^"]*" *, *//' customers_full.json. Then check the result withheadagain. - 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. - Optionally create the index first with your own mappings. If you don't, it is created automatically with dynamic mappings.
- Send the file with
--data-binary, not-d, and print only the error summary so a large response does not flood the terminal. - 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.
| Error | Cause | Fix |
|---|---|---|
The bulk request must be terminated by a newline [\n] | The last line has no trailing newline, or -d @file stripped the newlines | Append a newline and use --data-binary |
Action/metadata line [1] contains an unknown parameter [_type] | Typed bulk syntax sent to 8.x | Remove _type from action lines and URLs |
final mapping would have more than 1 type | Two types sent to one index on 6.x/7.x | Use one type per index, or better, a separate index per entity |
curl: (52) Empty reply from server | Plain HTTP sent to an HTTPS port on 8.x | Use https:// with --cacert and credentials |
401 security_exception | Missing or wrong credentials | Pass -u elastic:password or an API key header |
406 Content-Type header [...] is not supported | No Content-Type header | Add -H 'Content-Type: application/x-ndjson' (or application/json) |
| 413 Request Entity Too Large | Body 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_fororrefresh=trueonly in labs or small loads. For large imports, leave refresh off, or setindex.refresh_intervalto-1during the load and restore it afterwards. - Use
createinstead ofindexwhen 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
elasticsuperuser, 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
- What is Elasticsearch and use cases of Elasticsearch?
- Top 50 Elasticsearch Interview Questions and Answers
- What is ELK Stack and use cases of ELK Stack?
- More Elastic Stack (ELK) tutorials
I’m Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms.
I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.
Find Trusted Cardiac Hospitals
Compare heart hospitals by city and services — all in one place.
Explore Hospitals