## 文檔局部更新
在《更新文檔》一章,我們說了一種通過檢索,修改,然后重建整文檔的索引方法來更新文檔。這是對的。然而,使用`update` API,我們可以使用一個請求來實現局部更新,例如增加數量的操作。
我們也說過文檔是不可變的——它們不能被更改,只能被替換。`update` API**必須**遵循相同的規則。表面看來,我們似乎是局部更新了文檔的位置,內部卻是像我們之前說的一樣簡單的使用`update` API處理相同的*檢索-修改-重建索引*流程,我們也減少了其他進程可能導致沖突的修改。
最簡單的`update`請求表單接受一個局部文檔參數`doc`,它會合并到現有文檔中——對象合并在一起,存在的標量字段被覆蓋,新字段被添加。舉個例子,我們可以使用以下請求為博客添加一個`tags`字段和一個`views`字段:
```Javascript
POST /website/blog/1/_update
{
"doc" : {
"tags" : [ "testing" ],
"views": 0
}
}
```
如果請求成功,我們將看到類似`index`請求的響應結果:
```
{
"_index" : "website",
"_id" : "1",
"_type" : "blog",
"_version" : 3
}
```
檢索文檔文檔顯示被更新的`_source`字段:
```Javascript
{
"_index": "website",
"_type": "blog",
"_id": "1",
"_version": 3,
"found": true,
"_source": {
"title": "My first blog entry",
"text": "Starting to get the hang of this...",
"tags": [ "testing" ], <1>
"views": 0 <1>
}
}
```
- <1> 我們新添加的字段已經被添加到`_source`字段中。
### 使用腳本局部更新
> ### 使用Groovy腳本
> 這時候當API不能滿足要求時,Elasticsearch允許你使用腳本實現自己的邏輯。腳本支持非常多的API,例如搜索、排序、聚合和文檔更新。腳本可以通過請求的一部分、檢索特殊的`.scripts`索引或者從磁盤加載方式執行。
> 默認的腳本語言是[Groovy](http://groovy.codehaus.org/),一個快速且功能豐富的腳本語言,語法類似于Javascript。它在一個**沙盒(sandbox)**中運行,以防止惡意用戶毀壞Elasticsearch或攻擊服務器。
> 你可以在《腳本參考文檔》中獲得更多信息。
腳本能夠使用`update` API改變`_source`字段的內容,它在腳本內部以`ctx._source`表示。例如,我們可以使用腳本增加博客的`views`數量:
```Javascript
POST /website/blog/1/_update
{
"script" : "ctx._source.views+=1"
}
```
我們還可以使用腳本增加一個新標簽到`tags`數組中。在這個例子中,我們定義了一個新標簽做為參數而不是硬編碼在腳本里。這允許Elasticsearch未來可以重復利用腳本,而不是在想要增加新標簽時必須每次編譯新腳本:
```Javascript
POST /website/blog/1/_update
{
"script" : "ctx._source.tags+=new_tag",
"params" : {
"new_tag" : "search"
}
}
```
獲取最后兩個有效請求的文檔:
```Javascript
{
"_index": "website",
"_type": "blog",
"_id": "1",
"_version": 5,
"found": true,
"_source": {
"title": "My first blog entry",
"text": "Starting to get the hang of this...",
"tags": ["testing", "search"], <1>
"views": 1 <2>
}
}
```
- <1> `search`標簽已經被添加到`tags`數組。
- <2> `views`字段已經被增加。
通過設置`ctx.op`為`delete`我們可以根據內容刪除文檔:
```Javascript
POST /website/blog/1/_update
{
"script" : "ctx.op = ctx._source.views == count ? 'delete' : 'none'",
"params" : {
"count": 1
}
}
```
### 更新可能不存在的文檔
想象我們要在Elasticsearch中存儲瀏覽量計數器。每當有用戶訪問頁面,我們增加這個頁面的瀏覽量。但如果這是個新頁面,我們并不確定這個計數器存在與否。當我們試圖更新一個不存在的文檔,更新將失敗。
在這種情況下,我們可以使用`upsert`參數定義文檔來使其不存在時被創建。
```Javascrupt
POST /website/pageviews/1/_update
{
"script" : "ctx._source.views+=1",
"upsert": {
"views": 1
}
}
```
第一次執行這個請求,`upsert`值被索引為一個新文檔,初始化`views`字段為`1`.接下來文檔已經存在,所以`script`被更新代替,增加`views`數量。
### 更新和沖突
這這一節的介紹中,我們介紹了如何在**檢索(retrieve)**和**重建索引(reindex)**中保持更小的窗口,如何減少沖突性變更發生的概率,不過這些無法被完全避免,像一個其他進程在`update`進行重建索引時修改了文檔這種情況依舊可能發生。
為了避免丟失數據,`update` API在**檢索(retrieve)**階段檢索文檔的當前`_version`,然后在**重建索引(reindex)**階段通過`index`請求提交。如果其他進程在**檢索(retrieve)**和**重建索引(reindex)**階段修改了文檔,`_version`將不能被匹配,然后更新失敗。
對于多用戶的局部更新,文檔被修改了并不要緊。例如,兩個進程都要增加頁面瀏覽量,增加的順序我們并不關心——如果沖突發生,我們唯一要做的僅僅是重新嘗試更新既可。
這些可以通過`retry_on_conflict`參數設置重試次數來自動完成,這樣`update`操作將會在發生錯誤前重試——這個值默認為0。
```Javascript
POST /website/pageviews/1/_update?retry_on_conflict=5 <1>
{
"script" : "ctx._source.views+=1",
"upsert": {
"views": 0
}
}
```
- <1> 在錯誤發生前重試更新5次
這適用于像增加計數這種順序無關的操作,但是還有一種順序非常重要的情況。例如`index` API,使用**“保留最后更新(last-write-wins)”**的`update` API,但它依舊接受一個`version`參數以允許你使用**樂觀并發控制(optimistic concurrency control)**來指定你要更細文檔的版本。
- 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