OpenSearch/docs/reference/getting-started.asciidoc

1262 lines
52 KiB
Plaintext
Raw Normal View History

2014-04-18 13:51:59 -04:00
[[getting-started]]
= Getting started with {es}
2014-04-18 13:51:59 -04:00
[partintro]
--
Ready to take {es} for a test drive and see for yourself how you can use the
REST APIs to store, search, and analyze data?
2014-04-18 13:51:59 -04:00
Step through this getting started tutorial to:
2014-04-18 13:51:59 -04:00
. Get an {es} instance up and running
. Index some sample documents
. Search for documents using the {es} query language
. Analyze the results using bucket and metrics aggregations
2014-04-18 13:51:59 -04:00
Need more context?
Check out the <<elasticsearch-intro,
Elasticsearch Introduction>> to learn the lingo and understand the basics of
how {es} works. If you're already familiar with {es} and want to see how it works
with the rest of the stack, you might want to jump to the
{stack-gs}/get-started-elastic-stack.html[Elastic Stack
Tutorial] to see how to set up a system monitoring solution with {es}, {kib},
{beats}, and {ls}.
2014-04-18 13:51:59 -04:00
TIP: The fastest way to get started with {es} is to
https://www.elastic.co/cloud/elasticsearch-service/signup[start a free 14-day
trial of Elasticsearch Service] in the cloud.
--
2014-04-18 13:51:59 -04:00
2018-12-06 13:14:37 -05:00
[[getting-started-install]]
2014-04-18 13:51:59 -04:00
== Installation
[TIP]
==============
You can skip having to install Elasticsearch by using our
https://www.elastic.co/cloud/elasticsearch-service[hosted Elasticsearch Service]
on Elastic Cloud. The Elasticsearch Service is available on both AWS and GCP.
https://www.elastic.co/cloud/elasticsearch-service/signup[Try out the
Elasticsearch Service for free].
==============
NOTE: Elasticsearch includes a bundled version of http://openjdk.java.net[OpenJDK]
from the JDK maintainers (GPLv2+CE). To use your own version of Java,
see the <<jvm-version, JVM version requirements>>
2014-04-18 13:51:59 -04:00
The binaries are available from http://www.elastic.co/downloads[`www.elastic.co/downloads`].
Platform dependent archives are available for Windows, Linux and macOS. In addition,
`DEB` and `RPM` packages are available for Linux, and an `MSI` installation package
is available for Windows. You can also use the Elastic Homebrew tap to <<brew,install
using the brew package manager>> on macOS.
2014-04-18 13:51:59 -04:00
[float]
=== Installation example on Linux
For simplicity, let's use the {ref}/targz.html[tar] file.
Let's download the Elasticsearch {version} Linux tar as follows:
2014-04-18 13:51:59 -04:00
["source","sh",subs="attributes,callouts"]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
curl -L -O https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-{version}-linux-x86_64.tar.gz
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// NOTCONSOLE
2014-04-18 13:51:59 -04:00
Then extract it as follows:
2014-04-18 13:51:59 -04:00
["source","sh",subs="attributes,callouts"]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
tar -xvf elasticsearch-{version}-linux-x86_64.tar.gz
2014-04-18 13:51:59 -04:00
--------------------------------------------------
It will then create a bunch of files and folders in your current directory. We then go into the bin directory as follows:
["source","sh",subs="attributes,callouts"]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
cd elasticsearch-{version}/bin
2014-04-18 13:51:59 -04:00
--------------------------------------------------
And now we are ready to start our node and single cluster:
2014-04-18 13:51:59 -04:00
[source,sh]
--------------------------------------------------
./elasticsearch
--------------------------------------------------
[float]
=== Installation example with MSI Windows Installer
For Windows users, we recommend using the {ref}/windows.html[MSI Installer package]. The package contains a graphical user interface (GUI) that guides you through the installation process.
First, download the Elasticsearch {version} MSI from
https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-{version}.msi.
Then double-click the downloaded file to launch the GUI. Within the first screen, select the deployment directories:
[[getting-started-msi-installer-locations]]
image::images/msi_installer/msi_installer_locations.png[]
Then select whether to install as a service or start Elasticsearch manually as needed.
To align with the Linux example, choose not to install as a service:
[[getting-started-msi-installer-service]]
image::images/msi_installer/msi_installer_no_service.png[]
For configuration, simply leave the default values:
[[getting-started-msi-installer-configuration]]
image::images/msi_installer/msi_installer_configuration.png[]
Again, to align with the tar example, uncheck all plugins to not install any plugins:
[[getting-started-msi-installer-plugins]]
image::images/msi_installer/msi_installer_plugins.png[]
After clicking the install button, Elasticsearch will be installed:
[[getting-started-msi-installer-success]]
image::images/msi_installer/msi_installer_success.png[]
By default, Elasticsearch will be installed at `%PROGRAMFILES%\Elastic\Elasticsearch`. Navigate here and go into the bin directory as follows:
**with Command Prompt:**
[source,sh]
--------------------------------------------------
cd %PROGRAMFILES%\Elastic\Elasticsearch\bin
--------------------------------------------------
**with PowerShell:**
[source,powershell]
--------------------------------------------------
cd $env:PROGRAMFILES\Elastic\Elasticsearch\bin
--------------------------------------------------
And now we are ready to start our node and single cluster:
[source,sh]
--------------------------------------------------
.\elasticsearch.exe
--------------------------------------------------
[float]
[[successfully-running-node]]
=== Successfully running node
If everything goes well with installation, you should see a bunch of messages that look like below:
2014-04-18 13:51:59 -04:00
["source","sh",subs="attributes,callouts"]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
[2018-09-13T12:20:01,766][INFO ][o.e.e.NodeEnvironment ] [localhost.localdomain] using [1] data paths, mounts [[/home (/dev/mapper/fedora-home)]], net usable_space [335.3gb], net total_space [410.3gb], types [ext4]
[2018-09-13T12:20:01,772][INFO ][o.e.e.NodeEnvironment ] [localhost.localdomain] heap size [990.7mb], compressed ordinary object pointers [true]
[2018-09-13T12:20:01,774][INFO ][o.e.n.Node ] [localhost.localdomain] node name [localhost.localdomain], node ID [B0aEHNagTiWx7SYj-l4NTw]
[2018-09-13T12:20:01,775][INFO ][o.e.n.Node ] [localhost.localdomain] version[{version}], pid[13030], build[oss/zip/77fc20e/2018-09-13T15:37:57.478402Z], OS[Linux/4.16.11-100.fc26.x86_64/amd64], JVM["Oracle Corporation"/OpenJDK 64-Bit Server VM/10/10+46]
[2018-09-13T12:20:01,775][INFO ][o.e.n.Node ] [localhost.localdomain] JVM arguments [-Xms1g, -Xmx1g, -XX:+UseConcMarkSweepGC, -XX:CMSInitiatingOccupancyFraction=75, -XX:+UseCMSInitiatingOccupancyOnly, -XX:+AlwaysPreTouch, -Xss1m, -Djava.awt.headless=true, -Dfile.encoding=UTF-8, -Djna.nosys=true, -XX:-OmitStackTraceInFastThrow, -Dio.netty.noUnsafe=true, -Dio.netty.noKeySetOptimization=true, -Dio.netty.recycler.maxCapacityPerThread=0, -Dlog4j.shutdownHookEnabled=false, -Dlog4j2.disable.jmx=true, -Djava.io.tmpdir=/tmp/elasticsearch.LN1ctLCi, -XX:+HeapDumpOnOutOfMemoryError, -XX:HeapDumpPath=data, -XX:ErrorFile=logs/hs_err_pid%p.log, -Xlog:gc*,gc+age=trace,safepoint:file=logs/gc.log:utctime,pid,tags:filecount=32,filesize=64m, -Djava.locale.providers=COMPAT, -XX:UseAVX=2, -Dio.netty.allocator.type=unpooled, -Des.path.home=/home/manybubbles/Workspaces/Elastic/master/elasticsearch/qa/unconfigured-node-name/build/cluster/integTestCluster node0/elasticsearch-7.0.0-alpha1-SNAPSHOT, -Des.path.conf=/home/manybubbles/Workspaces/Elastic/master/elasticsearch/qa/unconfigured-node-name/build/cluster/integTestCluster node0/elasticsearch-7.0.0-alpha1-SNAPSHOT/config, -Des.distribution.flavor=oss, -Des.distribution.type=zip]
[2018-09-13T12:20:02,543][INFO ][o.e.p.PluginsService ] [localhost.localdomain] loaded module [aggs-matrix-stats]
[2018-09-13T12:20:02,543][INFO ][o.e.p.PluginsService ] [localhost.localdomain] loaded module [analysis-common]
[2018-09-13T12:20:02,543][INFO ][o.e.p.PluginsService ] [localhost.localdomain] loaded module [ingest-common]
[2018-09-13T12:20:02,544][INFO ][o.e.p.PluginsService ] [localhost.localdomain] loaded module [lang-expression]
[2018-09-13T12:20:02,544][INFO ][o.e.p.PluginsService ] [localhost.localdomain] loaded module [lang-mustache]
[2018-09-13T12:20:02,544][INFO ][o.e.p.PluginsService ] [localhost.localdomain] loaded module [lang-painless]
[2018-09-13T12:20:02,544][INFO ][o.e.p.PluginsService ] [localhost.localdomain] loaded module [mapper-extras]
[2018-09-13T12:20:02,544][INFO ][o.e.p.PluginsService ] [localhost.localdomain] loaded module [parent-join]
[2018-09-13T12:20:02,544][INFO ][o.e.p.PluginsService ] [localhost.localdomain] loaded module [percolator]
[2018-09-13T12:20:02,544][INFO ][o.e.p.PluginsService ] [localhost.localdomain] loaded module [rank-eval]
[2018-09-13T12:20:02,544][INFO ][o.e.p.PluginsService ] [localhost.localdomain] loaded module [reindex]
[2018-09-13T12:20:02,545][INFO ][o.e.p.PluginsService ] [localhost.localdomain] loaded module [repository-url]
[2018-09-13T12:20:02,545][INFO ][o.e.p.PluginsService ] [localhost.localdomain] loaded module [transport-netty4]
[2018-09-13T12:20:02,545][INFO ][o.e.p.PluginsService ] [localhost.localdomain] no plugins loaded
[2018-09-13T12:20:04,657][INFO ][o.e.d.DiscoveryModule ] [localhost.localdomain] using discovery type [zen]
[2018-09-13T12:20:05,006][INFO ][o.e.n.Node ] [localhost.localdomain] initialized
[2018-09-13T12:20:05,007][INFO ][o.e.n.Node ] [localhost.localdomain] starting ...
[2018-09-13T12:20:05,202][INFO ][o.e.t.TransportService ] [localhost.localdomain] publish_address {127.0.0.1:9300}, bound_addresses {[::1]:9300}, {127.0.0.1:9300}
[2018-09-13T12:20:05,221][WARN ][o.e.b.BootstrapChecks ] [localhost.localdomain] max file descriptors [4096] for elasticsearch process is too low, increase to at least [65535]
[2018-09-13T12:20:05,221][WARN ][o.e.b.BootstrapChecks ] [localhost.localdomain] max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]
[2018-09-13T12:20:08,355][INFO ][o.e.c.s.MasterService ] [localhost.localdomain] elected-as-master ([0] nodes joined)[, ], reason: master node changed {previous [], current [{localhost.localdomain}{B0aEHNagTiWx7SYj-l4NTw}{hzsQz6CVQMCTpMCVLM4IHg}{127.0.0.1}{127.0.0.1:9300}{testattr=test}]}
[2018-09-13T12:20:08,360][INFO ][o.e.c.s.ClusterApplierService] [localhost.localdomain] master node changed {previous [], current [{localhost.localdomain}{B0aEHNagTiWx7SYj-l4NTw}{hzsQz6CVQMCTpMCVLM4IHg}{127.0.0.1}{127.0.0.1:9300}{testattr=test}]}, reason: apply cluster state (from master [master {localhost.localdomain}{B0aEHNagTiWx7SYj-l4NTw}{hzsQz6CVQMCTpMCVLM4IHg}{127.0.0.1}{127.0.0.1:9300}{testattr=test} committed version [1] source [elected-as-master ([0] nodes joined)[, ]]])
[2018-09-13T12:20:08,384][INFO ][o.e.h.n.Netty4HttpServerTransport] [localhost.localdomain] publish_address {127.0.0.1:9200}, bound_addresses {[::1]:9200}, {127.0.0.1:9200}
[2018-09-13T12:20:08,384][INFO ][o.e.n.Node ] [localhost.localdomain] started
2014-04-18 13:51:59 -04:00
--------------------------------------------------
Without going too much into detail, we can see that our node named "localhost.localdomain" has started and elected itself as a master in a single cluster. Don't worry yet at the moment what master means. The main thing that is important here is that we have started one node within one cluster.
2014-04-18 13:51:59 -04:00
As mentioned previously, we can override either the cluster or node name. This can be done from the command line when starting Elasticsearch as follows:
[source,sh]
--------------------------------------------------
./elasticsearch -Ecluster.name=my_cluster_name -Enode.name=my_node_name
2014-04-18 13:51:59 -04:00
--------------------------------------------------
Also note the line marked http with information about the HTTP address (`192.168.8.112`) and port (`9200`) that our node is reachable from. By default, Elasticsearch uses port `9200` to provide access to its REST API. This port is configurable if necessary.
2018-12-06 13:14:37 -05:00
[[getting-started-explore]]
2014-04-18 13:51:59 -04:00
== Exploring Your Cluster
[float]
=== The REST API
Now that we have our node (and cluster) up and running, the next step is to understand how to communicate with it. Fortunately, Elasticsearch provides a very comprehensive and powerful REST API that you can use to interact with your cluster. Among the few things that can be done with the API are as follows:
2014-04-18 13:51:59 -04:00
* Check your cluster, node, and index health, status, and statistics
* Administer your cluster, node, and index data and metadata
* Perform CRUD (Create, Read, Update, and Delete) and search operations against your indexes
* Execute advanced search operations such as paging, sorting, filtering, scripting, aggregations, and many others
2014-04-18 13:51:59 -04:00
2018-12-06 13:14:37 -05:00
[[getting-started-cluster-health]]
2014-04-18 13:51:59 -04:00
=== Cluster Health
Let's start with a basic health check, which we can use to see how our cluster is doing. We'll be using curl to do this but you can use any tool that allows you to make HTTP/REST calls. Let's assume that we are still on the same node where we started Elasticsearch on and open another command shell window.
2014-04-18 13:51:59 -04:00
To check the cluster health, we will be using the {ref}/cat.html[`_cat` API]. You can
run the command below in {kibana-ref}/console-kibana.html[Kibana's Console]
by clicking "VIEW IN CONSOLE" or with `curl` by clicking the "COPY AS CURL"
link below and pasting it into a terminal.
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /_cat/health?v
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
2014-04-18 13:51:59 -04:00
And the response:
[source,txt]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
epoch timestamp cluster status node.total node.data shards pri relo init unassign pending_tasks max_task_wait_time active_shards_percent
1475247709 17:01:49 elasticsearch green 1 1 0 0 0 0 0 0 - 100.0%
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// TESTRESPONSE[s/1475247709 17:01:49 elasticsearch/\\d+ \\d+:\\d+:\\d+ integTest/]
// TESTRESPONSE[s/0 0 -/0 \\d+ -/]
// TESTRESPONSE[non_json]
2014-04-18 13:51:59 -04:00
We can see that our cluster named "elasticsearch" is up with a green status.
2014-04-18 13:51:59 -04:00
Whenever we ask for the cluster health, we either get green, yellow, or red.
* Green - everything is good (cluster is fully functional)
* Yellow - all data is available but some replicas are not yet allocated (cluster is fully functional)
* Red - some data is not available for whatever reason (cluster is partially functional)
**Note:** When a cluster is red, it will continue to serve search requests from the available shards but you will likely need to fix it ASAP since there are unassigned shards.
Also from the above response, we can see a total of 1 node and that we have 0 shards since we have no data in it yet. Note that since we are using the default cluster name (elasticsearch) and since Elasticsearch uses unicast network discovery by default to find other nodes on the same machine, it is possible that you could accidentally start up more than one node on your computer and have them all join a single cluster. In this scenario, you may see more than 1 node in the above response.
2014-04-18 13:51:59 -04:00
We can also get a list of nodes in our cluster as follows:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /_cat/nodes?v
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
2014-04-18 13:51:59 -04:00
And the response:
[source,txt]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
ip heap.percent ram.percent cpu load_1m load_5m load_15m node.role master name
127.0.0.1 10 5 5 4.46 dim * PB2SGZY
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// TESTRESPONSE[s/10 5 5 4.46/\\d+ \\d+ \\d+ (\\d+\\.\\d+)? (\\d+\\.\\d+)? (\\d+\.\\d+)?/]
// TESTRESPONSE[s/[*]/[*]/ s/PB2SGZY/.+/ non_json]
2014-04-18 13:51:59 -04:00
Here, we can see our one node named "PB2SGZY", which is the single node that is currently in our cluster.
2018-12-06 13:14:37 -05:00
[[getting-started-list-indices]]
=== List All Indices
2014-04-18 13:51:59 -04:00
Now let's take a peek at our indices:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /_cat/indices?v
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
2014-04-18 13:51:59 -04:00
And the response:
[source,txt]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// TESTRESPONSE[non_json]
2014-04-18 13:51:59 -04:00
Which simply means we have no indices yet in the cluster.
2014-04-18 13:51:59 -04:00
2018-12-06 13:14:37 -05:00
[[getting-started-create-index]]
2014-04-18 13:51:59 -04:00
=== Create an Index
Now let's create an index named "customer" and then list all the indexes again:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
PUT /customer?pretty
GET /_cat/indices?v
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
2014-04-18 13:51:59 -04:00
The first command creates the index named "customer" using the PUT verb. We simply append `pretty` to the end of the call to tell it to pretty-print the JSON response (if any).
2014-04-18 13:51:59 -04:00
And the response:
[source,txt]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
yellow open customer 95SQ4TSUT7mWBT7VNHH67A 1 1 0 0 260b 260b
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// TESTRESPONSE[s/95SQ4TSUT7mWBT7VNHH67A/.+/ s/260b/\\d+\\.?\\d?k?b/ non_json]
2014-04-18 13:51:59 -04:00
The results of the second command tells us that we now have one index named customer and it has one primary shard and one replica (the defaults) and it contains zero documents in it.
2014-04-18 13:51:59 -04:00
You might also notice that the customer index has a yellow health tagged to it. Recall from our previous discussion that yellow means that some replicas are not (yet) allocated. The reason this happens for this index is because Elasticsearch by default created one replica for this index. Since we only have one node running at the moment, that one replica cannot yet be allocated (for high availability) until a later point in time when another node joins the cluster. Once that replica gets allocated onto a second node, the health status for this index will turn to green.
2018-12-06 13:14:37 -05:00
[[getting-started-query-document]]
2014-04-18 13:51:59 -04:00
=== Index and Query a Document
Let's now put something into our customer index. We'll index a simple customer document into the customer index, with an ID of 1 as follows:
2014-04-18 13:51:59 -04:00
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
PUT /customer/_doc/1?pretty
{
"name": "John Doe"
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
2014-04-18 13:51:59 -04:00
And the response:
Enforce that responses in docs are valid json (#26249) All of the snippets in our docs marked with `// TESTRESPONSE` are checked against the response from Elasticsearch but, due to the way they are implemented they are actually parsed as YAML instead of JSON. Luckilly, all valid JSON is valid YAML! Unfurtunately that means that invalid JSON has snuck into the exmples! This adds a step during the build to parse them as JSON and fail the build if they don't parse. But no! It isn't quite that simple. The displayed text of some of these responses looks like: ``` { ... "aggregations": { "range": { "buckets": [ { "to": 1.4436576E12, "to_as_string": "10-2015", "doc_count": 7, "key": "*-10-2015" }, { "from": 1.4436576E12, "from_as_string": "10-2015", "doc_count": 0, "key": "10-2015-*" } ] } } } ``` Note the `...` which isn't valid json but we like it anyway and want it in the output. We use substitution rules to convert the `...` into the response we expect. That yields a response that looks like: ``` { "took": $body.took,"timed_out": false,"_shards": $body._shards,"hits": $body.hits, "aggregations": { "range": { "buckets": [ { "to": 1.4436576E12, "to_as_string": "10-2015", "doc_count": 7, "key": "*-10-2015" }, { "from": 1.4436576E12, "from_as_string": "10-2015", "doc_count": 0, "key": "10-2015-*" } ] } } } ``` That is what the tests consume but it isn't valid JSON! Oh no! We don't want to go update all the substitution rules because that'd be huge and, ultimately, wouldn't buy much. So we quote the `$body.took` bits before parsing the JSON. Note the responses that we use for the `_cat` APIs are all converted into regexes and there is no expectation that they are valid JSON. Closes #26233
2017-08-17 09:02:10 -04:00
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
{
"_index" : "customer",
"_type" : "_doc",
2014-04-18 13:51:59 -04:00
"_id" : "1",
"_version" : 1,
"result" : "created",
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1
2014-04-18 13:51:59 -04:00
}
--------------------------------------------------
// TESTRESPONSE[s/"_seq_no" : \d+/"_seq_no" : $body._seq_no/ s/"_primary_term" : 1/"_primary_term" : $body._primary_term/]
2014-04-18 13:51:59 -04:00
From the above, we can see that a new customer document was successfully created inside the customer index. The document also has an internal id of 1 which we specified at index time.
2014-04-18 13:51:59 -04:00
It is important to note that Elasticsearch does not require you to explicitly create an index first before you can index documents into it. In the previous example, Elasticsearch will automatically create the customer index if it didn't already exist beforehand.
2014-04-18 13:51:59 -04:00
Let's now retrieve that document that we just indexed:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /customer/_doc/1?pretty
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
And the response:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
{
"_index" : "customer",
"_type" : "_doc",
2014-04-18 13:51:59 -04:00
"_id" : "1",
"_version" : 1,
"_seq_no" : 25,
"_primary_term" : 1,
"found" : true,
"_source" : { "name": "John Doe" }
2014-04-18 13:51:59 -04:00
}
--------------------------------------------------
// TESTRESPONSE[s/"_seq_no" : \d+/"_seq_no" : $body._seq_no/ s/"_primary_term" : 1/"_primary_term" : $body._primary_term/]
2014-04-18 13:51:59 -04:00
Nothing out of the ordinary here other than a field, `found`, stating that we found a document with the requested ID 1 and another field, `_source`, which returns the full JSON document that we indexed from the previous step.
2018-12-06 13:14:37 -05:00
[[getting-started-delete-index]]
2014-04-18 13:51:59 -04:00
=== Delete an Index
Now let's delete the index that we just created and then list all the indexes again:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
DELETE /customer?pretty
GET /_cat/indices?v
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
And the response:
[source,txt]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// TESTRESPONSE[non_json]
2014-04-18 13:51:59 -04:00
Which means that the index was deleted successfully and we are now back to where we started with nothing in our cluster.
Before we move on, let's take a closer look again at some of the API commands that we have learned so far:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
PUT /customer
PUT /customer/_doc/1
{
"name": "John Doe"
}
GET /customer/_doc/1
DELETE /customer
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
2014-04-18 13:51:59 -04:00
If we study the above commands carefully, we can actually see a pattern of how we access data in Elasticsearch. That pattern can be summarized as follows:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
<HTTP Verb> /<Index>/<Endpoint>/<ID>
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// NOTCONSOLE
This REST access pattern is so pervasive throughout all the API commands that if you can simply remember it, you will have a good head start at mastering Elasticsearch.
2014-04-18 13:51:59 -04:00
2018-12-06 13:14:37 -05:00
[[getting-started-modify-data]]
2014-04-18 13:51:59 -04:00
== Modifying Your Data
Elasticsearch provides data manipulation and search capabilities in near real time. By default, you can expect a one second delay (refresh interval) from the time you index/update/delete your data until the time that it appears in your search results. This is an important distinction from other platforms like SQL wherein data is immediately available after a transaction is completed.
[float]
[[indexing-replacing-documents]]
2014-04-18 13:51:59 -04:00
=== Indexing/Replacing Documents
We've previously seen how we can index a single document. Let's recall that command again:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
PUT /customer/_doc/1?pretty
{
"name": "John Doe"
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
2014-04-18 13:51:59 -04:00
Again, the above will index the specified document into the customer index, with the ID of 1. If we then executed the above command again with a different (or same) document, Elasticsearch will replace (i.e. reindex) a new document on top of the existing one with the ID of 1:
2014-04-18 13:51:59 -04:00
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
PUT /customer/_doc/1?pretty
{
"name": "Jane Doe"
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
The above changes the name of the document with the ID of 1 from "John Doe" to "Jane Doe". If, on the other hand, we use a different ID, a new document will be indexed and the existing document(s) already in the index remains untouched.
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
PUT /customer/_doc/2?pretty
{
"name": "Jane Doe"
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
The above indexes a new document with an ID of 2.
When indexing, the ID part is optional. If not specified, Elasticsearch will generate a random ID and then use it to index the document. The actual ID Elasticsearch generates (or whatever we specified explicitly in the previous examples) is returned as part of the index API call.
This example shows how to index a document without an explicit ID:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
POST /customer/_doc?pretty
{
"name": "Jane Doe"
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
Note that in the above case, we are using the `POST` verb instead of PUT since we didn't specify an ID.
2014-04-18 13:51:59 -04:00
2018-12-06 13:14:37 -05:00
[[getting-started-update-documents]]
2014-04-18 13:51:59 -04:00
=== Updating Documents
In addition to being able to index and replace documents, we can also update documents. Note though that Elasticsearch does not actually do in-place updates under the hood. Whenever we do an update, Elasticsearch deletes the old document and then indexes a new document with the update applied to it in one shot.
This example shows how to update our previous document (ID of 1) by changing the name field to "Jane Doe":
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
POST /customer/_update/1?pretty
2014-04-18 13:51:59 -04:00
{
"doc": { "name": "Jane Doe" }
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
This example shows how to update our previous document (ID of 1) by changing the name field to "Jane Doe" and at the same time add an age field to it:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
POST /customer/_update/1?pretty
2014-04-18 13:51:59 -04:00
{
"doc": { "name": "Jane Doe", "age": 20 }
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
Updates can also be performed by using simple scripts. This example uses a script to increment the age by 5:
2014-04-18 13:51:59 -04:00
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
POST /customer/_update/1?pretty
2014-04-18 13:51:59 -04:00
{
"script" : "ctx._source.age += 5"
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
In the above example, `ctx._source` refers to the current source document that is about to be updated.
Elasticsearch provides the ability to update multiple documents given a query condition (like an `SQL UPDATE-WHERE` statement). See {ref}/docs-update-by-query.html[`docs-update-by-query` API]
2014-04-18 13:51:59 -04:00
2018-12-06 13:14:37 -05:00
[[getting-started-delete-documents]]
2014-04-18 13:51:59 -04:00
=== Deleting Documents
Deleting a document is fairly straightforward. This example shows how to delete our previous customer with the ID of 2:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
DELETE /customer/_doc/2?pretty
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
See the {ref}/docs-delete-by-query.html[`_delete_by_query` API] to delete all documents matching a specific query.
It is worth noting that it is much more efficient to delete a whole index
instead of deleting all documents with the Delete By Query API.
2014-04-18 13:51:59 -04:00
2018-12-06 13:14:37 -05:00
[[getting-started-batch-processing]]
2014-04-18 13:51:59 -04:00
=== Batch Processing
In addition to being able to index, update, and delete individual documents, Elasticsearch also provides the ability to perform any of the above operations in batches using the {ref}/docs-bulk.html[`_bulk` API]. This functionality is important in that it provides a very efficient mechanism to do multiple operations as fast as possible with as few network roundtrips as possible.
2014-04-18 13:51:59 -04:00
As a quick example, the following call indexes two documents (ID 1 - John Doe and ID 2 - Jane Doe) in one bulk operation:
2014-04-18 13:51:59 -04:00
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
POST /customer/_bulk?pretty
2014-04-18 13:51:59 -04:00
{"index":{"_id":"1"}}
{"name": "John Doe" }
{"index":{"_id":"2"}}
{"name": "Jane Doe" }
--------------------------------------------------
// CONSOLE
2014-04-18 13:51:59 -04:00
This example updates the first document (ID of 1) and then deletes the second document (ID of 2) in one bulk operation:
[source,sh]
--------------------------------------------------
POST /customer/_bulk?pretty
2014-04-18 13:51:59 -04:00
{"update":{"_id":"1"}}
{"doc": { "name": "John Doe becomes Jane Doe" } }
{"delete":{"_id":"2"}}
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
Note above that for the delete action, there is no corresponding source document after it since deletes only require the ID of the document to be deleted.
The Bulk API does not fail due to failures in one of the actions. If a single action fails for whatever reason, it will continue to process the remainder of the actions after it. When the bulk API returns, it will provide a status for each action (in the same order it was sent in) so that you can check if a specific action failed or not.
2014-04-18 13:51:59 -04:00
2018-12-06 13:14:37 -05:00
[[getting-started-explore-data]]
2014-04-18 13:51:59 -04:00
== Exploring Your Data
[float]
=== Sample Dataset
Now that we've gotten a glimpse of the basics, let's try to work on a more realistic dataset. I've prepared a sample of fictitious JSON documents of customer bank account information. Each document has the following schema:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
{
"account_number": 0,
"balance": 16623,
"firstname": "Bradshaw",
"lastname": "Mckenzie",
"age": 29,
"gender": "F",
"address": "244 Columbus Place",
"employer": "Euron",
"email": "bradshawmckenzie@euron.com",
"city": "Hobucken",
"state": "CO"
}
--------------------------------------------------
// NOTCONSOLE
2014-04-18 13:51:59 -04:00
For the curious, this data was generated using http://www.json-generator.com/[`www.json-generator.com/`], so please ignore the actual values and semantics of the data as these are all randomly generated.
2014-04-18 13:51:59 -04:00
[float]
=== Loading the Sample Dataset
You can download the sample dataset (accounts.json) from https://github.com/elastic/elasticsearch/blob/master/docs/src/test/resources/accounts.json?raw=true[here]. Extract it to our current directory and let's load it into our cluster as follows:
2014-04-18 13:51:59 -04:00
[source,sh]
--------------------------------------------------
curl -H "Content-Type: application/json" -XPOST "localhost:9200/bank/_bulk?pretty&refresh" --data-binary "@accounts.json"
curl "localhost:9200/_cat/indices?v"
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// NOTCONSOLE
////
This replicates the above in a document-testing friendly way but isn't visible
in the docs:
[source,js]
--------------------------------------------------
GET /_cat/indices?v
--------------------------------------------------
// CONSOLE
// TEST[setup:bank]
////
2014-04-18 13:51:59 -04:00
And the response:
Enforce that responses in docs are valid json (#26249) All of the snippets in our docs marked with `// TESTRESPONSE` are checked against the response from Elasticsearch but, due to the way they are implemented they are actually parsed as YAML instead of JSON. Luckilly, all valid JSON is valid YAML! Unfurtunately that means that invalid JSON has snuck into the exmples! This adds a step during the build to parse them as JSON and fail the build if they don't parse. But no! It isn't quite that simple. The displayed text of some of these responses looks like: ``` { ... "aggregations": { "range": { "buckets": [ { "to": 1.4436576E12, "to_as_string": "10-2015", "doc_count": 7, "key": "*-10-2015" }, { "from": 1.4436576E12, "from_as_string": "10-2015", "doc_count": 0, "key": "10-2015-*" } ] } } } ``` Note the `...` which isn't valid json but we like it anyway and want it in the output. We use substitution rules to convert the `...` into the response we expect. That yields a response that looks like: ``` { "took": $body.took,"timed_out": false,"_shards": $body._shards,"hits": $body.hits, "aggregations": { "range": { "buckets": [ { "to": 1.4436576E12, "to_as_string": "10-2015", "doc_count": 7, "key": "*-10-2015" }, { "from": 1.4436576E12, "from_as_string": "10-2015", "doc_count": 0, "key": "10-2015-*" } ] } } } ``` That is what the tests consume but it isn't valid JSON! Oh no! We don't want to go update all the substitution rules because that'd be huge and, ultimately, wouldn't buy much. So we quote the `$body.took` bits before parsing the JSON. Note the responses that we use for the `_cat` APIs are all converted into regexes and there is no expectation that they are valid JSON. Closes #26233
2017-08-17 09:02:10 -04:00
[source,txt]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
yellow open bank l7sSYV2cQXmu6_4rJWVIww 5 1 1000 0 128.6kb 128.6kb
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// TESTRESPONSE[s/128.6kb/\\d+(\\.\\d+)?[mk]?b/]
// TESTRESPONSE[s/l7sSYV2cQXmu6_4rJWVIww/.+/ non_json]
2014-04-18 13:51:59 -04:00
Which means that we just successfully bulk indexed 1000 documents into the bank index.
2014-04-18 13:51:59 -04:00
2018-12-06 13:14:37 -05:00
[[getting-started-search-API]]
2014-04-18 13:51:59 -04:00
=== The Search API
Now let's start with some simple searches. There are two basic ways to run searches: one is by sending search parameters through the {ref}/search-uri-request.html[REST request URI] and the other by sending them through the {ref}/search-request-body.html[REST request body]. The request body method allows you to be more expressive and also to define your searches in a more readable JSON format. We'll try one example of the request URI method but for the remainder of this tutorial, we will exclusively be using the request body method.
2014-04-18 13:51:59 -04:00
The REST API for search is accessible from the `_search` endpoint. This example returns all documents in the bank index:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search?q=*&sort=account_number:asc&pretty
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
Let's first dissect the search call. We are searching (`_search` endpoint) in the bank index, and the `q=*` parameter instructs Elasticsearch to match all documents in the index. The `sort=account_number:asc` parameter indicates to sort the results using the `account_number` field of each document in an ascending order. The `pretty` parameter, again, just tells Elasticsearch to return pretty-printed JSON results.
2014-04-18 13:51:59 -04:00
And the response (partially shown):
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
{
"took" : 63,
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
Add a shard filter search phase to pre-filter shards based on query rewriting (#25658) Today if we search across a large amount of shards we hit every shard. Yet, it's quite common to search across an index pattern for time based indices but filtering will exclude all results outside a certain time range ie. `now-3d`. While the search can potentially hit hundreds of shards the majority of the shards might yield 0 results since there is not document that is within this date range. Kibana for instance does this regularly but used `_field_stats` to optimize the indexes they need to query. Now with the deprecation of `_field_stats` and it's upcoming removal a single dashboard in kibana can potentially turn into searches hitting hundreds or thousands of shards and that can easily cause search rejections even though the most of the requests are very likely super cheap and only need a query rewriting to early terminate with 0 results. This change adds a pre-filter phase for searches that can, if the number of shards are higher than a the `pre_filter_shard_size` threshold (defaults to 128 shards), fan out to the shards and check if the query can potentially match any documents at all. While false positives are possible, a negative response means that no matches are possible. These requests are not subject to rejection and can greatly reduce the number of shards a request needs to hit. The approach here is preferable to the kibana approach with field stats since it correctly handles aliases and uses the correct threadpools to execute these requests. Further it's completely transparent to the user and improves scalability of elasticsearch in general on large clusters.
2017-07-12 16:19:20 -04:00
"skipped" : 0,
2014-04-18 13:51:59 -04:00
"failed" : 0
},
"hits" : {
"total" : {
"value": 1000,
"relation": "eq"
},
"max_score" : null,
2014-04-18 13:51:59 -04:00
"hits" : [ {
"_index" : "bank",
"_type" : "_doc",
"_id" : "0",
"sort": [0],
"_score" : null,
"_source" : {"account_number":0,"balance":16623,"firstname":"Bradshaw","lastname":"Mckenzie","age":29,"gender":"F","address":"244 Columbus Place","employer":"Euron","email":"bradshawmckenzie@euron.com","city":"Hobucken","state":"CO"}
2014-04-18 13:51:59 -04:00
}, {
"_index" : "bank",
"_type" : "_doc",
"_id" : "1",
"sort": [1],
"_score" : null,
"_source" : {"account_number":1,"balance":39225,"firstname":"Amber","lastname":"Duke","age":32,"gender":"M","address":"880 Holmes Lane","employer":"Pyrami","email":"amberduke@pyrami.com","city":"Brogan","state":"IL"}
}, ...
]
}
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// TESTRESPONSE[s/"took" : 63/"took" : $body.took/]
// TESTRESPONSE[s/\.\.\./$body.hits.hits.2, $body.hits.hits.3, $body.hits.hits.4, $body.hits.hits.5, $body.hits.hits.6, $body.hits.hits.7, $body.hits.hits.8, $body.hits.hits.9/]
2014-04-18 13:51:59 -04:00
As for the response, we see the following parts:
* `took` time in milliseconds for Elasticsearch to execute the search
* `timed_out` tells us if the search timed out or not
* `_shards` tells us how many shards were searched, as well as a count of the successful/failed searched shards
* `hits` search results
* `hits.total` an object that contains information about the total number of documents matching our search criteria
** `hits.total.value` - the value of the total hit count (must be interpreted in the context of `hits.total.relation`).
** `hits.total.relation` - whether `hits.total.value` is the exact hit count, in which case it is equal to `"eq"` or a
lower bound of the total hit count (greater than or equals), in which case it is equal to `gte`.
2014-04-18 13:51:59 -04:00
* `hits.hits` actual array of search results (defaults to first 10 documents)
* `hits.sort` - sort value of the sort key for each result (missing if sorting by score)
* `hits._score` and `max_score` - ignore these fields for now
2014-04-18 13:51:59 -04:00
The accuracy of `hits.total` is controlled by the request parameter `track_total_hits`, when set to true
the request will track the total hits accurately (`"relation": "eq"`). It defaults to `10,000`
which means that the total hit count is accurately tracked up to `10,000` documents.
You can force an accurate count by setting `track_total_hits` to true explicitly.
See the <<search-request-track-total-hits, request body>> documentation
for more details.
2014-04-18 13:51:59 -04:00
Here is the same exact search above using the alternative request body method:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"query": { "match_all": {} },
"sort": [
{ "account_number": "asc" }
]
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
The difference here is that instead of passing `q=*` in the URI, we provide a JSON-style query request body to the `_search` API. We'll discuss this JSON query in the next section.
2014-04-18 13:51:59 -04:00
////
Hidden response just so we can assert that it is indeed the same but don't have
to clutter the docs with it:
2014-04-18 13:51:59 -04:00
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
{
"took" : 63,
2014-04-18 13:51:59 -04:00
"timed_out" : false,
"_shards" : {
"total" : 5,
"successful" : 5,
Add a shard filter search phase to pre-filter shards based on query rewriting (#25658) Today if we search across a large amount of shards we hit every shard. Yet, it's quite common to search across an index pattern for time based indices but filtering will exclude all results outside a certain time range ie. `now-3d`. While the search can potentially hit hundreds of shards the majority of the shards might yield 0 results since there is not document that is within this date range. Kibana for instance does this regularly but used `_field_stats` to optimize the indexes they need to query. Now with the deprecation of `_field_stats` and it's upcoming removal a single dashboard in kibana can potentially turn into searches hitting hundreds or thousands of shards and that can easily cause search rejections even though the most of the requests are very likely super cheap and only need a query rewriting to early terminate with 0 results. This change adds a pre-filter phase for searches that can, if the number of shards are higher than a the `pre_filter_shard_size` threshold (defaults to 128 shards), fan out to the shards and check if the query can potentially match any documents at all. While false positives are possible, a negative response means that no matches are possible. These requests are not subject to rejection and can greatly reduce the number of shards a request needs to hit. The approach here is preferable to the kibana approach with field stats since it correctly handles aliases and uses the correct threadpools to execute these requests. Further it's completely transparent to the user and improves scalability of elasticsearch in general on large clusters.
2017-07-12 16:19:20 -04:00
"skipped" : 0,
2014-04-18 13:51:59 -04:00
"failed" : 0
},
"hits" : {
"total" : {
"value": 1000,
"relation": "eq"
},
"max_score": null,
2014-04-18 13:51:59 -04:00
"hits" : [ {
"_index" : "bank",
"_type" : "_doc",
"_id" : "0",
"sort": [0],
"_score": null,
"_source" : {"account_number":0,"balance":16623,"firstname":"Bradshaw","lastname":"Mckenzie","age":29,"gender":"F","address":"244 Columbus Place","employer":"Euron","email":"bradshawmckenzie@euron.com","city":"Hobucken","state":"CO"}
2014-04-18 13:51:59 -04:00
}, {
"_index" : "bank",
"_type" : "_doc",
"_id" : "1",
"sort": [1],
"_score": null,
"_source" : {"account_number":1,"balance":39225,"firstname":"Amber","lastname":"Duke","age":32,"gender":"M","address":"880 Holmes Lane","employer":"Pyrami","email":"amberduke@pyrami.com","city":"Brogan","state":"IL"}
}, ...
]
}
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// TESTRESPONSE[s/"took" : 63/"took" : $body.took/]
// TESTRESPONSE[s/\.\.\./$body.hits.hits.2, $body.hits.hits.3, $body.hits.hits.4, $body.hits.hits.5, $body.hits.hits.6, $body.hits.hits.7, $body.hits.hits.8, $body.hits.hits.9/]
////
2014-04-18 13:51:59 -04:00
It is important to understand that once you get your search results back, Elasticsearch is completely done with the request and does not maintain any kind of server-side resources or open cursors into your results. This is in stark contrast to many other platforms such as SQL wherein you may initially get a partial subset of your query results up-front and then you have to continuously go back to the server if you want to fetch (or page through) the rest of the results using some kind of stateful server-side cursor.
2018-12-06 13:14:37 -05:00
[[getting-started-query-lang]]
2014-04-18 13:51:59 -04:00
=== Introducing the Query Language
Elasticsearch provides a JSON-style domain-specific language that you can use to execute queries. This is referred to as the {ref}/query-dsl.html[Query DSL]. The query language is quite comprehensive and can be intimidating at first glance but the best way to actually learn it is to start with a few basic examples.
2014-04-18 13:51:59 -04:00
Going back to our last example, we executed this query:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"query": { "match_all": {} }
}
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
Dissecting the above, the `query` part tells us what our query definition is and the `match_all` part is simply the type of query that we want to run. The `match_all` query is simply a search for all documents in the specified index.
In addition to the `query` parameter, we also can pass other parameters to
influence the search results. In the example in the section above we passed in
`sort`, here we pass in `size`:
2014-04-18 13:51:59 -04:00
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"query": { "match_all": {} },
"size": 1
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
Note that if `size` is not specified, it defaults to 10.
This example does a `match_all` and returns documents 10 through 19:
2014-04-18 13:51:59 -04:00
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"query": { "match_all": {} },
"from": 10,
"size": 10
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
The `from` parameter (0-based) specifies which document index to start from and the `size` parameter specifies how many documents to return starting at the from parameter. This feature is useful when implementing paging of search results. Note that if `from` is not specified, it defaults to 0.
This example does a `match_all` and sorts the results by account balance in descending order and returns the top 10 (default size) documents.
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"query": { "match_all": {} },
"sort": { "balance": { "order": "desc" } }
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
2018-12-06 13:14:37 -05:00
[[getting-started-search]]
2014-04-18 13:51:59 -04:00
=== Executing Searches
Now that we have seen a few of the basic search parameters, let's dig in some more into the Query DSL. Let's first take a look at the returned document fields. By default, the full JSON document is returned as part of all searches. This is referred to as the source (`_source` field in the search hits). If we don't want the entire source document returned, we have the ability to request only a few fields from within source to be returned.
This example shows how to return two fields, `account_number` and `balance` (inside of `_source`), from the search:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"query": { "match_all": {} },
"_source": ["account_number", "balance"]
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
Note that the above example simply reduces the `_source` field. It will still only return one field named `_source` but within it, only the fields `account_number` and `balance` are included.
If you come from a SQL background, the above is somewhat similar in concept to the `SQL SELECT FROM` field list.
Now let's move on to the query part. Previously, we've seen how the `match_all` query is used to match all documents. Let's now introduce a new query called the {ref}/query-dsl-match-query.html[`match` query], which can be thought of as a basic fielded search query (i.e. a search done against a specific field or set of fields).
2014-04-18 13:51:59 -04:00
This example returns the account numbered 20:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"query": { "match": { "account_number": 20 } }
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
This example returns all accounts containing the term "mill" in the address:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"query": { "match": { "address": "mill" } }
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
This example returns all accounts containing the term "mill" or "lane" in the address:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"query": { "match": { "address": "mill lane" } }
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
This example is a variant of `match` (`match_phrase`) that returns all accounts containing the phrase "mill lane" in the address:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"query": { "match_phrase": { "address": "mill lane" } }
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
Let's now introduce the {ref}/query-dsl-bool-query.html[`bool` query]. The `bool` query allows us to compose smaller queries into bigger queries using boolean logic.
2014-04-18 13:51:59 -04:00
This example composes two `match` queries and returns all accounts containing "mill" and "lane" in the address:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"query": {
"bool": {
"must": [
{ "match": { "address": "mill" } },
{ "match": { "address": "lane" } }
]
}
}
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
In the above example, the `bool must` clause specifies all the queries that must be true for a document to be considered a match.
In contrast, this example composes two `match` queries and returns all accounts containing "mill" or "lane" in the address:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"query": {
"bool": {
"should": [
{ "match": { "address": "mill" } },
{ "match": { "address": "lane" } }
]
}
}
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
In the above example, the `bool should` clause specifies a list of queries either of which must be true for a document to be considered a match.
This example composes two `match` queries and returns all accounts that contain neither "mill" nor "lane" in the address:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"query": {
"bool": {
"must_not": [
{ "match": { "address": "mill" } },
{ "match": { "address": "lane" } }
]
}
}
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
In the above example, the `bool must_not` clause specifies a list of queries none of which must be true for a document to be considered a match.
We can combine `must`, `should`, and `must_not` clauses simultaneously inside a `bool` query. Furthermore, we can compose `bool` queries inside any of these `bool` clauses to mimic any complex multi-level boolean logic.
This example returns all accounts of anybody who is 40 years old but doesn't live in ID(aho):
2014-04-18 13:51:59 -04:00
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"query": {
"bool": {
"must": [
{ "match": { "age": "40" } }
],
"must_not": [
{ "match": { "state": "ID" } }
]
}
}
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
2018-12-06 13:14:37 -05:00
[[getting-started-filters]]
2014-04-18 13:51:59 -04:00
=== Executing Filters
In the previous section, we skipped over a little detail called the document score (`_score` field in the search results). The score is a numeric value that is a relative measure of how well the document matches the search query that we specified. The higher the score, the more relevant the document is, the lower the score, the less relevant the document is.
2015-08-29 07:15:11 -04:00
But queries do not always need to produce scores, in particular when they are only used for "filtering" the document set. Elasticsearch detects these situations and automatically optimizes query execution in order not to compute useless scores.
2014-04-18 13:51:59 -04:00
The {ref}/query-dsl-bool-query.html[`bool` query] that we introduced in the previous section also supports `filter` clauses which allow us to use a query to restrict the documents that will be matched by other clauses, without changing how scores are computed. As an example, let's introduce the {ref}/query-dsl-range-query.html[`range` query], which allows us to filter documents by a range of values. This is generally used for numeric or date filtering.
2014-04-18 13:51:59 -04:00
This example uses a bool query to return all accounts with balances between 20000 and 30000, inclusive. In other words, we want to find accounts with a balance that is greater than or equal to 20000 and less than or equal to 30000.
2014-04-18 13:51:59 -04:00
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"query": {
"bool": {
"must": { "match_all": {} },
2014-04-18 13:51:59 -04:00
"filter": {
"range": {
"balance": {
"gte": 20000,
"lte": 30000
}
}
}
}
}
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
Dissecting the above, the bool query contains a `match_all` query (the query part) and a `range` query (the filter part). We can substitute any other queries into the query and the filter parts. In the above case, the range query makes perfect sense since documents falling into the range all match "equally", i.e., no document is more relevant than another.
2014-04-18 13:51:59 -04:00
In addition to the `match_all`, `match`, `bool`, and `range` queries, there are a lot of other query types that are available and we won't go into them here. Since we already have a basic understanding of how they work, it shouldn't be too difficult to apply this knowledge in learning and experimenting with the other query types.
2014-04-18 13:51:59 -04:00
2018-12-06 13:14:37 -05:00
[[getting-started-aggregations]]
2014-04-18 13:51:59 -04:00
=== Executing Aggregations
Aggregations provide the ability to group and extract statistics from your data. The easiest way to think about aggregations is by roughly equating it to the SQL GROUP BY and the SQL aggregate functions. In Elasticsearch, you have the ability to execute searches returning hits and at the same time return aggregated results separate from the hits all in one response. This is very powerful and efficient in the sense that you can run queries and multiple aggregations and get the results back of both (or either) operations in one shot avoiding network roundtrips using a concise and simplified API.
To start with, this example groups all the accounts by state, and then returns the top 10 (default) states sorted by count descending (also default):
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"size": 0,
"aggs": {
"group_by_state": {
"terms": {
"field": "state.keyword"
2014-04-18 13:51:59 -04:00
}
}
}
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
In SQL, the above aggregation is similar in concept to:
[source,sh]
--------------------------------------------------
SELECT state, COUNT(*) FROM bank GROUP BY state ORDER BY COUNT(*) DESC LIMIT 10;
2014-04-18 13:51:59 -04:00
--------------------------------------------------
And the response (partially shown):
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
{
"took": 29,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
Add a shard filter search phase to pre-filter shards based on query rewriting (#25658) Today if we search across a large amount of shards we hit every shard. Yet, it's quite common to search across an index pattern for time based indices but filtering will exclude all results outside a certain time range ie. `now-3d`. While the search can potentially hit hundreds of shards the majority of the shards might yield 0 results since there is not document that is within this date range. Kibana for instance does this regularly but used `_field_stats` to optimize the indexes they need to query. Now with the deprecation of `_field_stats` and it's upcoming removal a single dashboard in kibana can potentially turn into searches hitting hundreds or thousands of shards and that can easily cause search rejections even though the most of the requests are very likely super cheap and only need a query rewriting to early terminate with 0 results. This change adds a pre-filter phase for searches that can, if the number of shards are higher than a the `pre_filter_shard_size` threshold (defaults to 128 shards), fan out to the shards and check if the query can potentially match any documents at all. While false positives are possible, a negative response means that no matches are possible. These requests are not subject to rejection and can greatly reduce the number of shards a request needs to hit. The approach here is preferable to the kibana approach with field stats since it correctly handles aliases and uses the correct threadpools to execute these requests. Further it's completely transparent to the user and improves scalability of elasticsearch in general on large clusters.
2017-07-12 16:19:20 -04:00
"skipped" : 0,
"failed": 0
},
2014-04-18 13:51:59 -04:00
"hits" : {
"total" : {
"value": 1000,
"relation": "eq"
},
"max_score" : null,
2014-04-18 13:51:59 -04:00
"hits" : [ ]
},
"aggregations" : {
"group_by_state" : {
"doc_count_error_upper_bound": 20,
"sum_other_doc_count": 770,
2014-04-18 13:51:59 -04:00
"buckets" : [ {
"key" : "ID",
"doc_count" : 27
2014-04-18 13:51:59 -04:00
}, {
"key" : "TX",
"doc_count" : 27
2014-04-18 13:51:59 -04:00
}, {
"key" : "AL",
"doc_count" : 25
2014-04-18 13:51:59 -04:00
}, {
"key" : "MD",
"doc_count" : 25
2014-04-18 13:51:59 -04:00
}, {
"key" : "TN",
"doc_count" : 23
2014-04-18 13:51:59 -04:00
}, {
"key" : "MA",
"doc_count" : 21
2014-04-18 13:51:59 -04:00
}, {
"key" : "NC",
"doc_count" : 21
2014-04-18 13:51:59 -04:00
}, {
"key" : "ND",
"doc_count" : 21
2014-04-18 13:51:59 -04:00
}, {
"key" : "ME",
"doc_count" : 20
2014-04-18 13:51:59 -04:00
}, {
"key" : "MO",
"doc_count" : 20
2014-04-18 13:51:59 -04:00
} ]
}
}
}
--------------------------------------------------
// TESTRESPONSE[s/"took": 29/"took": $body.took/]
2014-04-18 13:51:59 -04:00
We can see that there are 27 accounts in `ID` (Idaho), followed by 27 accounts
in `TX` (Texas), followed by 25 accounts in `AL` (Alabama), and so forth.
2014-04-18 13:51:59 -04:00
Note that we set `size=0` to not show search hits because we only want to see the aggregation results in the response.
Building on the previous aggregation, this example calculates the average account balance by state (again only for the top 10 states sorted by count in descending order):
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"size": 0,
"aggs": {
"group_by_state": {
"terms": {
"field": "state.keyword"
2014-04-18 13:51:59 -04:00
},
"aggs": {
"average_balance": {
"avg": {
"field": "balance"
}
}
}
}
}
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
Notice how we nested the `average_balance` aggregation inside the `group_by_state` aggregation. This is a common pattern for all the aggregations. You can nest aggregations inside aggregations arbitrarily to extract pivoted summarizations that you require from your data.
Building on the previous aggregation, let's now sort on the average balance in descending order:
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"size": 0,
"aggs": {
"group_by_state": {
"terms": {
"field": "state.keyword",
2014-04-18 13:51:59 -04:00
"order": {
"average_balance": "desc"
}
},
"aggs": {
"average_balance": {
"avg": {
"field": "balance"
}
}
}
}
}
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
This example demonstrates how we can group by age brackets (ages 20-29, 30-39, and 40-49), then by gender, and then finally get the average account balance, per age bracket, per gender:
2014-04-18 13:51:59 -04:00
[source,js]
2014-04-18 13:51:59 -04:00
--------------------------------------------------
GET /bank/_search
2014-04-18 13:51:59 -04:00
{
"size": 0,
"aggs": {
"group_by_age": {
"range": {
"field": "age",
"ranges": [
{
"from": 20,
"to": 30
},
{
"from": 30,
"to": 40
},
{
"from": 40,
"to": 50
}
]
},
"aggs": {
"group_by_gender": {
"terms": {
"field": "gender.keyword"
2014-04-18 13:51:59 -04:00
},
"aggs": {
"average_balance": {
"avg": {
"field": "balance"
}
}
}
}
}
}
}
}
2014-04-18 13:51:59 -04:00
--------------------------------------------------
// CONSOLE
// TEST[continued]
2014-04-18 13:51:59 -04:00
There are many other aggregations capabilities that we won't go into detail here. The {ref}/search-aggregations.html[aggregations reference guide] is a great starting point if you want to do further experimentation.
2014-04-18 13:51:59 -04:00
2018-12-06 13:14:37 -05:00
[[getting-started-conclusion]]
2014-04-18 13:51:59 -04:00
== Conclusion
Elasticsearch is both a simple and complex product. We've so far learned the basics of what it is, how to look inside of it, and how to work with it using some of the REST APIs. Hopefully this tutorial has given you a better understanding of what Elasticsearch is and more importantly, inspired you to further experiment with the rest of its great features!