search-speed.asciidoc 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536
  1. [[tune-for-search-speed]]
  2. == Tune for search speed
  3. [discrete]
  4. === Give memory to the filesystem cache
  5. Elasticsearch heavily relies on the filesystem cache in order to make search
  6. fast. In general, you should make sure that at least half the available memory
  7. goes to the filesystem cache so that Elasticsearch can keep hot regions of the
  8. index in physical memory.
  9. [discrete]
  10. === Use faster hardware
  11. If your search is I/O bound, you should investigate giving more memory to the
  12. filesystem cache (see above) or buying faster drives. In particular SSD drives
  13. are known to perform better than spinning disks. Always use local storage,
  14. remote filesystems such as `NFS` or `SMB` should be avoided. Also beware of
  15. virtualized storage such as Amazon's `Elastic Block Storage`. Virtualized
  16. storage works very well with Elasticsearch, and it is appealing since it is so
  17. fast and simple to set up, but it is also unfortunately inherently slower on an
  18. ongoing basis when compared to dedicated local storage. If you put an index on
  19. `EBS`, be sure to use provisioned IOPS otherwise operations could be quickly
  20. throttled.
  21. If your search is CPU-bound, you should investigate buying faster CPUs.
  22. [discrete]
  23. === Document modeling
  24. Documents should be modeled so that search-time operations are as cheap as possible.
  25. In particular, joins should be avoided. <<nested,`nested`>> can make queries
  26. several times slower and <<parent-join,parent-child>> relations can make
  27. queries hundreds of times slower. So if the same questions can be answered without
  28. joins by denormalizing documents, significant speedups can be expected.
  29. [discrete]
  30. [[search-as-few-fields-as-possible]]
  31. === Search as few fields as possible
  32. The more fields a <<query-dsl-query-string-query,`query_string`>> or
  33. <<query-dsl-multi-match-query,`multi_match`>> query targets, the slower it is.
  34. A common technique to improve search speed over multiple fields is to copy
  35. their values into a single field at index time, and then use this field at
  36. search time. This can be automated with the <<copy-to,`copy-to`>> directive of
  37. mappings without having to change the source of documents. Here is an example
  38. of an index containing movies that optimizes queries that search over both the
  39. name and the plot of the movie by indexing both values into the `name_and_plot`
  40. field.
  41. [source,console]
  42. --------------------------------------------------
  43. PUT movies
  44. {
  45. "mappings": {
  46. "properties": {
  47. "name_and_plot": {
  48. "type": "text"
  49. },
  50. "name": {
  51. "type": "text",
  52. "copy_to": "name_and_plot"
  53. },
  54. "plot": {
  55. "type": "text",
  56. "copy_to": "name_and_plot"
  57. }
  58. }
  59. }
  60. }
  61. --------------------------------------------------
  62. [discrete]
  63. === Pre-index data
  64. You should leverage patterns in your queries to optimize the way data is indexed.
  65. For instance, if all your documents have a `price` field and most queries run
  66. <<search-aggregations-bucket-range-aggregation,`range`>> aggregations on a fixed
  67. list of ranges, you could make this aggregation faster by pre-indexing the ranges
  68. into the index and using a <<search-aggregations-bucket-terms-aggregation,`terms`>>
  69. aggregations.
  70. For instance, if documents look like:
  71. [source,console]
  72. --------------------------------------------------
  73. PUT index/_doc/1
  74. {
  75. "designation": "spoon",
  76. "price": 13
  77. }
  78. --------------------------------------------------
  79. and search requests look like:
  80. [source,console]
  81. --------------------------------------------------
  82. GET index/_search
  83. {
  84. "aggs": {
  85. "price_ranges": {
  86. "range": {
  87. "field": "price",
  88. "ranges": [
  89. { "to": 10 },
  90. { "from": 10, "to": 100 },
  91. { "from": 100 }
  92. ]
  93. }
  94. }
  95. }
  96. }
  97. --------------------------------------------------
  98. // TEST[continued]
  99. Then documents could be enriched by a `price_range` field at index time, which
  100. should be mapped as a <<keyword,`keyword`>>:
  101. [source,console]
  102. --------------------------------------------------
  103. PUT index
  104. {
  105. "mappings": {
  106. "properties": {
  107. "price_range": {
  108. "type": "keyword"
  109. }
  110. }
  111. }
  112. }
  113. PUT index/_doc/1
  114. {
  115. "designation": "spoon",
  116. "price": 13,
  117. "price_range": "10-100"
  118. }
  119. --------------------------------------------------
  120. And then search requests could aggregate this new field rather than running a
  121. `range` aggregation on the `price` field.
  122. [source,console]
  123. --------------------------------------------------
  124. GET index/_search
  125. {
  126. "aggs": {
  127. "price_ranges": {
  128. "terms": {
  129. "field": "price_range"
  130. }
  131. }
  132. }
  133. }
  134. --------------------------------------------------
  135. // TEST[continued]
  136. [discrete]
  137. [[map-ids-as-keyword]]
  138. === Consider mapping identifiers as `keyword`
  139. include::../mapping/types/numeric.asciidoc[tag=map-ids-as-keyword]
  140. [discrete]
  141. === Avoid scripts
  142. If possible, avoid using <<modules-scripting,script>>-based sorting, scripts in
  143. aggregations, and the <<query-dsl-script-score-query,`script_score`>> query. See
  144. <<scripts-and-search-speed>>.
  145. [discrete]
  146. === Search rounded dates
  147. Queries on date fields that use `now` are typically not cacheable since the
  148. range that is being matched changes all the time. However switching to a
  149. rounded date is often acceptable in terms of user experience, and has the
  150. benefit of making better use of the query cache.
  151. For instance the below query:
  152. [source,console]
  153. --------------------------------------------------
  154. PUT index/_doc/1
  155. {
  156. "my_date": "2016-05-11T16:30:55.328Z"
  157. }
  158. GET index/_search
  159. {
  160. "query": {
  161. "constant_score": {
  162. "filter": {
  163. "range": {
  164. "my_date": {
  165. "gte": "now-1h",
  166. "lte": "now"
  167. }
  168. }
  169. }
  170. }
  171. }
  172. }
  173. --------------------------------------------------
  174. could be replaced with the following query:
  175. [source,console]
  176. --------------------------------------------------
  177. GET index/_search
  178. {
  179. "query": {
  180. "constant_score": {
  181. "filter": {
  182. "range": {
  183. "my_date": {
  184. "gte": "now-1h/m",
  185. "lte": "now/m"
  186. }
  187. }
  188. }
  189. }
  190. }
  191. }
  192. --------------------------------------------------
  193. // TEST[continued]
  194. In that case we rounded to the minute, so if the current time is `16:31:29`,
  195. the range query will match everything whose value of the `my_date` field is
  196. between `15:31:00` and `16:31:59`. And if several users run a query that
  197. contains this range in the same minute, the query cache could help speed things
  198. up a bit. The longer the interval that is used for rounding, the more the query
  199. cache can help, but beware that too aggressive rounding might also hurt user
  200. experience.
  201. NOTE: It might be tempting to split ranges into a large cacheable part and
  202. smaller not cacheable parts in order to be able to leverage the query cache,
  203. as shown below:
  204. [source,console]
  205. --------------------------------------------------
  206. GET index/_search
  207. {
  208. "query": {
  209. "constant_score": {
  210. "filter": {
  211. "bool": {
  212. "should": [
  213. {
  214. "range": {
  215. "my_date": {
  216. "gte": "now-1h",
  217. "lte": "now-1h/m"
  218. }
  219. }
  220. },
  221. {
  222. "range": {
  223. "my_date": {
  224. "gt": "now-1h/m",
  225. "lt": "now/m"
  226. }
  227. }
  228. },
  229. {
  230. "range": {
  231. "my_date": {
  232. "gte": "now/m",
  233. "lte": "now"
  234. }
  235. }
  236. }
  237. ]
  238. }
  239. }
  240. }
  241. }
  242. }
  243. --------------------------------------------------
  244. // TEST[continued]
  245. However such practice might make the query run slower in some cases since the
  246. overhead introduced by the `bool` query may defeat the savings from better
  247. leveraging the query cache.
  248. [discrete]
  249. === Force-merge read-only indices
  250. Indices that are read-only may benefit from being <<indices-forcemerge,merged
  251. down to a single segment>>. This is typically the case with time-based indices:
  252. only the index for the current time frame is getting new documents while older
  253. indices are read-only. Shards that have been force-merged into a single segment
  254. can use simpler and more efficient data structures to perform searches.
  255. IMPORTANT: Do not force-merge indices to which you are still writing, or to
  256. which you will write again in the future. Instead, rely on the automatic
  257. background merge process to perform merges as needed to keep the index running
  258. smoothly. If you continue to write to a force-merged index then its performance
  259. may become much worse.
  260. [discrete]
  261. === Warm up global ordinals
  262. <<eager-global-ordinals,Global ordinals>> are a data structure that is used to
  263. optimize the performance of aggregations. They are calculated lazily and stored in
  264. the JVM heap as part of the <<modules-fielddata, field data cache>>. For fields
  265. that are heavily used for bucketing aggregations, you can tell {es} to construct
  266. and cache the global ordinals before requests are received. This should be done
  267. carefully because it will increase heap usage and can make <<indices-refresh, refreshes>>
  268. take longer. The option can be updated dynamically on an existing mapping by
  269. setting the <<eager-global-ordinals, eager global ordinals>> mapping parameter:
  270. [source,console]
  271. --------------------------------------------------
  272. PUT index
  273. {
  274. "mappings": {
  275. "properties": {
  276. "foo": {
  277. "type": "keyword",
  278. "eager_global_ordinals": true
  279. }
  280. }
  281. }
  282. }
  283. --------------------------------------------------
  284. [discrete]
  285. === Warm up the filesystem cache
  286. If the machine running Elasticsearch is restarted, the filesystem cache will be
  287. empty, so it will take some time before the operating system loads hot regions
  288. of the index into memory so that search operations are fast. You can explicitly
  289. tell the operating system which files should be loaded into memory eagerly
  290. depending on the file extension using the
  291. <<preload-data-to-file-system-cache,`index.store.preload`>> setting.
  292. WARNING: Loading data into the filesystem cache eagerly on too many indices or
  293. too many files will make search _slower_ if the filesystem cache is not large
  294. enough to hold all the data. Use with caution.
  295. [discrete]
  296. === Use index sorting to speed up conjunctions
  297. <<index-modules-index-sorting,Index sorting>> can be useful in order to make
  298. conjunctions faster at the cost of slightly slower indexing. Read more about it
  299. in the <<index-modules-index-sorting-conjunctions,index sorting documentation>>.
  300. [discrete]
  301. [[preference-cache-optimization]]
  302. === Use `preference` to optimize cache utilization
  303. There are multiple caches that can help with search performance, such as the
  304. {wikipedia}/Page_cache[filesystem cache], the
  305. <<shard-request-cache,request cache>> or the <<query-cache,query cache>>. Yet
  306. all these caches are maintained at the node level, meaning that if you run the
  307. same request twice in a row, have 1 <<glossary-replica-shard,replica>> or more
  308. and use {wikipedia}/Round-robin_DNS[round-robin], the default
  309. routing algorithm, then those two requests will go to different shard copies,
  310. preventing node-level caches from helping.
  311. Since it is common for users of a search application to run similar requests
  312. one after another, for instance in order to analyze a narrower subset of the
  313. index, using a preference value that identifies the current user or session
  314. could help optimize usage of the caches.
  315. [discrete]
  316. === Replicas might help with throughput, but not always
  317. In addition to improving resiliency, replicas can help improve throughput. For
  318. instance if you have a single-shard index and three nodes, you will need to
  319. set the number of replicas to 2 in order to have 3 copies of your shard in
  320. total so that all nodes are utilized.
  321. Now imagine that you have a 2-shards index and two nodes. In one case, the
  322. number of replicas is 0, meaning that each node holds a single shard. In the
  323. second case the number of replicas is 1, meaning that each node has two shards.
  324. Which setup is going to perform best in terms of search performance? Usually,
  325. the setup that has fewer shards per node in total will perform better. The
  326. reason for that is that it gives a greater share of the available filesystem
  327. cache to each shard, and the filesystem cache is probably Elasticsearch's
  328. number 1 performance factor. At the same time, beware that a setup that does
  329. not have replicas is subject to failure in case of a single node failure, so
  330. there is a trade-off between throughput and availability.
  331. So what is the right number of replicas? If you have a cluster that has
  332. `num_nodes` nodes, `num_primaries` primary shards _in total_ and if you want to
  333. be able to cope with `max_failures` node failures at once at most, then the
  334. right number of replicas for you is
  335. `max(max_failures, ceil(num_nodes / num_primaries) - 1)`.
  336. === Tune your queries with the Profile API
  337. You can also analyse how expensive each component of your queries and
  338. aggregations are using the {ref}/search-profile.html[Profile API]. This might
  339. allow you to tune your queries to be less expensive, resulting in a positive
  340. performance result and reduced load. Also note that Profile API payloads can be
  341. easily visualised for better readability in the
  342. {kibana-ref}/xpack-profiler.html[Search Profiler], which is a Kibana dev tools
  343. UI available in all X-Pack licenses, including the free X-Pack Basic license.
  344. Some caveats to the Profile API are that:
  345. - the Profile API as a debugging tool adds significant overhead to search execution and can also have a very verbose output
  346. - given the added overhead, the resulting took times are not reliable indicators of actual took time, but can be used comparatively between clauses for relative timing differences
  347. - the Profile API is best for exploring possible reasons behind the most costly clauses of a query but isn't intended for accurately measuring absolute timings of each clause
  348. [[faster-phrase-queries]]
  349. === Faster phrase queries with `index_phrases`
  350. The <<text,`text`>> field has an <<index-phrases,`index_phrases`>> option that
  351. indexes 2-shingles and is automatically leveraged by query parsers to run phrase
  352. queries that don't have a slop. If your use-case involves running lots of phrase
  353. queries, this can speed up queries significantly.
  354. [[faster-prefix-queries]]
  355. === Faster prefix queries with `index_prefixes`
  356. The <<text,`text`>> field has an <<index-prefixes,`index_prefixes`>> option that
  357. indexes prefixes of all terms and is automatically leveraged by query parsers to
  358. run prefix queries. If your use-case involves running lots of prefix queries,
  359. this can speed up queries significantly.
  360. [[faster-filtering-with-constant-keyword]]
  361. === Use `constant_keyword` to speed up filtering
  362. There is a general rule that the cost of a filter is mostly a function of the
  363. number of matched documents. Imagine that you have an index containing cycles.
  364. There are a large number of bicycles and many searches perform a filter on
  365. `cycle_type: bicycle`. This very common filter is unfortunately also very costly
  366. since it matches most documents. There is a simple way to avoid running this
  367. filter: move bicycles to their own index and filter bicycles by searching this
  368. index instead of adding a filter to the query.
  369. Unfortunately this can make client-side logic tricky, which is where
  370. `constant_keyword` helps. By mapping `cycle_type` as a `constant_keyword` with
  371. value `bicycle` on the index that contains bicycles, clients can keep running
  372. the exact same queries as they used to run on the monolithic index and
  373. Elasticsearch will do the right thing on the bicycles index by ignoring filters
  374. on `cycle_type` if the value is `bicycle` and returning no hits otherwise.
  375. Here is what mappings could look like:
  376. [source,console]
  377. --------------------------------------------------
  378. PUT bicycles
  379. {
  380. "mappings": {
  381. "properties": {
  382. "cycle_type": {
  383. "type": "constant_keyword",
  384. "value": "bicycle"
  385. },
  386. "name": {
  387. "type": "text"
  388. }
  389. }
  390. }
  391. }
  392. PUT other_cycles
  393. {
  394. "mappings": {
  395. "properties": {
  396. "cycle_type": {
  397. "type": "keyword"
  398. },
  399. "name": {
  400. "type": "text"
  401. }
  402. }
  403. }
  404. }
  405. --------------------------------------------------
  406. We are splitting our index in two: one that will contain only bicycles, and
  407. another one that contains other cycles: unicycles, tricycles, etc. Then at
  408. search time, we need to search both indices, but we don't need to modify
  409. queries.
  410. [source,console]
  411. --------------------------------------------------
  412. GET bicycles,other_cycles/_search
  413. {
  414. "query": {
  415. "bool": {
  416. "must": {
  417. "match": {
  418. "description": "dutch"
  419. }
  420. },
  421. "filter": {
  422. "term": {
  423. "cycle_type": "bicycle"
  424. }
  425. }
  426. }
  427. }
  428. }
  429. --------------------------------------------------
  430. // TEST[continued]
  431. On the `bicycles` index, Elasticsearch will simply ignore the `cycle_type`
  432. filter and rewrite the search request to the one below:
  433. [source,console]
  434. --------------------------------------------------
  435. GET bicycles,other_cycles/_search
  436. {
  437. "query": {
  438. "match": {
  439. "description": "dutch"
  440. }
  441. }
  442. }
  443. --------------------------------------------------
  444. // TEST[continued]
  445. On the `other_cycles` index, Elasticsearch will quickly figure out that
  446. `bicycle` doesn't exist in the terms dictionary of the `cycle_type` field and
  447. return a search response with no hits.
  448. This is a powerful way of making queries cheaper by putting common values in a
  449. dedicated index. This idea can also be combined across multiple fields: for
  450. instance if you track the color of each cycle and your `bicycles` index ends up
  451. having a majority of black bikes, you could split it into a `bicycles-black`
  452. and a `bicycles-other-colors` indices.
  453. The `constant_keyword` is not strictly required for this optimization: it is
  454. also possible to update the client-side logic in order to route queries to the
  455. relevant indices based on filters. However `constant_keyword` makes it
  456. transparently and allows to decouple search requests from the index topology in
  457. exchange of very little overhead.