# 更新API
更新API允許根據提供的腳本來更新文檔。操作從索引獲取文檔(通過分片并發的),運行腳本(具有可選腳本語言和參數),并將結果建立索引(也允許刪除或忽略該操作)。它使用版本控制來確保在“get”和“reindex”期間沒有發生更新。
請注意,此操作仍然意味著文檔的完整重新索引,它只是刪除一些網絡往返,并減少`get`和`index`之間版本沖突的機會。需要啟用`_source`字段以使此功能正常工作。
為了演示,我們創建一個簡單的文檔:
```
PUT test/type1/1
{
"counter" : 1,
"tags" : ["red"]
}
```
## 腳本更新
現在,我們能執行以下腳本來遞增計數器:
```
POST test/type1/1/_update
{
"script" : {
"inline": "ctx._source.counter += params.count",
"lang": "painless",
"params" : {
"count" : 4
}
}
}
```
我們可以在`tags`中添加一個`tag`(注意,如果`tags`存在,它將會添加它,由于它是一個列表):
```
POST test/type1/1/_update
{
"script" : {
"inline": "ctx._source.tags.add(params.tag)",
"lang": "painless",
"params" : {
"tag" : "blue"
}
}
}
```
除`_source`外,以下變量可通過`ctx`映射獲得:`_index`、`_type`、`_id`、`_version`、`_routing`、`_parent`和`_now`(當前時間戳)。
我們還可以在文檔中添加一個新的字段:
```
POST test/type1/1/_update
{
"script" : "ctx._source.new_field = \"value_of_new_field\""
}
```
或者從文檔中刪除一個字段:
```
POST test/type1/1/_update
{
"script" : "ctx._source.remove(\"new_field\")"
}
```
我們甚至可以改變所執行的操作。這個例子中刪除文檔如果標簽字段包含`green`,否則什么也不做(`noop`):
```
POST test/type1/1/_update
{
"script" : {
"inline": "if (ctx._source.tags.contains(params.tag)) { ctx.op = \"delete\" } else { ctx.op = \"none\" }",
"lang": "painless",
"params" : {
"tag" : "green"
}
}
}
```
## 根據部分文檔修改
更新API還支持傳遞一個部分文檔,它將被合并到現有文檔中(簡單的遞歸合并,對象的內部合并,替換核心“鍵/值”和數組)。例如:
```
POST test/type1/1/_update
{
"doc" : {
"name" : "new_name"
}
}
```
如果指定了`doc`和`script`,則忽略`doc`。最好是將部分文檔的字段對放在腳本本身中。
## 探測noop更新
如果指定了`doc`,它的值將與現有的`_source`合并。默認情況下,不更改任何內容的更新會探測到它們不會更改任何內容并返回“result”:“noop”,如下所示:
```
POST test/type1/1/_update
{
"doc" : {
"name" : "new_name"
}
}
```
如果在發送請求之前`name`是`new_name`,則忽略整個更新請求。如果請求被忽略,則響應中的`result`元素返回`noop`。
```
{
"_shards": {
"total": 0,
"successful": 0,
"failed": 0
},
"_index": "test",
"_type": "type1",
"_id": "1",
"_version": 6,
"result": noop
}
```
您可以通過設置“detect\_noop”為`false`來禁用此行為,如下所示:
```
POST test/type1/1/_update
{
"doc" : {
"name" : "new_name"
},
"detect_noop": false
}
```
## Upserts
如果文檔不存在,則將`upsert`的內容作為新的文檔插入。如果文檔確實存在,那么`script`將被執行:
```
POST test/type1/1/_update
{
"script" : {
"inline": "ctx._source.counter += params.count",
"lang": "painless",
"params" : {
"count" : 4
}
},
"upsert" : {
"counter" : 1
}
}
```
### scripted\_upsert
如果您希望無論文檔是否存在都運行腳本——即腳本處理初始化文檔替代`upsert`元素——則將`scripted_upsert`設置為`true`:
```
POST sessions/session/dh3sgudg8gsrgl/_update
{
"scripted_upsert":true,
"script" : {
"id": "my_web_session_summariser",
"params" : {
"pageViewEvent" : {
"url":"foo.com/bar",
"response":404,
"time":"2014-01-01 12:32"
}
}
},
"upsert" : {}
}
```
### doc\_as\_upsert
將`doc_as_upsert`設置為`true`而不是發送部分文檔加上`upsert`文檔,而將`doc`的內容用作`upsert`值:
```
POST test/type1/1/_update
{
"doc" : {
"name" : "new_name"
},
"doc_as_upsert" : true
}
```
## 參數
更新操作支持如下查詢字符串參數:
* retry\_on\_conflict在更新的獲取和索引階段之間,另一個進程可能已經更新了同一個文檔。默認情況下,更新將失敗并出現版本沖突異常。`retry_on_conflict`參數控制在最后拋出異常之前重試更新的次數。
* routing如果正在更新的文檔不存在,則使用路由將更新請求路由到正確的分片,并為`upsert`請求設置路由。不能用于更新現有文檔的路由。parent如果正在更新的文檔不存在,則父用于將更新請求路由到正確的分片,并為`upsert`請求設置父級。不能用于更新現有文檔的父級。如果指定了別名索引路由,則它將覆蓋父路由,并用于路由請求。
* timeout等待分片變為可用的超時時間。
* wait\_for\_active\_shards在進行更新操作之前,分片副本的數量需要處于活動狀態。詳見[這里](Index_API.md#index-wait-for-active-shards)。
* refresh控制此請求所做的更改對于搜索是可見的。參見[?refresh](refresh.html)。
* \_source允許控制在響應中是否和如何返回更新的源。默認情況下,不會返回更新的源。有關詳細信息,請參閱[source filtering](../Search_APIs/Request_Body_Search/Source_filtering.md)。
* version & version\_type更新API在內部使用Elasticsearch的版本控制支持,以確保在更新過程中文檔不會更改。您可以使用`version`參數指定僅當文檔的版本與指定的版本匹配時才應更新該文檔。通過將版本類型設置為`force`,您可以在更新后強制使用新版本的文檔(謹慎使用!`force`不保證文檔沒有更改)。
> > 注意
>
> ## 更新API不支持外部版本控制
>
> 更新API不支持外部版本控制(版本類型`external`&`external_gte`),因為它會導致Elasticsearch版本號與外部系統不同步。使用[index API](Index_API.md)代替。
> my note
>
> script的使用
- 入門
- 基本概念
- 安裝
- 探索你的集群
- 集群健康
- 列出所有索引庫
- 創建一個索引庫
- 索引文檔創建與查詢
- 刪除一個索引庫
- 修改你的數據
- 更新文檔
- 刪除文檔
- 批量處理
- 探索你的數據
- 搜索API
- 查詢語言介紹
- 執行搜索
- 執行過濾
- 執行聚合
- 總結
- Elasticsearch設置
- 安裝Elasticsearch
- .zip或.tar.gz文件的安裝方式
- Install Elasticsearch with .zip on Windows
- Debian軟件包安裝方式
- RPM安裝方式
- Install Elasticsearch with Windows MSI Installer
- Docker安裝方式
- 配置Elasticsearch
- 安全配置
- 日志配置
- 重要的Elasticsearch配置
- 重要的系統配置
- 系統設置
- 在jvm.options中設置JVM堆大小
- 禁用swapping
- 文件描述符
- 虛擬內存
- 線程數
- DNS cache settings
- 啟動前檢查
- 堆大小檢查
- 文件描述符檢查
- 內存鎖定檢查
- 最大線程數檢查
- 最大虛擬內存檢查
- Max file size check
- 最大map數檢查
- JVM Client模式檢查
- 串行收集使用檢查
- 系統調用過濾檢查
- OnError與OnOutOfMemoryError檢查
- Early-access check
- G1GC檢查
- Elasticsearch停機
- Elasticsearch升級
- 滾動升級
- 全集群重啟升級
- 索引重建升級
- Set up X-Pack
- Installing X-Pack
- X-Pack Settings
- Watcher Settings
- Configuring Security
- Breaking changes in 6.0
- X-Pack Breaking Changes
- 重大變化
- 6.0的重大變化
- 聚合變化
- Cat API變化
- 客戶端變化
- 集群變化
- 文檔API變化
- 索引變化
- 預處理變化
- 映射變化
- Packaging變化
- Percolator變化
- 插件變化
- 索引重建變化
- 信息統計變化
- DSL查詢變化
- 設置變化
- 腳本變化
- API約定
- 多索引語法
- 索引庫名稱的日期運算
- 常用選項
- URL-based訪問控制
- 文檔APIs
- 讀寫文檔
- 索引接口
- Get接口
- Delete API
- Delete By Query API
- Update API
- Update By Query API
- Multi Get API
- Bulk API
- Reindex API
- Term Vectors
- Multi termvectors API
- ?refresh
- 搜索APIs
- Search
- URI Search
- Request Body Search
- Query
- From / Size
- Sort
- Source filtering
- Fields
- Script Fields
- Doc value Fields
- Post filter
- Highlighting
- Rescoring
- Search Type
- Scroll
- Preference
- Explain
- Version
- Index Boost
- min_score
- Named Queries
- Inner hits
- Field Collapsing
- Search After
- Search Template
- Multi Search Template
- Search Shards API
- Suggesters
- Term suggester
- Phrase Suggester
- Completion Suggester
- Context Suggester
- Returning the type of the suggester
- Multi Search API
- Count API
- Validate API
- Explain API
- Profile API
- Profiling Queries
- Profiling Aggregations
- Profiling Considerations
- Field Capabilities API
- Aggregations
- Metrics Aggregations
- 平均值聚合
- 值計數聚合(Value Count Aggregation)
- Cardinality Aggregation
- Extended Stats Aggregation
- 地理邊界聚合
- 地理重心聚合
- Max Aggregation
- Min Aggregation
- Percentiles Aggregation
- Percentile Ranks Aggregation
- Scripted Metric Aggregation
- Stats Aggregation
- Sum Aggregation
- Top hits Aggregation
- Value Count Aggregation
- Bucket Aggregations
- 鄰接矩陣聚合
- Children Aggregation
- Date Histogram Aggregation
- Date Range Aggregation
- Significant Terms Aggregation
- Filter Aggregation(過濾器聚合)
- Filters Aggregation
- Geo Distance Aggregation(地理距離聚合) 轉至元數據結尾
- GeoHash grid Aggregation(GeoHash網格聚合)
- Global Aggregation(全局聚合) 轉至元數據結尾
- Histogram Aggregation
- IP Range Aggregation(IP范圍聚合)
- Missing Aggregation
- Nested Aggregation(嵌套聚合)
- Range Aggregation(范圍聚合)
- Reverse nested Aggregation
- Sampler Aggregation
- Significant Terms Aggregation
- Significant Text Aggregation
- Terms Aggregation
- Pipeline Aggregations
- Avg Bucket Aggregation
- Derivative Aggregation(導數聚合)
- Max Bucket Aggregation
- Min Bucket Aggregation
- Sum Bucket Aggregation
- Stats Bucket Aggregation
- Extended Stats Bucket Aggregation(擴展信息桶聚合)
- Percentiles Bucket Aggregation(百分數桶聚合)
- Moving Average Aggregation
- Cumulative Sum Aggregation(累積匯總聚合)
- Bucket Script Aggregation(桶腳本聚合)
- Bucket Selector Aggregation(桶選擇器聚合)
- Serial Differencing Aggregation(串行差異聚合)
- Matrix Aggregations
- Matrix Stats
- Caching heavy aggregations
- Returning only aggregation results
- Aggregation Metadata
- Returning the type of the aggregation
- Indices APIs
- Create Index /創建索引
- Delete Index /刪除索引
- Get Index /獲取索引
- Indices Exists /索引存在
- Open / Close Index API /啟動關閉索引
- Shrink Index /縮小索引
- Rollover Index/滾動索引
- Put Mapping /提交映射
- Get Mapping /獲取映射
- Get Field Mapping /獲取字段映射
- Types Exists
- Index Aliases
- Update Indices Settings
- Get Settings
- Analyze
- Explain Analyze
- Index Templates
- 索引統計信息
- 索引段
- 索引恢復
- 索引分片存儲
- 清理緩存
- 刷新
- 同步刷新
- 重新加載
- 強制合并
- Cat APIs
- cat aliases
- cat allocation
- cat count
- cat fielddata
- cat health
- cat indices
- cat master
- cat nodeattrs
- cat nodes
- cat pending tasks
- cat plugins
- cat recovery
- cat repositories
- cat segments
- cat shards
- cat thread pool
- cat snapshots
- cat templates
- Cluster APIs
- 集群健康
- 集群狀態
- 集群統計
- 掛起的集群任務
- 集群重新路由
- Cluster Update Settings
- Nodes Stats
- Nodes Info
- Nodes Feature Usage
- Remote Cluster Info
- Task Management API
- Nodes hot_threads
- Cluster Allocation Explain API
- Query DSL
- 查詢context與過濾context
- Match All Query
- 全文搜索
- 匹配查詢
- 短語匹配查詢
- 短語前綴匹配查詢
- 多字段查詢
- 常用術語查詢
- 查詢語句查詢
- 簡單查詢語句
- Term level queries
- Term Query
- Terms Query
- Range Query
- Exists Query
- Prefix Query
- Wildcard Query
- Regexp Query
- Fuzzy Query
- Type Query
- Ids Query
- 復合查詢
- Constant Score 查詢
- Bool 查詢
- Dis Max 查詢
- Function Score 查詢
- Boosting 查詢
- Joining queries
- Has Child Query
- Has Parent Query
- Nested Query(嵌套查詢)
- Parent Id Query
- Geo queries
- GeoShape Query(地理形狀查詢)
- Geo Bounding Box Query(地理邊框查詢)
- Geo Distance Query(地理距離查詢)
- Geo Polygon Query(地理多邊形查詢)
- Specialized queries
- More Like This Query
- Script Query
- Percolate Query
- Span queries
- Span Term 查詢
- Span Multi Term 查詢
- Span First 查詢
- Span Near 查詢
- Span Or 查詢
- Span Not 查詢
- Span Containing 查詢
- Span Within 查詢
- Span Field Masking 查詢 轉至元數據結尾
- Minimum Should Match
- Multi Term Query Rewrite
- Mapping
- Removal of mapping types
- Field datatypes
- Array
- Binary
- Range
- Boolean
- Date
- Geo-point datatype
- Geo-Shape datatype
- IP datatype
- Keyword datatype
- Nested datatype
- Numeric datatypes
- Object datatype
- Text
- Token數
- 滲濾型
- join datatype
- Meta-Fields
- _all field
- _field_names field
- _id field
- _index field
- _meta field
- _routing field
- _source field
- _type field
- _uid field
- Mapping parameters
- analyzer(分析器)
- normalizer(歸一化)
- boost(提升)
- Coerce(強制類型轉換)
- copy_to(合并參數)
- doc_values(文檔值)
- dynamic(動態設置)
- enabled(開啟字段)
- eager_global_ordinals
- fielddata(字段數據)
- format (日期格式)
- ignore_above(忽略超越限制的字段)
- ignore_malformed(忽略格式不對的數據)
- index (索引)
- index_options(索引設置)
- fields(字段)
- Norms (標準信息)
- null_value(空值)
- position_increment_gap(短語位置間隙)
- properties (屬性)
- search_analyzer (搜索分析器)
- similarity (匹配方法)
- store(存儲)
- Term_vectors(詞根信息)
- Dynamic Mapping
- Dynamic field mapping(動態字段映射)
- Dynamic templates(動態模板)
- default mapping(mapping中的_default_)
- Analysis
- Anatomy of an analyzer(分析器的分析)
- Testing analyzers(測試分析器)
- Analyzers(分析器)
- Configuring built-in analyzers(配置內置分析器)
- Standard Analyzer(標準分析器)
- Simple Analyzer(簡單分析器)
- 空白分析器
- Stop Analyzer
- Keyword Analyzer
- 模式分析器
- 語言分析器
- 指紋分析器
- 自定義分析器
- Normalizers
- Tokenizers(分詞器)
- Standard Tokenizer(標準分詞器)
- Letter Tokenizer
- Lowercase Tokenizer (小寫分詞器)
- Whitespace Analyzer
- UAX URL Email Tokenizer
- Classic Tokenizer
- Thai Tokenizer(泰語分詞器)
- NGram Tokenizer
- Edge NGram Tokenizer
- Keyword Analyzer
- Pattern Tokenizer
- Simple Pattern Tokenizer
- Simple Pattern Split Tokenizer
- Path Hierarchy Tokenizer(路徑層次分詞器)
- Token Filters(詞元過濾器)
- Standard Token Filter
- ASCII Folding Token Filter
- Flatten Graph Token Filter
- Length Token Filter
- Lowercase Token Filter
- Uppercase Token Filter
- NGram Token Filter
- Edge NGram Token Filter
- Porter Stem Token Filter
- Shingle Token Filter
- Stop Token Filter
- Word Delimiter Token Filter
- Word Delimiter Graph Token Filter
- Stemmer Token Filter
- Stemmer Override Token Filter
- Keyword Marker Token Filter
- Keyword Repeat Token Filter
- KStem Token Filter
- Snowball Token Filter
- Phonetic Token Filter
- Synonym Token Filter
- Synonym Graph Token Filter
- Compound Word Token Filters
- Reverse Token Filter
- Elision Token Filter
- Truncate Token Filter
- Unique Token Filter
- Pattern Capture Token Filter
- Pattern Replace Token Filter
- Trim Token Filter
- Limit Token Count Token Filter
- Hunspell Token Filter
- Common Grams Token Filter
- Normalization Token Filter
- CJK Width Token Filter
- CJK Bigram Token Filter
- Delimited Payload Token Filter
- Keep Words Token Filter
- Keep Types Token Filter
- Classic Token Filter
- Apostrophe Token Filter
- Decimal Digit Token Filter
- Fingerprint Token Filter
- Minhash Token Filter
- Character Filters(字符過濾器)
- HTML Strip Character Filter
- Mapping Character Filter
- Pattern Replace Character Filter
- 模塊
- Cluster
- 集群級路由和碎片分配
- 基于磁盤的分片分配
- 分片分配awareness
- 分片分配過濾
- Miscellaneous cluster settings
- Scripting
- Painless Scripting Language
- Lucene Expressions Language
- Advanced scripts using script engines
- Snapshot And Restore
- Thread Pool
- Index Modules(索引模塊)
- 預處理節點
- Pipeline Definition
- Ingest APIs
- Put Pipeline API
- Get Pipeline API
- Delete Pipeline API
- Simulate Pipeline API
- Accessing Data in Pipelines
- Handling Failures in Pipelines
- Processors
- Monitoring Elasticsearch
- X-Pack APIs
- X-Pack Commands
- How To
- Testing(測試)
- Glossary of terms
- Release Notes
- X-Pack Release Notes