getting-started.asciidoc 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252
  1. [[getting-started]]
  2. = Getting started with {es}
  3. [partintro]
  4. --
  5. Ready to take {es} for a test drive and see for yourself how you can use the
  6. REST APIs to store, search, and analyze data?
  7. Follow this getting started tutorial to:
  8. . Get an {es} cluster up and running
  9. . Index some sample documents
  10. . Search for documents using the {es} query language
  11. . Analyze the results using bucket and metrics aggregations
  12. Need more context?
  13. Check out the <<elasticsearch-intro,
  14. Elasticsearch Introduction>> to learn the lingo and understand the basics of
  15. how {es} works. If you're already familiar with {es} and want to see how it works
  16. with the rest of the stack, you might want to jump to the
  17. {stack-gs}/get-started-elastic-stack.html[Elastic Stack
  18. Tutorial] to see how to set up a system monitoring solution with {es}, {kib},
  19. {beats}, and {ls}.
  20. TIP: The fastest way to get started with {es} is to
  21. https://www.elastic.co/cloud/elasticsearch-service/signup[start a free 14-day
  22. trial of Elasticsearch Service] in the cloud.
  23. --
  24. [[getting-started-install]]
  25. == Get {es} up and running
  26. To take {es} for a test drive, you can create a one-click cloud deployment
  27. on the https://www.elastic.co/cloud/elasticsearch-service/signup[Elasticsearch Service],
  28. or <<run-elasticsearch-local, set up a multi-node {es} cluster>> on your own
  29. Linux, macOS, or Windows machine.
  30. [float]
  31. [[run-elasticsearch-local]]
  32. === Run {es} locally on Linux, macOS, or Windows
  33. When you create a cluster on the Elasticsearch Service, you automatically
  34. get a three-node cluster. By installing from the tar or zip archive, you can
  35. start multiple instances of {es} locally to see how a multi-node cluster behaves.
  36. To run a three-node {es} cluster locally:
  37. . Download the Elasticsearch archive for your OS:
  38. +
  39. Linux: https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-{version}-linux-x86_64.tar.gz[elasticsearch-{version}-linux-x86_64.tar.gz]
  40. +
  41. ["source","sh",subs="attributes,callouts"]
  42. --------------------------------------------------
  43. curl -L -O https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-{version}-linux-x86_64.tar.gz
  44. --------------------------------------------------
  45. // NOTCONSOLE
  46. +
  47. macOS: https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-{version}-darwin-x86_64.tar.gz[elasticsearch-{version}-darwin-x86_64.tar.gz]
  48. +
  49. ["source","sh",subs="attributes,callouts"]
  50. --------------------------------------------------
  51. curl -L -O https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-{version}-darwin-x86_64.tar.gz
  52. --------------------------------------------------
  53. // NOTCONSOLE
  54. +
  55. Windows:
  56. https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-{version}-windows-x86_64.zip[elasticsearch-{version}-windows-x86_64.zip]
  57. . Extract the archive:
  58. +
  59. Linux:
  60. +
  61. ["source","sh",subs="attributes,callouts"]
  62. --------------------------------------------------
  63. tar -xvf elasticsearch-{version}-linux-x86_64.tar.gz
  64. --------------------------------------------------
  65. +
  66. macOS:
  67. +
  68. ["source","sh",subs="attributes,callouts"]
  69. --------------------------------------------------
  70. tar -xvf elasticsearch-{version}-darwin-x86_64.tar.gz
  71. --------------------------------------------------
  72. +
  73. Windows PowerShell:
  74. +
  75. ["source","sh",subs="attributes,callouts"]
  76. --------------------------------------------------
  77. Expand-Archive elasticsearch-{version}-windows-x86_64.zip
  78. --------------------------------------------------
  79. . Start elasticsearch from the `bin` directory:
  80. +
  81. Linux and macOS:
  82. +
  83. ["source","sh",subs="attributes,callouts"]
  84. --------------------------------------------------
  85. cd elasticsearch-{version}/bin
  86. ./elasticsearch
  87. --------------------------------------------------
  88. +
  89. Windows:
  90. +
  91. ["source","sh",subs="attributes,callouts"]
  92. --------------------------------------------------
  93. cd %PROGRAMFILES%\Elastic\Elasticsearch\bin
  94. .\elasticsearch.exe
  95. --------------------------------------------------
  96. +
  97. You now have a single-node {es} cluster up and running!
  98. . Start two more instances of {es} so you can see how a typical multi-node
  99. cluster behaves. You need to specify unique data and log paths
  100. for each node.
  101. +
  102. Linux and macOS:
  103. +
  104. ["source","sh",subs="attributes,callouts"]
  105. --------------------------------------------------
  106. ./elasticsearch -Epath.data=data2 -Epath.logs=log2
  107. ./elasticsearch -Epath.data=data3 -Epath.logs=log3
  108. --------------------------------------------------
  109. +
  110. Windows:
  111. +
  112. ["source","sh",subs="attributes,callouts"]
  113. --------------------------------------------------
  114. .\elasticsearch.exe -Epath.data=data2 -Epath.logs=log2
  115. .\elasticsearch.exe -Epath.data=data3 -Epath.logs=log3
  116. --------------------------------------------------
  117. +
  118. The additional nodes are assigned unique IDs. Because you're running all three
  119. nodes locally, they automatically join the cluster with the first node.
  120. . Use the `cat health` API to verify that your three-node cluster is up running.
  121. The `cat` APIs return information about your cluster and indices in a
  122. format that's easier to read than raw JSON.
  123. +
  124. You can interact directly with your cluster by submitting HTTP requests to
  125. the {es} REST API. Most of the examples in this guide enable you to copy the
  126. appropriate cURL command and submit the request to your local {es} instance from
  127. the command line. If you have Kibana installed and running, you can also
  128. open Kibana and submit requests through the Dev Console.
  129. +
  130. TIP: You'll want to check out the
  131. https://www.elastic.co/guide/en/elasticsearch/client/index.html[{es} language
  132. clients] when you're ready to start using {es} in your own applications.
  133. +
  134. [source,js]
  135. --------------------------------------------------
  136. GET /_cat/health?v
  137. --------------------------------------------------
  138. // CONSOLE
  139. +
  140. The response should indicate that the status of the _elasticsearch_ cluster
  141. is _green_ and it has three nodes:
  142. +
  143. [source,txt]
  144. --------------------------------------------------
  145. epoch timestamp cluster status node.total node.data shards pri relo init unassign pending_tasks max_task_wait_time active_shards_percent
  146. 1565052807 00:53:27 elasticsearch green 3 3 6 3 0 0 0 0 - 100.0%
  147. --------------------------------------------------
  148. // TESTRESPONSE[s/1565052807 00:53:27 elasticsearch/\\d+ \\d+:\\d+:\\d+ integTest/]
  149. // TESTRESPONSE[s/3 3 6 3/\\d+ \\d+ \\d+ \\d+/]
  150. // TESTRESPONSE[s/0 0 -/0 \\d+ -/]
  151. // TESTRESPONSE[non_json]
  152. +
  153. NOTE: The cluster status will remain yellow if you are only running a single
  154. instance of {es}. A single node cluster is fully functional, but data
  155. cannot be replicated to another node to provide resiliency. Replica shards must
  156. be available for the cluster status to be green. If the cluster status is red,
  157. some data is unavailable.
  158. [float]
  159. [[gs-other-install]]
  160. === Other installation options
  161. Installing {es} from an archive file enables you to easily install and run
  162. multiple instances locally so you can try things out. To run a single instance,
  163. you can run {es} in a Docker container, install {es} using the DEB or RPM
  164. packages on Linux, install using Homebrew on macOS, or install using the MSI
  165. package installer on Windows. See <<install-elasticsearch>> for more information.
  166. [[getting-started-explore]]
  167. == Exploring Your Cluster
  168. [float]
  169. === The REST API
  170. 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:
  171. * Check your cluster, node, and index health, status, and statistics
  172. * Administer your cluster, node, and index data and metadata
  173. * Perform CRUD (Create, Read, Update, and Delete) and search operations against your indexes
  174. * Execute advanced search operations such as paging, sorting, filtering, scripting, aggregations, and many others
  175. [[getting-started-cluster-health]]
  176. === Cluster Health
  177. 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.
  178. To check the cluster health, we will be using the {ref}/cat.html[`_cat` API]. You can
  179. run the command below in {kibana-ref}/console-kibana.html[Kibana's Console]
  180. by clicking "VIEW IN CONSOLE" or with `curl` by clicking the "COPY AS CURL"
  181. link below and pasting it into a terminal.
  182. [source,js]
  183. --------------------------------------------------
  184. GET /_cat/health?v
  185. --------------------------------------------------
  186. // CONSOLE
  187. And the response:
  188. [source,txt]
  189. --------------------------------------------------
  190. epoch timestamp cluster status node.total node.data shards pri relo init unassign pending_tasks max_task_wait_time active_shards_percent
  191. 1475247709 17:01:49 elasticsearch green 1 1 0 0 0 0 0 0 - 100.0%
  192. --------------------------------------------------
  193. // TESTRESPONSE[s/1475247709 17:01:49 elasticsearch/\\d+ \\d+:\\d+:\\d+ integTest/]
  194. // TESTRESPONSE[s/0 0 -/0 \\d+ -/]
  195. // TESTRESPONSE[non_json]
  196. We can see that our cluster named "elasticsearch" is up with a green status.
  197. Whenever we ask for the cluster health, we either get green, yellow, or red.
  198. * Green - everything is good (cluster is fully functional)
  199. * Yellow - all data is available but some replicas are not yet allocated (cluster is fully functional)
  200. * Red - some data is not available for whatever reason (cluster is partially functional)
  201. **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.
  202. 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.
  203. We can also get a list of nodes in our cluster as follows:
  204. [source,js]
  205. --------------------------------------------------
  206. GET /_cat/nodes?v
  207. --------------------------------------------------
  208. // CONSOLE
  209. And the response:
  210. [source,txt]
  211. --------------------------------------------------
  212. ip heap.percent ram.percent cpu load_1m load_5m load_15m node.role master name
  213. 127.0.0.1 10 5 5 4.46 dim * PB2SGZY
  214. --------------------------------------------------
  215. // TESTRESPONSE[s/10 5 5 4.46/\\d+ \\d+ \\d+ (\\d+\\.\\d+)? (\\d+\\.\\d+)? (\\d+\.\\d+)?/]
  216. // TESTRESPONSE[s/dim/.+/ s/[*]/[*]/ s/PB2SGZY/.+/ non_json]
  217. Here, we can see our one node named "PB2SGZY", which is the single node that is currently in our cluster.
  218. [[getting-started-list-indices]]
  219. === List All Indices
  220. Now let's take a peek at our indices:
  221. [source,js]
  222. --------------------------------------------------
  223. GET /_cat/indices?v
  224. --------------------------------------------------
  225. // CONSOLE
  226. And the response:
  227. [source,txt]
  228. --------------------------------------------------
  229. health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
  230. --------------------------------------------------
  231. // TESTRESPONSE[non_json]
  232. Which simply means we have no indices yet in the cluster.
  233. [[getting-started-create-index]]
  234. === Create an Index
  235. Now let's create an index named "customer" and then list all the indexes again:
  236. [source,js]
  237. --------------------------------------------------
  238. PUT /customer?pretty
  239. GET /_cat/indices?v
  240. --------------------------------------------------
  241. // CONSOLE
  242. 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).
  243. And the response:
  244. [source,txt]
  245. --------------------------------------------------
  246. health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
  247. yellow open customer 95SQ4TSUT7mWBT7VNHH67A 1 1 0 0 260b 260b
  248. --------------------------------------------------
  249. // TESTRESPONSE[s/95SQ4TSUT7mWBT7VNHH67A/.+/ s/260b/\\d+\\.?\\d?k?b/ non_json]
  250. 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.
  251. 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.
  252. [[getting-started-query-document]]
  253. === Index and Query a Document
  254. 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:
  255. [source,js]
  256. --------------------------------------------------
  257. PUT /customer/_doc/1?pretty
  258. {
  259. "name": "John Doe"
  260. }
  261. --------------------------------------------------
  262. // CONSOLE
  263. And the response:
  264. [source,js]
  265. --------------------------------------------------
  266. {
  267. "_index" : "customer",
  268. "_type" : "_doc",
  269. "_id" : "1",
  270. "_version" : 1,
  271. "result" : "created",
  272. "_shards" : {
  273. "total" : 2,
  274. "successful" : 1,
  275. "failed" : 0
  276. },
  277. "_seq_no" : 0,
  278. "_primary_term" : 1
  279. }
  280. --------------------------------------------------
  281. // TESTRESPONSE[s/"_seq_no" : \d+/"_seq_no" : $body._seq_no/ s/"_primary_term" : 1/"_primary_term" : $body._primary_term/]
  282. 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.
  283. 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.
  284. Let's now retrieve that document that we just indexed:
  285. [source,js]
  286. --------------------------------------------------
  287. GET /customer/_doc/1?pretty
  288. --------------------------------------------------
  289. // CONSOLE
  290. // TEST[continued]
  291. And the response:
  292. [source,js]
  293. --------------------------------------------------
  294. {
  295. "_index" : "customer",
  296. "_type" : "_doc",
  297. "_id" : "1",
  298. "_version" : 1,
  299. "_seq_no" : 25,
  300. "_primary_term" : 1,
  301. "found" : true,
  302. "_source" : { "name": "John Doe" }
  303. }
  304. --------------------------------------------------
  305. // TESTRESPONSE[s/"_seq_no" : \d+/"_seq_no" : $body._seq_no/ s/"_primary_term" : 1/"_primary_term" : $body._primary_term/]
  306. 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.
  307. [[getting-started-delete-index]]
  308. === Delete an Index
  309. Now let's delete the index that we just created and then list all the indexes again:
  310. [source,js]
  311. --------------------------------------------------
  312. DELETE /customer?pretty
  313. GET /_cat/indices?v
  314. --------------------------------------------------
  315. // CONSOLE
  316. // TEST[continued]
  317. And the response:
  318. [source,txt]
  319. --------------------------------------------------
  320. health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
  321. --------------------------------------------------
  322. // TESTRESPONSE[non_json]
  323. Which means that the index was deleted successfully and we are now back to where we started with nothing in our cluster.
  324. Before we move on, let's take a closer look again at some of the API commands that we have learned so far:
  325. [source,js]
  326. --------------------------------------------------
  327. PUT /customer
  328. PUT /customer/_doc/1
  329. {
  330. "name": "John Doe"
  331. }
  332. GET /customer/_doc/1
  333. DELETE /customer
  334. --------------------------------------------------
  335. // CONSOLE
  336. 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:
  337. [source,js]
  338. --------------------------------------------------
  339. <HTTP Verb> /<Index>/<Endpoint>/<ID>
  340. --------------------------------------------------
  341. // NOTCONSOLE
  342. 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.
  343. [[getting-started-modify-data]]
  344. == Modifying Your Data
  345. 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.
  346. [float]
  347. [[indexing-replacing-documents]]
  348. === Indexing/Replacing Documents
  349. We've previously seen how we can index a single document. Let's recall that command again:
  350. [source,js]
  351. --------------------------------------------------
  352. PUT /customer/_doc/1?pretty
  353. {
  354. "name": "John Doe"
  355. }
  356. --------------------------------------------------
  357. // CONSOLE
  358. 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:
  359. [source,js]
  360. --------------------------------------------------
  361. PUT /customer/_doc/1?pretty
  362. {
  363. "name": "Jane Doe"
  364. }
  365. --------------------------------------------------
  366. // CONSOLE
  367. // TEST[continued]
  368. 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.
  369. [source,js]
  370. --------------------------------------------------
  371. PUT /customer/_doc/2?pretty
  372. {
  373. "name": "Jane Doe"
  374. }
  375. --------------------------------------------------
  376. // CONSOLE
  377. // TEST[continued]
  378. The above indexes a new document with an ID of 2.
  379. 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.
  380. This example shows how to index a document without an explicit ID:
  381. [source,js]
  382. --------------------------------------------------
  383. POST /customer/_doc?pretty
  384. {
  385. "name": "Jane Doe"
  386. }
  387. --------------------------------------------------
  388. // CONSOLE
  389. // TEST[continued]
  390. Note that in the above case, we are using the `POST` verb instead of PUT since we didn't specify an ID.
  391. [[getting-started-update-documents]]
  392. === Updating Documents
  393. 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.
  394. This example shows how to update our previous document (ID of 1) by changing the name field to "Jane Doe":
  395. [source,js]
  396. --------------------------------------------------
  397. POST /customer/_update/1?pretty
  398. {
  399. "doc": { "name": "Jane Doe" }
  400. }
  401. --------------------------------------------------
  402. // CONSOLE
  403. // TEST[continued]
  404. 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:
  405. [source,js]
  406. --------------------------------------------------
  407. POST /customer/_update/1?pretty
  408. {
  409. "doc": { "name": "Jane Doe", "age": 20 }
  410. }
  411. --------------------------------------------------
  412. // CONSOLE
  413. // TEST[continued]
  414. Updates can also be performed by using simple scripts. This example uses a script to increment the age by 5:
  415. [source,js]
  416. --------------------------------------------------
  417. POST /customer/_update/1?pretty
  418. {
  419. "script" : "ctx._source.age += 5"
  420. }
  421. --------------------------------------------------
  422. // CONSOLE
  423. // TEST[continued]
  424. In the above example, `ctx._source` refers to the current source document that is about to be updated.
  425. 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]
  426. [[getting-started-delete-documents]]
  427. === Deleting Documents
  428. Deleting a document is fairly straightforward. This example shows how to delete our previous customer with the ID of 2:
  429. [source,js]
  430. --------------------------------------------------
  431. DELETE /customer/_doc/2?pretty
  432. --------------------------------------------------
  433. // CONSOLE
  434. // TEST[continued]
  435. See the {ref}/docs-delete-by-query.html[`_delete_by_query` API] to delete all documents matching a specific query.
  436. It is worth noting that it is much more efficient to delete a whole index
  437. instead of deleting all documents with the Delete By Query API.
  438. [[getting-started-batch-processing]]
  439. === Batch Processing
  440. 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.
  441. As a quick example, the following call indexes two documents (ID 1 - John Doe and ID 2 - Jane Doe) in one bulk operation:
  442. [source,js]
  443. --------------------------------------------------
  444. POST /customer/_bulk?pretty
  445. {"index":{"_id":"1"}}
  446. {"name": "John Doe" }
  447. {"index":{"_id":"2"}}
  448. {"name": "Jane Doe" }
  449. --------------------------------------------------
  450. // CONSOLE
  451. This example updates the first document (ID of 1) and then deletes the second document (ID of 2) in one bulk operation:
  452. [source,sh]
  453. --------------------------------------------------
  454. POST /customer/_bulk?pretty
  455. {"update":{"_id":"1"}}
  456. {"doc": { "name": "John Doe becomes Jane Doe" } }
  457. {"delete":{"_id":"2"}}
  458. --------------------------------------------------
  459. // CONSOLE
  460. // TEST[continued]
  461. 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.
  462. 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.
  463. [[getting-started-explore-data]]
  464. == Exploring Your Data
  465. [float]
  466. === Sample Dataset
  467. 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:
  468. [source,js]
  469. --------------------------------------------------
  470. {
  471. "account_number": 0,
  472. "balance": 16623,
  473. "firstname": "Bradshaw",
  474. "lastname": "Mckenzie",
  475. "age": 29,
  476. "gender": "F",
  477. "address": "244 Columbus Place",
  478. "employer": "Euron",
  479. "email": "bradshawmckenzie@euron.com",
  480. "city": "Hobucken",
  481. "state": "CO"
  482. }
  483. --------------------------------------------------
  484. // NOTCONSOLE
  485. 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.
  486. [float]
  487. === Loading the Sample Dataset
  488. 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:
  489. [source,sh]
  490. --------------------------------------------------
  491. curl -H "Content-Type: application/json" -XPOST "localhost:9200/bank/_bulk?pretty&refresh" --data-binary "@accounts.json"
  492. curl "localhost:9200/_cat/indices?v"
  493. --------------------------------------------------
  494. // NOTCONSOLE
  495. ////
  496. This replicates the above in a document-testing friendly way but isn't visible
  497. in the docs:
  498. [source,js]
  499. --------------------------------------------------
  500. GET /_cat/indices?v
  501. --------------------------------------------------
  502. // CONSOLE
  503. // TEST[setup:bank]
  504. ////
  505. And the response:
  506. [source,txt]
  507. --------------------------------------------------
  508. health status index uuid pri rep docs.count docs.deleted store.size pri.store.size
  509. yellow open bank l7sSYV2cQXmu6_4rJWVIww 5 1 1000 0 128.6kb 128.6kb
  510. --------------------------------------------------
  511. // TESTRESPONSE[s/128.6kb/\\d+(\\.\\d+)?[mk]?b/]
  512. // TESTRESPONSE[s/l7sSYV2cQXmu6_4rJWVIww/.+/ non_json]
  513. Which means that we just successfully bulk indexed 1000 documents into the bank index.
  514. [[getting-started-search-API]]
  515. === The Search API
  516. 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.
  517. The REST API for search is accessible from the `_search` endpoint. This example returns all documents in the bank index:
  518. [source,js]
  519. --------------------------------------------------
  520. GET /bank/_search?q=*&sort=account_number:asc&pretty
  521. --------------------------------------------------
  522. // CONSOLE
  523. // TEST[continued]
  524. 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.
  525. And the response (partially shown):
  526. [source,js]
  527. --------------------------------------------------
  528. {
  529. "took" : 63,
  530. "timed_out" : false,
  531. "_shards" : {
  532. "total" : 5,
  533. "successful" : 5,
  534. "skipped" : 0,
  535. "failed" : 0
  536. },
  537. "hits" : {
  538. "total" : {
  539. "value": 1000,
  540. "relation": "eq"
  541. },
  542. "max_score" : null,
  543. "hits" : [ {
  544. "_index" : "bank",
  545. "_type" : "_doc",
  546. "_id" : "0",
  547. "sort": [0],
  548. "_score" : null,
  549. "_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"}
  550. }, {
  551. "_index" : "bank",
  552. "_type" : "_doc",
  553. "_id" : "1",
  554. "sort": [1],
  555. "_score" : null,
  556. "_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"}
  557. }, ...
  558. ]
  559. }
  560. }
  561. --------------------------------------------------
  562. // TESTRESPONSE[s/"took" : 63/"took" : $body.took/]
  563. // 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/]
  564. As for the response, we see the following parts:
  565. * `took` – time in milliseconds for Elasticsearch to execute the search
  566. * `timed_out` – tells us if the search timed out or not
  567. * `_shards` – tells us how many shards were searched, as well as a count of the successful/failed searched shards
  568. * `hits` – search results
  569. * `hits.total` – an object that contains information about the total number of documents matching our search criteria
  570. ** `hits.total.value` - the value of the total hit count (must be interpreted in the context of `hits.total.relation`).
  571. ** `hits.total.relation` - whether `hits.total.value` is the exact hit count, in which case it is equal to `"eq"` or a
  572. lower bound of the total hit count (greater than or equals), in which case it is equal to `gte`.
  573. * `hits.hits` – actual array of search results (defaults to first 10 documents)
  574. * `hits.sort` - sort value of the sort key for each result (missing if sorting by score)
  575. * `hits._score` and `max_score` - ignore these fields for now
  576. The accuracy of `hits.total` is controlled by the request parameter `track_total_hits`, when set to true
  577. the request will track the total hits accurately (`"relation": "eq"`). It defaults to `10,000`
  578. which means that the total hit count is accurately tracked up to `10,000` documents.
  579. You can force an accurate count by setting `track_total_hits` to true explicitly.
  580. See the <<request-body-search-track-total-hits, request body>> documentation
  581. for more details.
  582. Here is the same exact search above using the alternative request body method:
  583. [source,js]
  584. --------------------------------------------------
  585. GET /bank/_search
  586. {
  587. "query": { "match_all": {} },
  588. "sort": [
  589. { "account_number": "asc" }
  590. ]
  591. }
  592. --------------------------------------------------
  593. // CONSOLE
  594. // TEST[continued]
  595. 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.
  596. ////
  597. Hidden response just so we can assert that it is indeed the same but don't have
  598. to clutter the docs with it:
  599. [source,js]
  600. --------------------------------------------------
  601. {
  602. "took" : 63,
  603. "timed_out" : false,
  604. "_shards" : {
  605. "total" : 5,
  606. "successful" : 5,
  607. "skipped" : 0,
  608. "failed" : 0
  609. },
  610. "hits" : {
  611. "total" : {
  612. "value": 1000,
  613. "relation": "eq"
  614. },
  615. "max_score": null,
  616. "hits" : [ {
  617. "_index" : "bank",
  618. "_type" : "_doc",
  619. "_id" : "0",
  620. "sort": [0],
  621. "_score": null,
  622. "_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"}
  623. }, {
  624. "_index" : "bank",
  625. "_type" : "_doc",
  626. "_id" : "1",
  627. "sort": [1],
  628. "_score": null,
  629. "_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"}
  630. }, ...
  631. ]
  632. }
  633. }
  634. --------------------------------------------------
  635. // TESTRESPONSE[s/"took" : 63/"took" : $body.took/]
  636. // 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/]
  637. ////
  638. 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.
  639. [[getting-started-query-lang]]
  640. === Introducing the Query Language
  641. 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.
  642. Going back to our last example, we executed this query:
  643. [source,js]
  644. --------------------------------------------------
  645. GET /bank/_search
  646. {
  647. "query": { "match_all": {} }
  648. }
  649. --------------------------------------------------
  650. // CONSOLE
  651. // TEST[continued]
  652. 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.
  653. In addition to the `query` parameter, we also can pass other parameters to
  654. influence the search results. In the example in the section above we passed in
  655. `sort`, here we pass in `size`:
  656. [source,js]
  657. --------------------------------------------------
  658. GET /bank/_search
  659. {
  660. "query": { "match_all": {} },
  661. "size": 1
  662. }
  663. --------------------------------------------------
  664. // CONSOLE
  665. // TEST[continued]
  666. Note that if `size` is not specified, it defaults to 10.
  667. This example does a `match_all` and returns documents 10 through 19:
  668. [source,js]
  669. --------------------------------------------------
  670. GET /bank/_search
  671. {
  672. "query": { "match_all": {} },
  673. "from": 10,
  674. "size": 10
  675. }
  676. --------------------------------------------------
  677. // CONSOLE
  678. // TEST[continued]
  679. 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.
  680. This example does a `match_all` and sorts the results by account balance in descending order and returns the top 10 (default size) documents.
  681. [source,js]
  682. --------------------------------------------------
  683. GET /bank/_search
  684. {
  685. "query": { "match_all": {} },
  686. "sort": { "balance": { "order": "desc" } }
  687. }
  688. --------------------------------------------------
  689. // CONSOLE
  690. // TEST[continued]
  691. [[getting-started-search]]
  692. === Executing Searches
  693. 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.
  694. This example shows how to return two fields, `account_number` and `balance` (inside of `_source`), from the search:
  695. [source,js]
  696. --------------------------------------------------
  697. GET /bank/_search
  698. {
  699. "query": { "match_all": {} },
  700. "_source": ["account_number", "balance"]
  701. }
  702. --------------------------------------------------
  703. // CONSOLE
  704. // TEST[continued]
  705. 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.
  706. If you come from a SQL background, the above is somewhat similar in concept to the `SQL SELECT FROM` field list.
  707. 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).
  708. This example returns the account numbered 20:
  709. [source,js]
  710. --------------------------------------------------
  711. GET /bank/_search
  712. {
  713. "query": { "match": { "account_number": 20 } }
  714. }
  715. --------------------------------------------------
  716. // CONSOLE
  717. // TEST[continued]
  718. This example returns all accounts containing the term "mill" in the address:
  719. [source,js]
  720. --------------------------------------------------
  721. GET /bank/_search
  722. {
  723. "query": { "match": { "address": "mill" } }
  724. }
  725. --------------------------------------------------
  726. // CONSOLE
  727. // TEST[continued]
  728. This example returns all accounts containing the term "mill" or "lane" in the address:
  729. [source,js]
  730. --------------------------------------------------
  731. GET /bank/_search
  732. {
  733. "query": { "match": { "address": "mill lane" } }
  734. }
  735. --------------------------------------------------
  736. // CONSOLE
  737. // TEST[continued]
  738. This example is a variant of `match` (`match_phrase`) that returns all accounts containing the phrase "mill lane" in the address:
  739. [source,js]
  740. --------------------------------------------------
  741. GET /bank/_search
  742. {
  743. "query": { "match_phrase": { "address": "mill lane" } }
  744. }
  745. --------------------------------------------------
  746. // CONSOLE
  747. // TEST[continued]
  748. 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.
  749. This example composes two `match` queries and returns all accounts containing "mill" and "lane" in the address:
  750. [source,js]
  751. --------------------------------------------------
  752. GET /bank/_search
  753. {
  754. "query": {
  755. "bool": {
  756. "must": [
  757. { "match": { "address": "mill" } },
  758. { "match": { "address": "lane" } }
  759. ]
  760. }
  761. }
  762. }
  763. --------------------------------------------------
  764. // CONSOLE
  765. // TEST[continued]
  766. In the above example, the `bool must` clause specifies all the queries that must be true for a document to be considered a match.
  767. In contrast, this example composes two `match` queries and returns all accounts containing "mill" or "lane" in the address:
  768. [source,js]
  769. --------------------------------------------------
  770. GET /bank/_search
  771. {
  772. "query": {
  773. "bool": {
  774. "should": [
  775. { "match": { "address": "mill" } },
  776. { "match": { "address": "lane" } }
  777. ]
  778. }
  779. }
  780. }
  781. --------------------------------------------------
  782. // CONSOLE
  783. // TEST[continued]
  784. 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.
  785. This example composes two `match` queries and returns all accounts that contain neither "mill" nor "lane" in the address:
  786. [source,js]
  787. --------------------------------------------------
  788. GET /bank/_search
  789. {
  790. "query": {
  791. "bool": {
  792. "must_not": [
  793. { "match": { "address": "mill" } },
  794. { "match": { "address": "lane" } }
  795. ]
  796. }
  797. }
  798. }
  799. --------------------------------------------------
  800. // CONSOLE
  801. // TEST[continued]
  802. 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.
  803. 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.
  804. This example returns all accounts of anybody who is 40 years old but doesn't live in ID(aho):
  805. [source,js]
  806. --------------------------------------------------
  807. GET /bank/_search
  808. {
  809. "query": {
  810. "bool": {
  811. "must": [
  812. { "match": { "age": "40" } }
  813. ],
  814. "must_not": [
  815. { "match": { "state": "ID" } }
  816. ]
  817. }
  818. }
  819. }
  820. --------------------------------------------------
  821. // CONSOLE
  822. // TEST[continued]
  823. [[getting-started-filters]]
  824. === Executing Filters
  825. 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.
  826. 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.
  827. 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.
  828. 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.
  829. [source,js]
  830. --------------------------------------------------
  831. GET /bank/_search
  832. {
  833. "query": {
  834. "bool": {
  835. "must": { "match_all": {} },
  836. "filter": {
  837. "range": {
  838. "balance": {
  839. "gte": 20000,
  840. "lte": 30000
  841. }
  842. }
  843. }
  844. }
  845. }
  846. }
  847. --------------------------------------------------
  848. // CONSOLE
  849. // TEST[continued]
  850. 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.
  851. 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.
  852. [[getting-started-aggregations]]
  853. === Executing Aggregations
  854. 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.
  855. 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):
  856. [source,js]
  857. --------------------------------------------------
  858. GET /bank/_search
  859. {
  860. "size": 0,
  861. "aggs": {
  862. "group_by_state": {
  863. "terms": {
  864. "field": "state.keyword"
  865. }
  866. }
  867. }
  868. }
  869. --------------------------------------------------
  870. // CONSOLE
  871. // TEST[continued]
  872. In SQL, the above aggregation is similar in concept to:
  873. [source,sh]
  874. --------------------------------------------------
  875. SELECT state, COUNT(*) FROM bank GROUP BY state ORDER BY COUNT(*) DESC LIMIT 10;
  876. --------------------------------------------------
  877. And the response (partially shown):
  878. [source,js]
  879. --------------------------------------------------
  880. {
  881. "took": 29,
  882. "timed_out": false,
  883. "_shards": {
  884. "total": 5,
  885. "successful": 5,
  886. "skipped" : 0,
  887. "failed": 0
  888. },
  889. "hits" : {
  890. "total" : {
  891. "value": 1000,
  892. "relation": "eq"
  893. },
  894. "max_score" : null,
  895. "hits" : [ ]
  896. },
  897. "aggregations" : {
  898. "group_by_state" : {
  899. "doc_count_error_upper_bound": 20,
  900. "sum_other_doc_count": 770,
  901. "buckets" : [ {
  902. "key" : "ID",
  903. "doc_count" : 27
  904. }, {
  905. "key" : "TX",
  906. "doc_count" : 27
  907. }, {
  908. "key" : "AL",
  909. "doc_count" : 25
  910. }, {
  911. "key" : "MD",
  912. "doc_count" : 25
  913. }, {
  914. "key" : "TN",
  915. "doc_count" : 23
  916. }, {
  917. "key" : "MA",
  918. "doc_count" : 21
  919. }, {
  920. "key" : "NC",
  921. "doc_count" : 21
  922. }, {
  923. "key" : "ND",
  924. "doc_count" : 21
  925. }, {
  926. "key" : "ME",
  927. "doc_count" : 20
  928. }, {
  929. "key" : "MO",
  930. "doc_count" : 20
  931. } ]
  932. }
  933. }
  934. }
  935. --------------------------------------------------
  936. // TESTRESPONSE[s/"took": 29/"took": $body.took/]
  937. We can see that there are 27 accounts in `ID` (Idaho), followed by 27 accounts
  938. in `TX` (Texas), followed by 25 accounts in `AL` (Alabama), and so forth.
  939. Note that we set `size=0` to not show search hits because we only want to see the aggregation results in the response.
  940. 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):
  941. [source,js]
  942. --------------------------------------------------
  943. GET /bank/_search
  944. {
  945. "size": 0,
  946. "aggs": {
  947. "group_by_state": {
  948. "terms": {
  949. "field": "state.keyword"
  950. },
  951. "aggs": {
  952. "average_balance": {
  953. "avg": {
  954. "field": "balance"
  955. }
  956. }
  957. }
  958. }
  959. }
  960. }
  961. --------------------------------------------------
  962. // CONSOLE
  963. // TEST[continued]
  964. 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.
  965. Building on the previous aggregation, let's now sort on the average balance in descending order:
  966. [source,js]
  967. --------------------------------------------------
  968. GET /bank/_search
  969. {
  970. "size": 0,
  971. "aggs": {
  972. "group_by_state": {
  973. "terms": {
  974. "field": "state.keyword",
  975. "order": {
  976. "average_balance": "desc"
  977. }
  978. },
  979. "aggs": {
  980. "average_balance": {
  981. "avg": {
  982. "field": "balance"
  983. }
  984. }
  985. }
  986. }
  987. }
  988. }
  989. --------------------------------------------------
  990. // CONSOLE
  991. // TEST[continued]
  992. 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:
  993. [source,js]
  994. --------------------------------------------------
  995. GET /bank/_search
  996. {
  997. "size": 0,
  998. "aggs": {
  999. "group_by_age": {
  1000. "range": {
  1001. "field": "age",
  1002. "ranges": [
  1003. {
  1004. "from": 20,
  1005. "to": 30
  1006. },
  1007. {
  1008. "from": 30,
  1009. "to": 40
  1010. },
  1011. {
  1012. "from": 40,
  1013. "to": 50
  1014. }
  1015. ]
  1016. },
  1017. "aggs": {
  1018. "group_by_gender": {
  1019. "terms": {
  1020. "field": "gender.keyword"
  1021. },
  1022. "aggs": {
  1023. "average_balance": {
  1024. "avg": {
  1025. "field": "balance"
  1026. }
  1027. }
  1028. }
  1029. }
  1030. }
  1031. }
  1032. }
  1033. }
  1034. --------------------------------------------------
  1035. // CONSOLE
  1036. // TEST[continued]
  1037. 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.
  1038. [[getting-started-conclusion]]
  1039. == Conclusion
  1040. 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!