[[preload-fielddata]]
=== Preloading Fielddata
The default behavior of Elasticsearch is to ((("fielddata", "pre-loading")))load in-memory fielddata _lazily_.
The first time Elasticsearch encounters a query that needs fielddata for a
particular field, it will load that entire field into memory for each segment
in the index.
For small segments, this requires a negligible amount of time. But if you
have a few 5 GB segments and need to load 10 GB of fielddata into memory, this
process could take tens of seconds. Users accustomed to subsecond response
times would all of a sudden be hit by an apparently unresponsive website.
There are three methods to combat this latency spike:
- Eagerly load fielddata
- Eagerly load global ordinals
- Prepopulate caches with warmers
All are variations on the same concept: preload the fielddata so that there is
no latency spike when the user needs to execute a search.
[[eager-fielddata]]
==== Eagerly Loading Fielddata
The first tool is called _eager loading_ (as opposed ((("eager loading", "of fielddata")))to the default lazy
loading). As new segments are created (by refreshing, flushing, or merging),
fields with eager loading enabled will have their per-segment fielddata
preloaded _before_ the segment becomes visible to search.
This means that the first query to hit the segment will not need to trigger
fielddata loading, as the in-memory cache has already been populated. This
prevents your users from experiencing the _cold cache_ latency spike.
Eager loading is enabled on a per-field basis, so you can control which fields
are pre-loaded:
[source,js]
----
PUT /music/_mapping/_song
{
"price_usd": {
"type": "integer",
"fielddata": {
"loading" : "eager" <1>
}
}
}
----
<1> By setting `fielddata.loading: eager`, we tell Elasticsearch to preload
this field's contents into memory.
Fielddata loading can be set to `lazy` or `eager` on existing fields, using
the `update-mapping` API.
[WARNING]
====
Eager loading simply shifts the cost of loading fielddata. Instead of paying
at query time, you pay at refresh time.
Large segments will take longer to refresh than small segments. Usually,
large segments are created by merging smaller segments that are already
visible to search, so the slower refresh time is not important.
====
[[global-ordinals]]
==== Global Ordinals
One of the techniques used to reduce the memory usage of string
fielddata is ((("ordinals")))called _ordinals_.
Imagine that we have a billion documents, each of which has a `status` field.
There are only three statuses: `status_pending`, `status_published`,
`status_deleted`. If we were to hold the full string status in memory for
every document, we would use 14 to 16 bytes per document, or about 15 GB.
Instead, we can identify the three unique strings, sort them, and number them: 0, 1, 2.
Ordinal | Term
-------------------
0 | status_deleted
1 | status_pending
2 | status_published
The original strings are stored only once in the ordinals list, and each
document just uses the numbered ordinal to point to the value that it
contains.
Doc | Ordinal
-------------------------
0 | 1 # pending
1 | 1 # pending
2 | 2 # published
3 | 0 # deleted
This reduces memory usage from 15 GB to less than 1 GB!
But there is a problem. Remember that fielddata caches are _per segment_. If
one segment contains only two statuses—`status_deleted` and
`status_published`—then the resulting ordinals (0 and 1) will not be the
same as the ordinals for a segment that contains all three statuses.
If we try to run a `terms` aggregation on the `status` field, we need to
aggregate on the actual string values, which means that we need to identify
the same values across all segments. A naive way of doing this would be to
run the aggregation on each segment, return the string values from each
segment, and then reduce them into an overall result. While this would work,
it would be slow and CPU intensive.
Instead, we use a structure called _global ordinals_. ((("global ordinals"))) Global ordinals are a
small in-memory data structure built on top of fielddata. Unique values are
identified _across all segments_ and stored in an ordinals list like the one
we have already described.
Now, our `terms` aggregation can just aggregate on the global ordinals, and
the conversion from ordinal to actual string value happens only once at the
end of the aggregation. This increases performance of aggregations (and
sorting) by a factor of three or four.
===== Building global ordinals
Of course, nothing in life is free. ((("global ordinals", "building"))) Global ordinals cross all segments in an
index, so if a new segment is added or an old segment is deleted, the global
ordinals need to be rebuilt. Rebuilding requires reading every unique term in
every segment. The higher the cardinality--the more unique terms that exist--the longer this process takes.
Global ordinals are built on top of in-memory fielddata and doc values. In
fact, they are one of the major reasons that doc values perform as well as
they do.
Like fielddata loading, global ordinals are built lazily, by default. The
first request that requires fielddata to hit an index will trigger the
building of global ordinals. Depending on the cardinality of the field, this
can result in a significant latency spike for your users. Once global
ordinals have been rebuilt, they will be reused until the segments in the index
change: after a refresh, a flush, or a merge.
[[eager-global-ordinals]]
===== Eager global ordinals
Individual string fields((("eager loading", "of global ordinals")))((("global ordinals", "eager"))) can be configured to prebuild global ordinals eagerly:
[source,js]
----
PUT /music/_mapping/_song
{
"song_title": {
"type": "string",
"fielddata": {
"loading" : "eager_global_ordinals" <1>
}
}
}
----
<1> Setting `eager_global_ordinals` also implies loading fielddata eagerly.
Just like the eager preloading of fielddata, eager global ordinals are built
before a new segment becomes visible to search.
[NOTE]
=========================
Ordinals are only built and used for strings. Numerical data (integers, geopoints,
dates, etc) doesn't need an ordinal mapping, since the value itself acts as an
intrinsic ordinal mapping.
Therefore, you can only enable eager global ordinals for string fields.
=========================
Doc values can also have their global ordinals built eagerly:
[source,js]
----
PUT /music/_mapping/_song
{
"song_title": {
"type": "string",
"doc_values": true,
"fielddata": {
"loading" : "eager_global_ordinals" <1>
}
}
}
----
<1> In this case, fielddata is not loaded into memory, but doc values are
loaded into the filesystem cache.
Unlike fielddata preloading, eager building of global ordinals can have an
impact on the _real-time_ aspect of your data. For very high cardinality
fields, building global ordinals can delay a refresh by several seconds. The
choice is between paying the cost on each refresh, or on the first query after
a refresh. If you index often and query seldom, it is probably better to pay
the price at query time instead of on every refresh.
[TIP]
====
Make your global ordinals pay for themselves. If you have very high
cardinality fields that take seconds to rebuild, increase the
`refresh_interval` so that global ordinals remain valid for longer. This will
also reduce CPU usage, as you will need to rebuild global ordinals less often.
====
[[index-warmers]]
==== Index Warmers
Finally, we come to _index warmers_. Warmers((("index warmers"))) predate eager fielddata loading
and eager global ordinals, but they still serve a purpose. An index warmer
allows you to specify a query and aggregations that should be run before a new
segment is made visible to search. The idea is to prepopulate, or _warm_,
caches so your users never see a spike in latency.
Originally, the most important use for warmers was to make sure that fielddata
was pre-loaded, as this is usually the most costly step. This is now better
controlled with the techniques we discussed previously. However, warmers can
be used to prebuild filter caches, and can still be used to preload fielddata
should you so choose.
Let's register a warmer and then talk about what's happening:
[source,js]
----
PUT /music/_warmer/warmer_1 <1>
{
"query" : {
"filtered" : {
"filter" : {
"bool": {
"should": [ <2>
{ "term": { "tag": "rock" }},
{ "term": { "tag": "hiphop" }},
{ "term": { "tag": "electronics" }}
]
}
}
}
},
"aggs" : {
"price" : {
"histogram" : {
"field" : "price", <3>
"interval" : 10
}
}
}
}
----
<1> Warmers are associated with an index (`music`) and are registered using
the `_warmer` endpoint and a unique ID (`warmer_1`).
<2> The three most popular music genres have their filter caches prebuilt.
<3> The fielddata and global ordinals for the `price` field will be preloaded.
Warmers are registered against a specific index.((("warmers", see="index warmers"))) Each warmer is given a
unique ID, because you can have multiple warmers per index.
Then you just specify a query, any query. It can include queries, filters,
aggregations, sort values, scripts--literally any valid query DSL. The
point is to register queries that are representative of the traffic that your
users will generate, so that appropriate caches can be prepopulated.
When a new segment is created, Elasticsearch will _literally_ execute the queries
registered in your warmers. The act of executing these queries will force
caches to be loaded. Only after all warmers have been executed will the segment
be made visible to search.
[WARNING]
====
Similar to eager loading, warmers shift the cost of cold caches to refresh time.
When registering warmers, it is important to be judicious. You _could_ add
thousands of warmers to make sure every cache is populated--but that will
drastically increase the time it takes for new segments to be made searchable.
In practice, select a handful of queries that represent the majority of your
user's queries and register those.
====
Some administrative details (such as getting existing warmers and deleting warmers) that have been omitted from this explanation. Refer to the http://bit.ly/1AUGwys[warmers documentation] for the rest
of the details.
- Introduction
- 入门
- 是什么
- 安装
- API
- 文档
- 索引
- 搜索
- 聚合
- 小结
- 分布式
- 结语
- 分布式集群
- 空集群
- 集群健康
- 添加索引
- 故障转移
- 横向扩展
- 更多扩展
- 应对故障
- 数据
- 文档
- 索引
- 获取
- 存在
- 更新
- 创建
- 删除
- 版本控制
- 局部更新
- Mget
- 批量
- 结语
- 分布式增删改查
- 路由
- 分片交互
- 新建、索引和删除
- 检索
- 局部更新
- 批量请求
- 批量格式
- 搜索
- 空搜索
- 多索引和多类型
- 分页
- 查询字符串
- 映射和分析
- 数据类型差异
- 确切值对决全文
- 倒排索引
- 分析
- 映射
- 复合类型
- 结构化查询
- 请求体查询
- 结构化查询
- 查询与过滤
- 重要的查询子句
- 过滤查询
- 验证查询
- 结语
- 排序
- 排序
- 字符串排序
- 相关性
- 字段数据
- 分布式搜索
- 查询阶段
- 取回阶段
- 搜索选项
- 扫描和滚屏
- 索引管理
- 创建删除
- 设置
- 配置分析器
- 自定义分析器
- 映射
- 根对象
- 元数据中的source字段
- 元数据中的all字段
- 元数据中的ID字段
- 动态映射
- 自定义动态映射
- 默认映射
- 重建索引
- 别名
- 深入分片
- 使文本可以被搜索
- 动态索引
- 近实时搜索
- 持久化变更
- 合并段
- 结构化搜索
- 查询准确值
- 组合过滤
- 查询多个准确值
- 包含,而不是相等
- 范围
- 处理 Null 值
- 缓存
- 过滤顺序
- 全文搜索
- 匹配查询
- 多词查询
- 组合查询
- 布尔匹配
- 增加子句
- 控制分析
- 关联失效
- 多字段搜索
- 多重查询字符串
- 单一查询字符串
- 最佳字段
- 最佳字段查询调优
- 多重匹配查询
- 最多字段查询
- 跨字段对象查询
- 以字段为中心查询
- 全字段查询
- 跨字段查询
- 精确查询
- 模糊匹配
- Phrase matching
- Slop
- Multi value fields
- Scoring
- Relevance
- Performance
- Shingles
- Partial_Matching
- Postcodes
- Prefix query
- Wildcard Regexp
- Match phrase prefix
- Index time
- Ngram intro
- Search as you type
- Compound words
- Relevance
- Scoring theory
- Practical scoring
- Query time boosting
- Query scoring
- Not quite not
- Ignoring TFIDF
- Function score query
- Popularity
- Boosting filtered subsets
- Random scoring
- Decay functions
- Pluggable similarities
- Conclusion
- Language intro
- Intro
- Using
- Configuring
- Language pitfalls
- One language per doc
- One language per field
- Mixed language fields
- Conclusion
- Identifying words
- Intro
- Standard analyzer
- Standard tokenizer
- ICU plugin
- ICU tokenizer
- Tidying text
- Token normalization
- Intro
- Lowercasing
- Removing diacritics
- Unicode world
- Case folding
- Character folding
- Sorting and collations
- Stemming
- Intro
- Algorithmic stemmers
- Dictionary stemmers
- Hunspell stemmer
- Choosing a stemmer
- Controlling stemming
- Stemming in situ
- Stopwords
- Intro
- Using stopwords
- Stopwords and performance
- Divide and conquer
- Phrase queries
- Common grams
- Relevance
- Synonyms
- Intro
- Using synonyms
- Synonym formats
- Expand contract
- Analysis chain
- Multi word synonyms
- Symbol synonyms
- Fuzzy matching
- Intro
- Fuzziness
- Fuzzy query
- Fuzzy match query
- Scoring fuzziness
- Phonetic matching
- Aggregations
- overview
- circuit breaker fd settings
- filtering
- facets
- docvalues
- eager
- breadth vs depth
- Conclusion
- concepts buckets
- basic example
- add metric
- nested bucket
- extra metrics
- bucket metric list
- histogram
- date histogram
- scope
- filtering
- sorting ordering
- approx intro
- cardinality
- percentiles
- sigterms intro
- sigterms
- fielddata
- analyzed vs not
- 地理坐标点
- 地理坐标点
- 通过地理坐标点过滤
- 地理坐标盒模型过滤器
- 地理距离过滤器
- 缓存地理位置过滤器
- 减少内存占用
- 按距离排序
- Geohashe
- Geohashe
- Geohashe映射
- Geohash单元过滤器
- 地理位置聚合
- 地理位置聚合
- 按距离聚合
- Geohash单元聚合器
- 范围(边界)聚合器
- 地理形状
- 地理形状
- 映射地理形状
- 索引地理形状
- 查询地理形状
- 在查询中使用已索引的形状
- 地理形状的过滤与缓存
- 关系
- 关系
- 应用级别的Join操作
- 扁平化你的数据
- Top hits
- Concurrency
- Concurrency solutions
- 嵌套
- 嵌套对象
- 嵌套映射
- 嵌套查询
- 嵌套排序
- 嵌套集合
- Parent Child
- Parent child
- Indexing parent child
- Has child
- Has parent
- Children agg
- Grandparents
- Practical considerations
- Scaling
- Shard
- Overallocation
- Kagillion shards
- Capacity planning
- Replica shards
- Multiple indices
- Index per timeframe
- Index templates
- Retiring data
- Index per user
- Shared index
- Faking it
- One big user
- Scale is not infinite
- Cluster Admin
- Marvel
- Health
- Node stats
- Other stats
- Deployment
- hardware
- other
- config
- dont touch
- heap
- file descriptors
- conclusion
- cluster settings
- Post Deployment
- dynamic settings
- logging
- indexing perf
- rolling restart
- backup
- restore
- conclusion