Elasticsearch / OpenSearch
last updated 2026-12
update 2026 - first written for Elasticsearch 0.20 (2013), rewritten for Elasticsearch 8/9 and OpenSearch 2/3. everything on these pages works the same on both - every example was run on OpenSearch 2.19, 3.x and Elasticsearch 9.2. they differ in the setup, the security defaults, and in what's newer than these notes (ES|QL vs PPL/SQL, vector search, …)
i was really surprised by Elasticsearch (ES further on) - the simplicity of setup and configuration, and its powers and options
history
- 2010 - Shay Banon releases Elasticsearch, Apache 2.0 licensed, built on Lucene (after his earlier Compass); the company behind it is Elastic since 2012
- 2015 - AWS starts offering it as a managed service, Amazon Elasticsearch Service, without contributing much back - a long running sore point for Elastic
- 2021-01 - Elastic moves Elasticsearch and Kibana from 7.11 on to the SSPL and their own Elastic License, neither of them open source - mostly to stop exactly that kind of cloud resale
- 2021 - AWS forks the last Apache-licensed version, 7.10.2, as OpenSearch (and Kibana as OpenSearch Dashboards); 1.0 in 2021-07, and the AWS service is renamed to Amazon OpenSearch Service (2021-09)
- 2024 - Elastic adds the AGPL as a third license option, so Elasticsearch is open source again; OpenSearch moves to the Linux Foundation (OpenSearch Software Foundation), so it's not just an AWS project any more
the two have drifted apart since, but the core REST API (documents, search, query DSL, mappings) is still the same - which is what these pages are about
AWS's managed service runs OpenSearch now (it still offers old Elasticsearch versions up to 7.10), but the es name is still all over it:
- IAM actions and policies -
es:ESHttpGet,es:CreateDomain, … - the CLI -
aws es …still works next toaws opensearch …, the same goes for boto3'sesandopensearchclients - domain endpoints -
https://search-<domain>-<id>.<region>.es.amazonaws.com - SigV4 request signing - service name
es(aossfor OpenSearch Serverless)
installation
the easiest way is docker, with the data folder shared with the host, so it survives the container:
sudo mkdir -p /var/local/docker-data-volumes/os-data
sudo chown 1000:1000 /var/local/docker-data-volumes/os-data
docker run -d --name opensearch -p 127.0.0.1:9200:9200 -p 127.0.0.1:9600:9600 -e "discovery.type=single-node" -e "DISABLE_SECURITY_PLUGIN=true" -e "OPENSEARCH_JAVA_OPTS=-Xms750m -Xmx750m" -v /var/local/docker-data-volumes/os-data:/usr/share/opensearch/data opensearchproject/opensearch:2
chown 1000- the server runs as uid 1000 in the container, and won't start if it can't write to the data folderDISABLE_SECURITY_PLUGIN=true- plain HTTP without a login, fine for a local dev instance bound to127.0.0.1. without it, OpenSearch 2.12+ refuses to start unless you setOPENSEARCH_INITIAL_ADMIN_PASSWORD, and then it's HTTPS with a self-signed cert (curl -k -u admin:<password> https://localhost:9200)discovery.type=single-node- no cluster forming, and it also skips the production bootstrap checks (e.g.vm.max_map_count)- port
9600is the Performance Analyzer, optional opensearch:3works the same
the Elasticsearch equivalent:
docker run -d --name elasticsearch -p 127.0.0.1:9200:9200 -e "discovery.type=single-node" -e "xpack.security.enabled=false" -e "ES_JAVA_OPTS=-Xms750m -Xmx750m" -v /var/local/docker-data-volumes/es-data:/usr/share/elasticsearch/data docker.elastic.co/elasticsearch/elasticsearch:9.2.0
what you get
after the above 30-sec setup, you have a search engine running on http://localhost:9200/, with sharding, replication, and much much more
a few highlights:
- a neat RESTful API that communicates (almost) entirely in JSON
- schemaless, unless you want it to be - field types are guessed from the first document that has them
- you can hint it on many tasks - e.g. what shards to search in, etc.
- indices are created on the fly, no need to precreate (yes, might be tougher to find a bug, but installation of a new system is a breeze)
- you can specify what indices to search - a group, all, or just one
- documents are versioned - indexing a document with an existing ID replaces it and bumps its
_version
every request with a body needs -H 'Content-Type: application/json'. append ?pretty to any URL to get readable JSON back
indexing
example
let's start with an add-get example (responses shortened):
# lets add a user to _twitter_ index, with ID _kimchy_
$ curl -XPUT 'localhost:9200/twitter/_doc/kimchy' -H 'Content-Type: application/json' -d '{ "name" : "Shay Banon" }'
> {"_index":"twitter","_id":"kimchy","_version":1,"result":"created", … ,"_seq_no":0,"_primary_term":1}
$ curl -XGET 'localhost:9200/twitter/_doc/kimchy?pretty'
> {
> "_index" : "twitter",
> "_id" : "kimchy",
> "_version" : 1,
> "_seq_no" : 0,
> "_primary_term" : 1,
> "found" : true,
> "_source" : { "name" : "Shay Banon" }
> }
# lets add one more document with the same ID
$ curl -XPUT 'localhost:9200/twitter/_doc/kimchy' -H 'Content-Type: application/json' -d '{ "name" : "Shay Baror" }'
> {"_index":"twitter","_id":"kimchy","_version":2,"result":"updated", … ,"_seq_no":1,"_primary_term":1}
# note the increase in version number - the old document is gone
$ curl -XGET 'localhost:9200/twitter/_doc/kimchy?pretty'
> {
> "_index" : "twitter",
> "_id" : "kimchy",
> "_version" : 2,
> "_seq_no" : 1,
> "_primary_term" : 1,
> "found" : true,
> "_source" : { "name" : "Shay Baror" }
> }
# now, lets search for "shay" users
$ curl -XGET 'localhost:9200/twitter/_search?q=name:shay&pretty'
> {
> "took" : 4,
> "timed_out" : false,
> "_shards" : {
> "total" : 1,
> "successful" : 1,
> "skipped" : 0,
> "failed" : 0
> },
> "hits" : {
> "total" : {
> "value" : 1,
> "relation" : "eq"
> },
> "max_score" : 0.2876821,
> "hits" : [ {
> "_index" : "twitter",
> "_id" : "kimchy",
> "_score" : 0.2876821,
> "_source" : { "name" : "Shay Baror" }
> } ]
> }
> }
# finally, you may search all indices
$ curl -XGET 'localhost:9200/_search?q=name:shay'
# or just selected indices - _twitter_ and _facebook_
$ curl -XGET 'localhost:9200/twitter,facebook/_search?q=name:shay'
# or on all indices starting with _t_, excluding _twitter_
$ curl -XGET 'localhost:9200/t*,-twitter/_search?q=name:shay'
note that you get most of the useful information, and very little superfluous. of course, without the pretty parameter, you get the "normal" more compressed version of JSON
creating documents
you create/index documents by PUTting them to an index with docid ID:
curl -XPUT 'localhost:9200/index/_doc/docid' -H 'Content-Type: application/json' -d '{"content":"trying out Elasticsearch"}'
the _doc in the URL is fixed - it used to be the document's type, and mapping types were removed in ES 7/8 (an index holds one kind of document now)
optimistic concurrency control
note that documents are replaced, and their version bumped, if PUT more than once
you can use OCC to make sure you're updating the document you started the update on - pass the _seq_no and _primary_term you got when reading it:
curl -XPUT 'localhost:9200/twitter/_doc/kimchy?if_seq_no=1&if_primary_term=1' -H 'Content-Type: application/json' -d '{"name":"Shay Boron"}'
if the document changed in the meantime, you'll get an error (409):
{"error":{"root_cause":[…],"type":"version_conflict_engine_exception","reason":"[kimchy]: version conflict, required seqNo [1], primary term [1]. current document has seqNo [2] and primary term [1]", …},"status":409}
it's up to you then to get the new version and update the data accordingly and PUT again
if the version lives outside (e.g. a timestamp in your DB), use ?version=<n>&version_type=external instead - the write goes through only if <n> is higher than the stored version
PUT-if-absent
to create a document only if it's not present in the index yet, use the create op type (the following 2 calls are equivalent; a 409 if it exists):
curl -XPUT 'localhost:9200/twitter/_doc/1?op_type=create' -H 'Content-Type: application/json' -d '{"name":"Shay"}'
curl -XPUT 'localhost:9200/twitter/_create/1' -H 'Content-Type: application/json' -d '{"name":"Shay"}'
automatic ID generation
you can create a document without providing an ID. note that the call is POST not PUT! (this, of course, automatically sets op_type to create)
curl -XPOST 'localhost:9200/twitter/_doc' -H 'Content-Type: application/json' -d '{"name":"Shay"}'
you'll receive the generated (20 chars, URL-safe base64) ID in the response:
{
"_index" : "twitter",
"_id" : "Y4wW3JoBc5dQ8_FYxB2r",
"_version" : 1,
"result" : "created",
…
}
refresh
a new document shows up in search only after the next index refresh, 1 s by default (GET by ID sees it right away). add ?refresh=wait_for to a write to return only once it's searchable - handy in tests, don't do it for every write
indices and mappings
an index is automatically created if it doesn't exist. the field mapping is also automatically created/updated
indices can also be created "manually", as well as mappings
set action.auto_create_index to false in the cluster settings, and indices need to be created manually before use. for new fields it's "dynamic": "strict" in the index mapping
curl -XPUT 'localhost:9200/_cluster/settings' -H 'Content-Type: application/json' -d '{
"persistent" : { "action.auto_create_index" : "false" }
}'
you can also white/black-list indices by name, which are to be created automatically, by setting action.auto_create_index to +aaa*,-bbb*,+ccc*,-*
routing
by default, the shard used to store the document is selected using a hash of the document's ID
you can "control" this by providing the ID used for hashing manually, using the routing parameter:
curl -XPOST 'localhost:9200/twitter/_doc?routing=kimchy' -H 'Content-Type: application/json' -d '{"user":"kimchy"}'
the main advantage of routing is that you can use this information later on when searching for documents, by providing the same ID:
curl -XGET 'localhost:9200/twitter/_search?routing=kimchy' -H 'Content-Type: application/json' -d '{"query":{"term":{"user":"kimchy"}}}'
this will restrict the search only to shards that might store the documents for the given routing. it only pays off with more than one shard - an index has 1 shard by default since ES 7
deleting
you can simply delete a document using the DELETE HTTP method:
curl -XDELETE 'localhost:9200/twitter/_doc/1'
to make sure you're deleting the document you really want to delete, you can provide the if_seq_no and if_primary_term parameters, and the delete will fail if the document changed since
note: if you used routing for creation of the document, you need to provide it for deletion also!
to delete everything matching a query, there's _delete_by_query:
curl -XPOST 'localhost:9200/twitter/_delete_by_query' -H 'Content-Type: application/json' -d '{
"query" : { "match" : { "name" : "shay" } }
}'
getting
you can get a document from the index by ID:
curl -XGET 'localhost:9200/twitter/_doc/1'
{
"_index" : "twitter",
"_id" : "1",
"_version" : 1,
"_seq_no" : 0,
"_primary_term" : 1,
"found" : true,
"_source" : {
"user" : "kimchy",
"postDate" : "2009-11-15T14:12:12",
"message" : "trying out Elasticsearch"
}
}
to simply check if the document exists, use HEAD - 200 or 404, no body:
curl -I 'localhost:9200/twitter/_doc/1'
to get just the source, without the metadata, use _source instead of _doc:
curl -XGET 'localhost:9200/twitter/_source/1'
get options
the GET API is realtime, that is, not affected by the refresh rate of the index (when data will become visible for search). you can disable this by setting the realtime parameter to false
you can also use the _source_includes (or _source_excludes) parameter to get only selected fields from the document. you may also fetch sub-objects, using obj1.obj2 notation, and wildcards obj1.*
curl -XGET 'localhost:9200/twitter/_doc/1?_source_includes=title,content'
_source=false skips the source completely
the routing parameter is used as usual to specify the shard explicitly
multi get
the _mget interface allows you to get multiple documents based on an index and id (and possibly routing)
from various indices
curl 'localhost:9200/_mget' -H 'Content-Type: application/json' -d '{
"docs" : [
{
"_index" : "test",
"_id" : "1"
},
{
"_index" : "twitter",
"_id" : "2"
}
]
}'
same index
curl 'localhost:9200/test/_mget' -H 'Content-Type: application/json' -d '{ "ids" : ["1", "2"] }'
you can also specify fields to fetch:
curl 'localhost:9200/_mget' -H 'Content-Type: application/json' -d '{
"docs" : [
{
"_index" : "test",
"_id" : "1",
"_source" : ["field1", "field2"]
},
{
"_index" : "test",
"_id" : "2",
"_source" : ["field3", "field4"]
}
]
}'
updating
the operation gets the document, runs the script, and indexes back the result (also allows to delete, or ignore the operation). it uses versioning to make sure no updates have happened during the "get" and "reindex"
note: a full document reindex is still needed, just cutting down the network round-trip and using versioning to avoid conflicts
scripts are in Painless, a Java-like language - the same in both. pass values through params rather than into the script source, so the compiled script gets reused
example
# create a document
curl -XPUT 'localhost:9200/test/_doc/1' -H 'Content-Type: application/json' -d '{
"counter" : 1,
"tags" : ["red"]
}'
# update the counter - increment by 4
curl -XPOST 'localhost:9200/test/_update/1' -H 'Content-Type: application/json' -d '{
"script" : {
"source" : "ctx._source.counter += params.count",
"params" : { "count" : 4 }
}
}'
# add a tag (might add a duplicate, since it's just a list!)
curl -XPOST 'localhost:9200/test/_update/1' -H 'Content-Type: application/json' -d '{
"script" : {
"source" : "ctx._source.tags.add(params.tag)",
"params" : { "tag" : "blue" }
}
}'
# add a new field
curl -XPOST 'localhost:9200/test/_update/1' -H 'Content-Type: application/json' -d '{
"script" : "ctx._source.text = \"some text\""
}'
# remove a field
curl -XPOST 'localhost:9200/test/_update/1' -H 'Content-Type: application/json' -d '{
"script" : "ctx._source.remove(\"text\")"
}'
# a partial document may also be POST'ed, causing the final document to be a merge of original and update
curl -XPOST 'localhost:9200/test/_update/1' -H 'Content-Type: application/json' -d '{
"doc" : {
"name" : "new_name"
}
}'
# if the document does not exist, its initial content may be given as 'upsert'
curl -XPOST 'localhost:9200/test/_update/1' -H 'Content-Type: application/json' -d '{
"script" : {
"source" : "ctx._source.counter += params.count",
"params" : { "count" : 4 }
},
"upsert" : {
"counter" : 1
}
}'
# delete documents with tag 'blue', or ignore/noop
curl -XPOST 'localhost:9200/test/_update/1' -H 'Content-Type: application/json' -d '{
"script" : {
"source" : "if (ctx._source.tags.contains(params.tag)) { ctx.op = \"delete\" } else { ctx.op = \"noop\" }",
"params" : { "tag" : "blue" }
}
}'
to run a script over everything matching a query, there's _update_by_query
update parameters
routing- select routing/shardtimeout- timeout waiting for a shard to become availablewait_for_active_shards- how many shard copies must be active before the update goes ahead; default1(just the primary)refresh-truerefreshes the affected shard right away,wait_forwaits for the next refresh, so that the updated document appears in search results (truemight increase load)_source- return the updated document's source (true, or a list of fields)retry_on_conflict- how many times to retry if there is a version conflict; default0if_seq_no,if_primary_term- the OCC check, as for indexing
search
notes on search
query DSL
indices management
create index
multiple indices are supported, including executing operations across several indices. each index created can have specific settings associated with it
curl -XPUT 'localhost:9200/blog' -H 'Content-Type: application/json' -d '{
"settings" : {
"number_of_shards" : 3,
"number_of_replicas" : 2
}
}'
on a single node, the replicas can't be allocated anywhere and the index stays yellow - set number_of_replicas to 0 there
you may also provide mappings (see below) when creating an index:
curl -XPUT 'localhost:9200/products' -H 'Content-Type: application/json' -d '{
"settings" : {
"number_of_shards" : 1
},
"mappings" : {
"properties" : {
"field1" : { "type" : "keyword" }
}
}
}'
delete index
you can delete an index by simply
curl -XDELETE 'localhost:9200/blog'
note that you can specify multiple indices (CSV), and wildcards. _all or * deletes all indices - Elasticsearch 8+ refuses that unless action.destructive_requires_name is false, OpenSearch still allows it by default!
open and close index
indices may be closed - they have no overhead (exc. keeping metadata up to date), and all read/write operations on the index are then disabled. when you open an index, it goes through the normal recovery process:
curl -XPOST 'localhost:9200/my_index/_close'
curl -XPOST 'localhost:9200/my_index/_open'
get settings
curl -XGET 'localhost:9200/twitter/_settings'
aliases
an alias is a second name for one or more indices - point the app at the alias, build a new index next to the old one (e.g. with changed mappings, see _reindex below), then switch the alias in one atomic call:
curl -XPOST 'localhost:9200/_aliases' -H 'Content-Type: application/json' -d '{
"actions" : [
{ "remove" : { "index" : "tweets_v1", "alias" : "tweets" } },
{ "add" : { "index" : "tweets_v2", "alias" : "tweets" } }
]
}'
mappings
mapping is the process of defining how a document should be mapped to the search engine, including its searchable characteristics such as which fields are searchable and if/how they are tokenized
mapping settings may be set while creating the index, or separately
the most used field types:
text- full-text, analyzed (tokenized, lowercased, …), formatchqueries; can't be sorted or aggregated onkeyword- exact value, not analyzed, fortermqueries, sorting and aggregations (IDs, tags, statuses, emails)- numbers -
float,double,byte,short,integer,long,scaled_float, … date- all dates are UTC; format may be specified, and alongnumber of milliseconds since epoch can be used any timeboolean,object(a JSON sub-object),nested(an array of objects, each queried on its own),geo_point,ip,binary
a string field that's added on the fly gets mapped as text with a keyword sub-field - search title, sort and aggregate on title.keyword
put mapping
new fields can be added to an existing index:
curl -XPUT 'localhost:9200/twitter/_mapping' -H 'Content-Type: application/json' -d '{
"properties" : {
"message" : { "type" : "text", "store" : true }
}
}'
fields are not stored on their own by default, just indexed (see below - common attributes)
mapping can be applied to multiple indices (CSV of index names, or wildcards)
an existing field's type can't be changed, nor can a field be removed (a few parameters can be updated, and a field can get new sub-fields). for anything else, create a new index with the new mapping and copy the data over:
curl -XPOST 'localhost:9200/_reindex' -H 'Content-Type: application/json' -d '{
"source" : { "index" : "twitter" },
"dest" : { "index" : "twitter_v2" }
}'
get mapping
curl -XGET 'localhost:9200/twitter/_mapping'
again, you can pass CSV of index names, or wildcards
common attributes
see the full list of mapping parameters
the following attributes are supported for most field types:
store-trueto store the field on its own in the index; defaultfalse(the JSON doc is stored in_source, and the field can be extracted from it)index-true= indexed and searchable;false= not searchable at all (still in_source)doc_values- on-disk column store used for sorting and aggregations; defaulttruefor all buttextnull_value- value to index when the field isnull; default "do not add the field"copy_to- copy the value into another field, e.g. to search several fields as one (what the old_allfield did)ignore_malformed- ignore malformed record? (e.g. string instead of number); defaultfalsefields- sub-fields, the same value indexed in other ways (thetitle.keywordabove)
specific attributes
date
format- defaultstrict_date_optional_time||epoch_millis(see the full date formats list)
text
analyzer- how the text is split into terms, defaultstandard; there are language ones too, e.g.english(stemming, stop words)
binary
- base64 representation of binary data, not searchable
example
{
"properties" : {
"user" : { "type" : "keyword" },
"message" : { "type" : "text", "analyzer" : "english" },
"postDate" : { "type" : "date" },
"priority" : { "type" : "integer" },
"rank" : { "type" : "float", "null_value" : 1.0 },
"tags" : { "type" : "keyword" }
}
}
diagnostics
the _cat APIs give plain-text tables, ?v adds the header:
curl 'localhost:9200/_cat/health?v'
curl 'localhost:9200/_cat/indices?v'
curl 'localhost:9200/_cat/shards?v'
health
curl -XGET 'localhost:9200/_cluster/health?pretty'
green = all shards allocated, yellow = some replicas not (the usual state on a single node), red = a primary shard is missing
stats
curl -XGET 'localhost:9200/twitter/_stats'
CSV indices, wildcards, or none for all of them, can be used
recovery
curl -XGET 'localhost:9200/twitter/_recovery'