[[concurrency-solutions]]
=== Solving Concurrency Issues
The problem comes when we want to allow more than one person to rename files
or directories _at the same time_. ((("concurrency", "solving concurrency issues")))((("relationships", "solving concurrency issues"))) Imagine that you rename the `/clinton`
directory, which contains hundreds of thousands of files. Meanwhile, another
user renames the single file `/clinton/projects/elasticsearch/README.txt`.
That user's change, although it started after yours, will probably finish more
quickly.
One of two things will happen:
* You have decided to use `version` numbers, in which case your mass rename
will fail with a version conflict when it hits the renamed
`README.asciidoc` file.
* You didn't use versioning, and your changes will overwrite the changes from
the other user.
The problem is that Elasticsearch does not support
http://en.wikipedia.org/wiki/ACID_transactions[ACID transactions].((("ACID transactions"))) Changes to
individual documents are ACIDic, but not changes involving multiple documents.
If your main data store is a relational database, and Elasticsearch is simply
being used as a search engine((("relational databases", "Elasticsearch used with"))) or as a way to improve performance, make
your changes in the database first and replicate those changes to
Elasticsearch after they have succeeded. This way, you benefit from the ACID
transactions available in the database, and all changes to Elasticsearch happen
in the right order. Concurrency is dealt with in the relational database.
If you are not using a relational store, these concurrency issues need to
be dealt with at the Elasticsearch level. The following are three practical
solutions using Elasticsearch, all of which involve some form of locking:
* Global Locking
* Document Locking
* Tree Locking
[TIP]
==================================================
The solutions described in this section could also be implemented by applying the same
principles while using an external system instead of Elasticsearch.
==================================================
[[global-lock]]
==== Global Locking
We can avoid concurrency issues completely by allowing only one process to
make changes at any time.((("locking", "global lock")))((("global lock"))) Most changes will involve only a few files and will
complete very quickly. A rename of a top-level directory may block all other
changes for longer, but these are likely to be much less frequent.
Because document-level changes in Elasticsearch are ACIDic, we can use the
existence or absence of a document as a global lock. To request a
lock, we try to `create` the global-lock document:
[source,json]
--------------------------
PUT /fs/lock/global/_create
{}
--------------------------
If this `create` request fails with a conflict exception,
another process has already been granted the global lock and we will have to
try again later. If it succeeds, we are now the proud owners of the
global lock and we can continue with our changes. Once we are finished, we
must release the lock by deleting the global lock document:
[source,json]
--------------------------
DELETE /fs/lock/global
--------------------------
Depending on how frequent changes are, and how long they take, a global lock
could restrict the performance of a system significantly. We can increase
parallelism by making our locking more fine-grained.
[[document-locking]]
==== Document Locking
Instead of locking the whole filesystem, we could lock individual documents
by using the same technique as previously described.((("locking", "document locking")))((("document locking"))) A process could use a
<<scan-scroll,scan-and-scroll>> request to retrieve the IDs of all documents
that would be affected by the change, and would need to create a lock file for
each of them:
[source,json]
--------------------------
PUT /fs/lock/_bulk
{ "create": { "_id": 1}} <1>
{ "process_id": 123 } <2>
{ "create": { "_id": 2}}
{ "process_id": 123 }
...
--------------------------
<1> The ID of the `lock` document would be the same as the ID of the file
that should be locked.
<2> The `process_id` is a unique ID that represents the process that
wants to perform the changes.
If some files are already locked, parts of the `bulk` request will fail and we
will have to try again.
Of course, if we try to lock _all_ of the files again, the `create` statements
that we used previously will fail for any file that is already locked by us!
Instead of a simple `create` statement, we need an `update` request with an
`upsert` parameter and this `script`:
[source,groovy]
--------------------------
if ( ctx._source.process_id != process_id ) { <1>
assert false; <2>
}
ctx.op = 'noop'; <3>
--------------------------
<1> `process_id` is a parameter that we pass into the script.
<2> `assert false` will throw an exception, causing the update to fail.
<3> Changing the `op` from `update` to `noop` prevents the update request
from making any changes, but still returns success.
The full `update` request looks like this:
[source,json]
--------------------------
POST /fs/lock/1/_update
{
"upsert": { "process_id": 123 },
"script": "if ( ctx._source.process_id != process_id )
{ assert false }; ctx.op = 'noop';"
"params": {
"process_id": 123
}
}
--------------------------
If the document doesn't already exist, the `upsert` document will be inserted--much the same as the `create` request we used previously. However, if the
document _does_ exist, the script will look at the `process_id` stored in the
document. If it is the same as ours, it aborts the update (`noop`) and
returns success. If it is different, the `assert false` throws an exception
and we know that the lock has failed.
Once all locks have been successfully created, the rename operation can begin.
Afterward, we must release((("delete-by-query request"))) all of the locks, which we can do with a
`delete-by-query` request:
[source,json]
--------------------------
POST /fs/_refresh <1>
DELETE /fs/lock/_query
{
"query": {
"term": {
"process_id": 123
}
}
}
--------------------------
<1> The `refresh` call ensures that all `lock` documents are visible to
the `delete-by-query` request.
Document-level locking enables fine-grained access control, but creating lock
files for millions of documents can be expensive. In certain scenarios, such
as this example with directory trees, it is possible to achieve fine-grained
locking with much less work.
[[tree-locking]]
==== Tree Locking
Rather than locking every involved document, as in the previous option, we
could lock just part of the directory tree.((("locking", "tree locking"))) We will need exclusive access
to the file or directory that we want to rename, which can be achieved with an
_exclusive lock_ document:
[source,json]
--------------------------
{ "lock_type": "exclusive" }
--------------------------
And we need shared locks on any parent directories, with a _shared lock_
document:
[source,json]
--------------------------
{
"lock_type": "shared",
"lock_count": 1 <1>
}
--------------------------
<1> The `lock_count` records the number of processes that hold a shared lock.
A process that wants to rename `/clinton/projects/elasticsearch/README.txt`
needs an _exclusive_ lock on that file, and a _shared_ lock on `/clinton`,
`/clinton/projects`, and `/clinton/projects/elasticsearch`.
A simple `create` request will suffice for the exclusive lock, but the shared
lock needs a scripted update to implement some extra logic:
[source,groovy]
--------------------------
if (ctx._source.lock_type == 'exclusive') {
assert false; <1>
}
ctx._source.lock_count++ <2>
--------------------------
<1> If the `lock_type` is `exclusive`, the `assert` statement will throw
an exception, causing the update request to fail.
<2> Otherwise, we increment the `lock_count`.
This script handles the case where the `lock` document already exists, but we
will also need an `upsert` document to handle the case where it doesn't exist
yet. The full update request is as follows:
[source,json]
--------------------------
POST /fs/lock/%2Fclinton/_update <1>
{
"upsert": { <2>
"lock_type": "shared",
"lock_count": 1
},
"script": "if (ctx._source.lock_type == 'exclusive')
{ assert false }; ctx._source.lock_count++"
}
--------------------------
<1> The ID of the document is `/clinton`, which is URL-encoded to `%2fclinton`.
<2> The `upsert` document will be inserted if the document does not already
exist.
Once we succeed in gaining a shared lock on all of the parent directories, we
try to `create` an exclusive lock on the file itself:
[source,json]
--------------------------
PUT /fs/lock/%2Fclinton%2fprojects%2felasticsearch%2fREADME.txt/_create
{ "lock_type": "exclusive" }
--------------------------
Now, if somebody else wants to rename the `/clinton` directory, they would
have to gain an exclusive lock on that path:
[source,json]
--------------------------
PUT /fs/lock/%2Fclinton/_create
{ "lock_type": "exclusive" }
--------------------------
This request would fail because a `lock` document with the same ID already
exists. The other user would have to wait until our operation is done and we
have released our locks. The exclusive lock can just be deleted:
[source,json]
--------------------------
DELETE /fs/lock/%2Fclinton%2fprojects%2felasticsearch%2fREADME.txt
--------------------------
The shared locks need another script that decrements the `lock_count` and, if
the count drops to zero, deletes the `lock` document:
[source,groovy]
--------------------------
if (--ctx._source.lock_count == 0) {
ctx.op = 'delete' <1>
}
--------------------------
<1> Once the `lock_count` reaches `0`, the `ctx.op` is changed from `update`
to `delete`.
This update request would need to be run for each parent directory in reverse
order, from longest to shortest:
[source,json]
--------------------------
POST /fs/lock/%2Fclinton%2fprojects%2felasticsearch/_update
{
"script": "if (--ctx._source.lock_count == 0) { ctx.op = 'delete' } "
}
--------------------------
Tree locking gives us fine-grained concurrency control with the minimum of
effort. Of course, it is not applicable to every situation--the data model
must have some sort of access path like the directory tree for it to work.
[NOTE]
=====================================
None of the three options--global, document, or tree locking--deals with
the thorniest problem associated with locking: what happens if the process
holding the lock dies?
The unexpected death of a process leaves us with two problems:
* How do we know that we can release the locks held by the dead process?
* How do we clean up the change that the dead process did not manage to complete?
These topics are beyond the scope of this book, but you will need to give them
some thought if you decide to use locking.
=====================================
While denormalization is a good choice for many projects, the need for locking
schemes can make for complicated implementations. Instead, Elasticsearch
provides two models that help us deal with related entities:
_nested objects_ and _parent-child relationships_.
- 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