UPDATE 命令用于将指定表中现有文档的行式属性值更改为新值。请注意,您不能更新全文字段或列式属性的内容。如果有此类需求,请使用 REPLACE。
属性更新支持 RT、PQ 和普通表。只要属性存储在行式存储中,所有属性类型都可以更新。
请注意,文档 ID 不能被更新。
需要注意的是,更新属性会禁用其二级索引。如果维护二级索引的连续性至关重要,请考虑完全或部分替换文档。
关于 UPDATE 与部分 REPLACE 的更多信息,请参见这里。
- SQL
- JSON
- PHP
- Python
- Python-asyncio
- javascript
- Java
- C#
- Rust
- TypeScript
- Go
UPDATE products SET enabled=0 WHERE id=10;POST /update
{
"table":"products",
"id":10,
"doc":
{
"enabled":0
}
}$index->updateDocument([
'enabled'=>0
],10);indexApi = api = manticoresearch.IndexApi(client)
indexApi.update({"table" : "products", "id" : 1, "doc" : {"price":10}})indexApi = api = manticoresearch.IndexApi(client)
await indexApi.update({"table" : "products", "id" : 1, "doc" : {"price":10}})res = await indexApi.update({"table" : "products", "id" : 1, "doc" : {"price":10}});UpdateDocumentRequest updateRequest = new UpdateDocumentRequest();
doc = new HashMap<String,Object >(){{
put("price",10);
}};
updateRequest.index("products").id(1L).setDoc(doc);
indexApi.update(updateRequest);Dictionary<string, Object> doc = new Dictionary<string, Object>();
doc.Add("price", 10);
UpdateDocumentRequest updateRequest = new UpdateDocumentRequest(index: "products", id: 1, doc: doc);
indexApi.Update(updateRequest);let mut doc = HashMap::new();
doc.insert("price".to_string(), serde_json::json!(10));
let update_req = UpdateDocumentRequest {
table: serde_json::json!("products"),
doc: serde_json::json!(doc),
id: serde_json::json!(1),
..Default::default(),
};
let update_res = index_api.update(update_req).await;res = await indexApi.update({ index: "test", id: 1, doc: { cat: 10 } });updateDoc = map[string]interface{} {"cat":10}
updateRequest = openapiclient.NewUpdateDocumentRequest("test", updateDoc)
updateRequest.SetId(1)
res, _, _ = apiClient.IndexAPI.Update(context.Background()).UpdateDocumentRequest(*updateRequest).Execute()Query OK, 1 row affected (0.00 sec){
"table":"products",
"updated":1
}Array(
[_index] => products
[_id] => 10
[result] => updated
){'id': 1, 'table': 'products', 'result': 'updated', 'updated': None}{'id': 1, 'table': 'products', 'result': 'updated', 'updated': None}{"table":"products","_id":1,"result":"updated"}class UpdateResponse {
index: products
updated: null
id: 1
result: updated
}class UpdateResponse {
index: products
updated: null
id: 1
result: updated
}class UpdateResponse {
index: products
updated: null
id: 1
result: updated
}{
"table":"test",
"_id":1,
"result":"updated"
}{
"table":"test",
"_id":1,
"result":"updated"
}单条语句中可以更新多个属性。示例:
- SQL
- JSON
- PHP
- Python
- Python-asyncio
- javascript
- Java
- C#
- Rust
- TypeScript
- Go
UPDATE products
SET price=100000000000,
coeff=3465.23,
tags1=(3,6,4),
tags2=()
WHERE MATCH('phone') AND enabled=1;POST /update
{
"table":"products",
"doc":
{
"price":100000000000,
"coeff":3465.23,
"tags1":[3,6,4],
"tags2":[]
},
"query":
{
"match": { "*": "phone" },
"equals": { "enabled": 1 }
}
}$query= new BoolQuery();
$query->must(new Match('phone','*'));
$query->must(new Equals('enabled',1));
$index->updateDocuments([
'price' => 100000000000,
'coeff' => 3465.23,
'tags1' => [3,6,4],
'tags2' => []
],
$query
);indexApi = api = manticoresearch.IndexApi(client)
indexApi.update({"table" : "products", "id" : 1, "doc" : {
"price": 100000000000,
"coeff": 3465.23,
"tags1": [3,6,4],
"tags2": []}})indexApi = api = manticoresearch.IndexApi(client)
await indexApi.update({"table" : "products", "id" : 1, "doc" : {
"price": 100000000000,
"coeff": 3465.23,
"tags1": [3,6,4],
"tags2": []}})res = await indexApi.update({"table" : "products", "id" : 1, "doc" : {
"price": 100000000000,
"coeff": 3465.23,
"tags1": [3,6,4],
"tags2": []}});UpdateDocumentRequest updateRequest = new UpdateDocumentRequest();
doc = new HashMap<String,Object >(){{
put("price",10);
put("coeff",3465.23);
put("tags1",new int[]{3,6,4});
put("tags2",new int[]{});
}};
updateRequest.index("products").id(1L).setDoc(doc);
indexApi.update(updateRequest);Dictionary<string, Object> doc = new Dictionary<string, Object>();
doc.Add("price", 10);
doc.Add("coeff", 3465.23);
doc.Add("tags1", new List<int> {3,6,4});
doc.Add("tags2", new List<int> {});
UpdateDocumentRequest updateRequest = new UpdateDocumentRequest(index: "products", id: 1, doc: doc);
indexApi.Update(updateRequest);let mut doc = HashMap::new();
doc.insert("price".to_string(), serde_json::json!(10));
doc.insert("coeff".to_string(), serde_json::json!(3465.23));
doc.insert("tags1".to_string(), serde_json::json!([3,6,4]));
doc.insert("tags2".to_string(), serde_json::json!([]));
let update_req = UpdateDocumentRequest {
table: serde_json::json!("products"),
doc: serde_json::json!(doc),
id: serde_json::json!(1),
..Default::default(),
};
let update_res = index_api.update(update_req).await;res = await indexApi.update({ index: "test", id: 1, doc: { name: "Doc 21", cat: "10" } });updateDoc = map[string]interface{} {"name":"Doc 21", "cat":10}
updateRequest = manticoreclient.NewUpdateDocumentRequest("test", updateDoc)
updateRequest.SetId(1)
res, _, _ = apiClient.IndexAPI.Update(context.Background()).UpdateDocumentRequest(*updateRequest).Execute()Query OK, 148 rows affected (0.0 sec){
"table":"products",
"updated":148
}Array(
[_index] => products
[updated] => 148
){'id': 1, 'table': 'products', 'result': 'updated', 'updated': None}{'id': 1, 'table': 'products', 'result': 'updated', 'updated': None}{"table":"products","_id":1,"result":"updated"}class UpdateResponse {
index: products
updated: null
id: 1
result: updated
}class UpdateResponse {
index: products
updated: null
id: 1
result: updated
}class UpdateResponse {
index: products
updated: null
id: 1
result: updated
}{
"table":"test",
"_id":1,
"result":"updated"
}{
"table":"test",
"_id":1,
"result":"updated"
}当给 32 位属性赋予超出范围的值时,它们会被截断为其低 32 位,且不会有提示。例如,如果您尝试用值 4294967297 更新 32 位无符号整数,实际存储的值将是 1,因为 4294967297(十六进制为 0x100000001)的低 32 位是 1(十六进制为 0x00000001)。
UPDATE 可用于对数值数据类型或数值数据类型数组执行部分 JSON 更新。只需确保不要用浮点数值更新整数值,因为浮点数会被四舍五入。
- SQL
- JSON
- PHP
- Python
- Python-asyncio
- javascript
- Java
- C#
- Rust
- TypeScript
- Go
insert into products (id, title, meta) values (1,'title','{"tags":[1,2,3]}');
update products set meta.tags[0]=100 where id=1;POST /insert
{
"table":"products",
"id":100,
"doc":
{
"title":"title",
"meta": {
"tags":[1,2,3]
}
}
}
POST /update
{
"table":"products",
"id":100,
"doc":
{
"meta.tags[0]":100
}
}$index->insertDocument([
'title' => 'title',
'meta' => ['tags' => [1,2,3]]
],1);
$index->updateDocument([
'meta.tags[0]' => 100
],1);indexApi = api = manticoresearch.IndexApi(client)
indexApi.update({"table" : "products", "id" : 1, "doc" : {
"meta.tags[0]": 100}})indexApi = api = manticoresearch.IndexApi(client)
await indexApi.update({"table" : "products", "id" : 1, "doc" : {
"meta.tags[0]": 100}})res = await indexApi.update({"table" : "products", "id" : 1, "doc" : {
"meta.tags[0]": 100}});UpdateDocumentRequest updateRequest = new UpdateDocumentRequest();
doc = new HashMap<String,Object >(){{
put("meta.tags[0]",100);
}};
updateRequest.index("products").id(1L).setDoc(doc);
indexApi.update(updateRequest);Dictionary<string, Object> doc = new Dictionary<string, Object>();
doc.Add("meta.tags[0]", 100);
UpdateDocumentRequest updateRequest = new UpdateDocumentRequest(index: "products", id: 1, doc: doc);
indexApi.Update(updateRequest);let mut doc = HashMap::new();
doc.insert("meta.tags[0]".to_string(), serde_json::json!(100));
let update_req = UpdateDocumentRequest {
table: serde_json::json!("products"),
doc: serde_json::json!(doc),
id: serde_json::json!(1),
..Default::default(),
};
let update_res = index_api.update(update_req).await;res = await indexApi.update({"table" : "test", "id" : 1, "doc" : { "meta.tags[0]": 100} });updateDoc = map[string]interface{} {"meta.tags[0]":100}
updateRequest = manticoreclient.NewUpdateDocumentRequest("test", updateDoc)
updateRequest.SetId(1)
res, _, _ = apiClient.IndexAPI.Update(context.Background()).UpdateDocumentRequest(*updateRequest).Execute()Query OK, 1 row affected (0.00 sec)
Query OK, 1 row affected (0.00 sec){
"table":"products",
"_id":100,
"created":true,
"result":"created",
"status":201
}
{
"table":"products",
"updated":1
}Array(
[_index] => products
[_id] => 1
[created] => true
[result] => created
)
Array(
[_index] => products
[updated] => 1
){'id': 1, 'table': 'products', 'result': 'updated', 'updated': None}{'id': 1, 'table': 'products', 'result': 'updated', 'updated': None}{"table":"products","_id":1,"result":"updated"}class UpdateResponse {
index: products
updated: null
id: 1
result: updated
}class UpdateResponse {
index: products
updated: null
id: 1
result: updated
}class UpdateResponse {
index: products
updated: null
id: 1
result: updated
}{"table":"test","_id":1,"result":"updated"}{
"table":"test",
"_id":1,
"result":"updated"
}更新其他数据类型或更改 JSON 属性中的属性类型需要进行完整的 JSON 更新。
- SQL
- JSON
- PHP
- Python
- Python-asyncio
- javascript
- Java
- C#
- Rust
- TypeScript
- Go
insert into products values (1,'title','{"tags":[1,2,3]}');
update products set data='{"tags":["one","two","three"]}' where id=1;POST /insert
{
"table":"products",
"id":1,
"doc":
{
"title":"title",
"data":"{\"tags\":[1,2,3]}"
}
}
POST /update
{
"table":"products",
"id":1,
"doc":
{
"data":"{\"tags\":[\"one\",\"two\",\"three\"]}"
}
}$index->insertDocument([
'title'=> 'title',
'data' => [
'tags' => [1,2,3]
]
],1);
$index->updateDocument([
'data' => [
'one', 'two', 'three'
]
],1);indexApi.insert({"table" : "products", "id" : 100, "doc" : {"title" : "title", "meta" : {"tags":[1,2,3]}}})
indexApi.update({"table" : "products", "id" : 100, "doc" : {"meta" : {"tags":['one','two','three']}}})await indexApi.insert({"table" : "products", "id" : 100, "doc" : {"title" : "title", "meta" : {"tags":[1,2,3]}}})
await indexApi.update({"table" : "products", "id" : 100, "doc" : {"meta" : {"tags":['one','two','three']}}})res = await indexApi.insert({"table" : "products", "id" : 100, "doc" : {"title" : "title", "meta" : {"tags":[1,2,3]}}});
res = await indexApi.update({"table" : "products", "id" : 100, "doc" : {"meta" : {"tags":['one','two','three']}}});InsertDocumentRequest newdoc = new InsertDocumentRequest();
doc = new HashMap<String,Object>(){{
put("title","title");
put("meta",
new HashMap<String,Object>(){{
put("tags",new int[]{1,2,3});
}});
}};
newdoc.index("products").id(100L).setDoc(doc);
indexApi.insert(newdoc);
updatedoc = new UpdateDocumentRequest();
doc = new HashMap<String,Object >(){{
put("meta",
new HashMap<String,Object>(){{
put("tags",new String[]{"one","two","three"});
}});
}};
updatedoc.index("products").id(100L).setDoc(doc);
indexApi.update(updatedoc);Dictionary<string, Object> meta = new Dictionary<string, Object>();
meta.Add("tags", new List<int> {1,2,3});
Dictionary<string, Object> doc = new Dictionary<string, Object>();
doc.Add("title", "title");
doc.Add("meta", meta);
InsertDocumentRequest newdoc = new InsertDocumentRequest(index: "products", id: 100, doc: doc);
indexApi.Insert(newdoc);
meta = new Dictionary<string, Object>();
meta.Add("tags", new List<string> {"one","two","three"});
doc = new Dictionary<string, Object>();
doc.Add("meta", meta);
UpdateDocumentRequest updatedoc = new UpdateDocumentRequest(index: "products", id: 100, doc: doc);
indexApi.Update(updatedoc);let mut meta = HashMap::new();
meta.insert("tags".to_string(), serde_json::json!([1,2,3]));
let mut doc = HashMap::new();
doc.insert("title".to_string(), serde_json::json!("title"));
doc.insert("meta".to_string(), serde_json::json!(meta));
let insert_req = InsertDocumentRequest {
table: serde_json::json!("products"),
doc: serde_json::json!(doc),
id: serde_json::json!(100),
..Default::default(),
};
let insert_res = index_api.insert(insert_req).await;
meta = HashMap::new();
meta.insert("tags".to_string(), serde_json::json!(["one","two","three"]));
doc = HashMap::new();
doc.insert("meta".to_string(), serde_json::json!(meta));
let update_req = UpdateDocumentRequest {
table: serde_json::json!("products"),
doc: serde_json::json!(doc),
id: serde_json::json!(100),
..Default::default(),
};
let update_res = index_api.update(update_req).await;res = await indexApi.insert({
index: 'test',
id: 1,
doc: { content: 'Text 1', name: 'Doc 1', meta: { tags:[1,2,3] } }
})
res = await indexApi.update({ index: 'test', id: 1, doc: { meta: { tags:['one','two','three'] } } });metaField := map[string]interface{} {"tags": []int{1, 2, 3}}
insertDoc := map[string]interface{} {"name": "Doc 1", "meta": metaField}}
insertRequest := manticoreclient.NewInsertDocumentRequest("test", insertDoc)
insertRequest.SetId(1)
res, _, _ := apiClient.IndexAPI.Insert(context.Background()).InsertDocumentRequest(*insertRequest).Execute();
metaField = map[string]interface{} {"tags": []string{"one", "two", "three"}}
updateDoc := map[string]interface{} {"meta": metaField}
updateRequest := manticoreclient.NewUpdateDocumentRequest("test", updateDoc)
res, _, _ = apiClient.IndexAPI.Update(context.Background()).UpdateDocumentRequest(*updateRequest).Execute()Query OK, 1 row affected (0.00 sec)
Query OK, 1 row affected (0.00 sec){
"table":"products",
"updated":1
}Array(
[_index] => products
[_id] => 1
[created] => true
[result] => created
)
Array(
[_index] => products
[updated] => 1
){'created': True,
'found': None,
'id': 100,
'table': 'products',
'result': 'created'}
{'id': 100, 'table': 'products', 'result': 'updated', 'updated': None}{'created': True,
'found': None,
'id': 100,
'table': 'products',
'result': 'created'}
{'id': 100, 'table': 'products', 'result': 'updated', 'updated': None}{"table":"products","_id":100,"created":true,"result":"created"}
{"table":"products","_id":100,"result":"updated"}class SuccessResponse {
index: products
id: 100
created: true
result: created
found: null
}
class UpdateResponse {
index: products
updated: null
id: 100
result: updated
}class SuccessResponse {
index: products
id: 100
created: true
result: created
found: null
}
class UpdateResponse {
index: products
updated: null
id: 100
result: updated
}class SuccessResponse {
index: products
id: 100
created: true
result: created
found: null
}
class UpdateResponse {
index: products
updated: null
id: 100
result: updated
}{
"table":"test",
"_id":1,
"created":true,
"result":"created"
}
{
"table":"test",
"_id":1,
"result":"updated"
}{
"table":"test",
"_id":1,
"created":true,
"result":"created"
}
{
"table":"test",
"_id":1,
"result":"updated"
}When using replication, the table name should be prepended with cluster_name: (in SQL) so that updates will be propagated to all nodes in the cluster. For queries via HTTP, you should set a cluster property. See setting up replication for more information.
{
"cluster":"nodes4",
"table":"test",
"id":1,
"doc":
{
"gid" : 100,
"price" : 1000
}
}
- SQL
- JSON
- PHP
- Python
- Python-asyncio
- javascript
- Java
- C#
- Rust
- TypeScript
- Go
update weekly:posts set enabled=0 where id=1;POST /update
{
"cluster":"weekly",
"table":"products",
"id":1,
"doc":
{
"enabled":0
}
}$index->setName('products')->setCluster('weekly');
$index->updateDocument(['enabled'=>0],1);indexApi.update({"cluster":"weekly", "table" : "products", "id" : 1, "doc" : {"enabled" : 0}})await indexApi.update({"cluster":"weekly", "table" : "products", "id" : 1, "doc" : {"enabled" : 0}})res = wait indexApi.update({"cluster":"weekly", "table" : "products", "id" : 1, "doc" : {"enabled" : 0}});updatedoc = new UpdateDocumentRequest();
doc = new HashMap<String,Object >(){{
put("enabled",0);
}};
updatedoc.index("products").cluster("weekly").id(1L).setDoc(doc);
indexApi.update(updatedoc);Dictionary<string, Object> doc = new Dictionary<string, Object>();
doc.Add("enabled", 0);
UpdateDocumentRequest updatedoc = new UpdateDocumentRequest(index: "products", cluster: "weekly", id: 1, doc: doc);
indexApi.Update(updatedoc);let mut doc = HashMap::new();
doc.insert("enabled".to_string(), serde_json::json!(0));
let update_req = UpdateDocumentRequest {
table: serde_json::json!("products"),
cluster: serde_json::json!("weekly"),
doc: serde_json::json!(doc),
id: serde_json::json!(1),
};
let update_res = index_api.update(update_req).await;res = wait indexApi.update( {cluster: 'test_cluster', index : 'test', id : 1, doc : {name : 'Doc 11'}} );updateDoc = map[string]interface{} {"name":"Doc 11"}
updateRequest = manticoreclient.NewUpdateDocumentRequest("test", updateDoc)
updateRequest.SetCluster("test_cluster")
updateRequest.SetId(1)
res, _, _ = apiClient.IndexAPI.Update(context.Background()).UpdateDocumentRequest(*updateRequest).Execute()Here is the syntax for the SQL UPDATE statement:
UPDATE table SET col1 = newval1 [, ...] WHERE where_condition [OPTION opt_name = opt_value [, ...]] [FORCE|IGNORE INDEX(id)]
where_condition has the same syntax as in the SELECT statement.
Multi-value attribute value sets must be specified as comma-separated lists in parentheses. To remove all values from a multi-value attribute, just assign () to it.
- SQL
- JSON
- PHP
- Python
- Python-asyncio
- javascript
- Java
- C#
- Rust
- TypeScript
- Go
UPDATE products SET tags1=(3,6,4) WHERE id=1;
UPDATE products SET tags1=() WHERE id=1;POST /update
{
"table":"products",
"_id":1,
"doc":
{
"tags1": []
}
}$index->updateDocument(['tags1'=>[]],1);indexApi.update({"table" : "products", "id" : 1, "doc" : {"tags1": []}})await indexApi.update({"table" : "products", "id" : 1, "doc" : {"tags1": []}})indexApi.update({"table" : "products", "id" : 1, "doc" : {"tags1": []}})updatedoc = new UpdateDocumentRequest();
doc = new HashMap<String,Object >(){{
put("tags1",new int[]{});
}};
updatedoc.index("products").id(1L).setDoc(doc);
indexApi.update(updatedoc);Dictionary<string, Object> doc = new Dictionary<string, Object>();
doc.Add("tags1", new List<int> {});
UpdateDocumentRequest updatedoc = new UpdateDocumentRequest(index: "products", id: 1, doc: doc);
indexApi.Update(updatedoc);let mut doc = HashMap::new();
doc.insert("tags1".to_string(), serde_json::json!([]));
let update_req = UpdateDocumentRequest {
table: serde_json::json!("products"),
doc: serde_json::json!(doc),
id: serde_json::json!(1),
..Default::default(),
};
let update_res = index_api.update(update_req).await;res = await indexApi.update({ index: 'test', id: 1, doc: { cat: 10 } });updateDoc = map[string]interface{} {"cat":10}
updateRequest = manticoreclient.NewUpdateDocumentRequest("test", updateDoc)
updateRequest.SetId(1)
res, _, _ = apiClient.IndexAPI.Update(context.Background()).UpdateDocumentRequest(*updateRequest).Execute()Query OK, 1 row affected (0.00 sec)
Query OK, 1 row affected (0.00 sec){
"table":"products",
"updated":1
}Array(
[_index] => products
[updated] => 1
){'id': 1, 'table': 'products', 'result': 'updated', 'updated': None}{'id': 1, 'table': 'products', 'result': 'updated', 'updated': None}{"table":"products","_id":1,"result":"updated"}class UpdateResponse {
index: products
updated: null
id: 1
result: updated
}class UpdateResponse {
index: products
updated: null
id: 1
result: updated
}class UpdateResponse {
index: products
updated: null
id: 1
result: updated
}{
"table":"test",
"_id":1,
"result":"updated"
}{
"table":"test",
"_id":1,
"result":"updated"
}OPTION clause is a Manticore-specific extension that lets you control a number of per-update options. The syntax is:
OPTION <optionname>=<value> [ , ... ]
The options are the same as for the SELECT statement. Specifically for the UPDATE statement, you can use these options:
- 'ignore_nonexistent_columns' - If set to 1, it indicates that the update will silently ignore any warnings about trying to update a column which does not exist in the current table schema. The default value is 0.
- 'strict' - This option is used in partial JSON attribute updates. By default (strict=1),
UPDATEwill result in an error if theUPDATEquery tries to perform an update on non-numeric properties. With strict=0, if multiple properties are updated and some are not allowed, theUPDATEwill not result in an error and will perform the changes only on allowed properties (with the rest being ignored). If none of theSETchanges of theUPDATEre permitted, the command will result in an error even with strict=0.
In rare cases, Manticore's built-in query analyzer may be incorrect in understanding a query and determining whether a table by ID should be used. This can result in poor performance for queries like UPDATE ... WHERE id = 123.
For information on how to force the optimizer to use a docid index, see Query optimizer hints.
Updates using HTTP JSON protocol are performed via the /update endpoint. The syntax is similar to the /insert endpoint, but this time the doc property is mandatory.
The server will respond with a JSON object stating if the operation was successful or not.
- JSON
POST /update
{
"table":"test",
"id":1,
"doc":
{
"gid" : 100,
"price" : 1000
}
}{
"table": "test",
"_id": 1,
"result": "updated"
}The ID of the document that needs to be updated can be set directly using the id property, as shown in the previous example, or you can update documents by query and apply the update to all the documents that match the query:
- JSON
POST /update
{
"table":"test",
"doc":
{
"price" : 1000
},
"query":
{
"match": { "*": "apple" }
}
}{
"table":"products",
"updated":1
}查询语法与/search endpoint中的相同。请注意,不能同时指定id和query。
FLUSH ATTRIBUTES
FLUSH ATTRIBUTES命令确保所有活动表中内存中的属性更新都被刷新到磁盘。它返回一个标记,标识结果的磁盘状态,该标记表示自服务器启动以来实际执行的磁盘属性保存次数。
mysql> UPDATE testindex SET channel_id=1107025 WHERE id=1;
Query OK, 1 row affected (0.04 sec)
mysql> FLUSH ATTRIBUTES;
+------+
| tag |
+------+
| 1 |
+------+
1 row in set (0.19 sec)
另请参见attr_flush_period设置。
您可以使用/bulk端点在一次调用中执行多个更新操作。此端点仅适用于Content-Type设置为application/x-ndjson的数据。数据应格式化为换行分隔的JSON(NDJSON)。本质上,这意味着每行应包含一个JSON语句,并以换行符\n结束,可能还有\r。
- JSON
POST /bulk
{ "update" : { "table" : "products", "id" : 1, "doc": { "price" : 10 } } }
{ "update" : { "table" : "products", "id" : 2, "doc": { "price" : 20 } } }{
"items":
[
{
"update":
{
"table":"products",
"_id":1,
"result":"updated"
}
},
{
"update":
{
"table":"products",
"_id":2,
"result":"updated"
}
}
],
"errors":false
}/bulk端点支持插入、替换和删除。每个语句以操作类型开始(此处为update)。以下是支持的操作列表:
insert:插入文档。语法与/insert endpoint相同。create:insert的同义词replace:替换文档。语法与/replace相同。index:replace的同义词update:更新文档。语法与/update相同。delete:删除文档。语法与/delete endpoint相同。
也支持通过查询进行更新和删除。
- JSON
- PHP
- Python
- Python-asyncio
- javascript
- Java
- C#
- Rust
- TypeScript
- Go
POST /bulk
{ "update" : { "table" : "products", "doc": { "coeff" : 1000 }, "query": { "range": { "price": { "gte": 1000 } } } } }
{ "update" : { "table" : "products", "doc": { "coeff" : 0 }, "query": { "range": { "price": { "lt": 1000 } } } } }$client->bulk([
['update'=>[
'table' => 'products',
'doc' => [
'coeff' => 100
],
'query' => [
'range' => ['price'=>['gte'=>1000]]
]
]
],
['update'=>[
'table' => 'products',
'doc' => [
'coeff' => 0
],
'query' => [
'range' => ['price'=>['lt'=>1000]]
]
]
]
]);docs = [ \
{ "update" : { "table" : "products", "doc": { "coeff" : 1000 }, "query": { "range": { "price": { "gte": 1000 } } } } }, \
{ "update" : { "table" : "products", "doc": { "coeff" : 0 }, "query": { "range": { "price": { "lt": 1000 } } } } } ]
indexApi.bulk('\n'.join(map(json.dumps,docs)))docs = [ \
{ "update" : { "table" : "products", "doc": { "coeff" : 1000 }, "query": { "range": { "price": { "gte": 1000 } } } } }, \
{ "update" : { "table" : "products", "doc": { "coeff" : 0 }, "query": { "range": { "price": { "lt": 1000 } } } } } ]
await indexApi.bulk('\n'.join(map(json.dumps,docs)))docs = [
{ "update" : { "table" : "products", "doc": { "coeff" : 1000 }, "query": { "range": { "price": { "gte": 1000 } } } } },
{ "update" : { "table" : "products", "doc": { "coeff" : 0 }, "query": { "range": { "price": { "lt": 1000 } } } } } ];
res = await indexApi.bulk(docs.map(e=>JSON.stringify(e)).join('\n'));String body = "{ \"update\" : { \"index\" : \"products\", \"doc\": { \"coeff\" : 1000 }, \"query\": { \"range\": { \"price\": { \"gte\": 1000 } } } }} "+"\n"+
"{ \"update\" : { \"index\" : \"products\", \"doc\": { \"coeff\" : 0 }, \"query\": { \"range\": { \"price\": { \"lt\": 1000 } } } } }"+"\n";
indexApi.bulk(body);string body = "{ \"update\" : { \"index\" : \"products\", \"doc\": { \"coeff\" : 1000 }, \"query\": { \"range\": { \"price\": { \"gte\": 1000 } } } }} "+"\n"+
"{ \"update\" : { \"index\" : \"products\", \"doc\": { \"coeff\" : 0 }, \"query\": { \"range\": { \"price\": { \"lt\": 1000 } } } } }"+"\n";
indexApi.Bulk(body);string body = r#"{ "update" : { "index" : "products", "doc": { "coeff" : 1000 }, "query": { "range": { "price": { "gte": 1000 } } } }}
{ "update" : { "index" : "products", "doc": { "coeff" : 0 }, "query": { "range": { "price": { "lt": 1000 } } } } }
"#;
index_api.bulk(body).await;updateDocs = [
{
update: {
index: 'test',
id: 1,
doc: { content: 'Text 11', cat: 1, name: 'Doc 11' },
},
},
{
update: {
index: 'test',
id: 2,
doc: { content: 'Text 22', cat: 9, name: 'Doc 22' },
},
},
];
res = await indexApi.bulk(
updateDocs.map((e) => JSON.stringify(e)).join("\n")
);body := "{\"update\": {\"index\": \"test\", \"id\": 1, \"doc\": {\"content\": \"Text 11\", \"name\": \"Doc 11\", \"cat\": 1 }}}" + "\n" +
"{\"update\": {\"index\": \"test\", \"id\": 2, \"doc\": {\"content\": \"Text 22\", \"name\": \"Doc 22\", \"cat\": 9 }}}" +"\n";
res, _, _ := apiClient.IndexAPI.Bulk(context.Background()).Body(body).Execute(){
"items":
[
{
"update":
{
"table":"products",
"updated":1
}
},
{
"update":
{
"table":"products",
"updated":3
}
}
],
"errors":false
}Array(
[items] => Array (
Array(
[update] => Array(
[_index] => products
[updated] => 1
)
)
Array(
[update] => Array(
[_index] => products
[updated] => 3
)
)
){'error': None,
'items': [{u'update': {u'table': u'products', u'updated': 1}},
{u'update': {u'table': u'products', u'updated': 3}}]}{'error': None,
'items': [{u'update': {u'table': u'products', u'updated': 1}},
{u'update': {u'table': u'products', u'updated': 3}}]}{"items":[{"update":{"table":"products","updated":1}},{"update":{"table":"products","updated":3}}],"errors":false}class BulkResponse {
items: [{update={_index=products, _id=1, created=false, result=updated, status=200}}, {update={_index=products, _id=2, created=false, result=updated, status=200}}]
error: null
additionalProperties: {errors=false}
}class BulkResponse {
items: [{update={_index=products, _id=1, created=false, result=updated, status=200}}, {update={_index=products, _id=2, created=false, result=updated, status=200}}]
error: null
additionalProperties: {errors=false}
}class BulkResponse {
items: [{update={_index=products, _id=1, created=false, result=updated, status=200}}, {update={_index=products, _id=2, created=false, result=updated, status=200}}]
error: null
additionalProperties: {errors=false}
}{
"items":
[
{
"update":
{
"table":"test",
"updated":1
}
},
{
"update":
{
"table":"test",
"updated":1
}
}
],
"errors":false
}{
"items":
[
{
"update":
{
"table":"test",
"updated":1
}
},
{
"update":
{
"table":"test",
"updated":1
}
}
],
"errors":false
}请注意,批量操作将在遇到第一个错误的查询时停止。
attr_update_reserve=size
attr_update_reserve是每个表的设置,用于确定为blob属性更新保留的空间。此设置是可选的,默认值为128k。
当blob属性(MVAs、字符串、JSON)被更新时,其长度可能会变化。如果更新后的字符串(或MVA,或JSON)比旧的短,则会覆盖.spb文件中的旧内容。然而,如果更新后的字符串更长,更新将写入.spb文件的末尾。该文件是内存映射的,这意味着根据操作系统对内存映射文件的实现,调整其大小可能是一个相当缓慢的过程。
为了避免频繁调整大小,您可以使用此选项指定在.spb文件末尾保留的额外空间。
- SQL
- JSON
- PHP
- Python
- Python-asyncio
- javascript
- Java
- C#
- Rust
- TypeScript
- Go
- CONFIG
create table products(title text, price float) attr_update_reserve = '1M'POST /cli -d "
create table products(title text, price float) attr_update_reserve = '1M'"$params = [
'body' => [
'settings' => [
'attr_update_reserve' => '1M'
],
'columns' => [
'title'=>['type'=>'text'],
'price'=>['type'=>'float']
]
],
'table' => 'products'
];
$index = new \Manticoresearch\Index($client);
$index->create($params);utilsApi.sql('create table products(title text, price float) attr_update_reserve = \'1M\'')await utilsApi.sql('create table products(title text, price float) attr_update_reserve = \'1M\'')res = await utilsApi.sql('create table products(title text, price float) attr_update_reserve = \'1M\'');utilsApi.sql("create table products(title text, price float) attr_update_reserve = '1M'", true);utilsApi.Sql("create table products(title text, price float) attr_update_reserve = '1M'", true);utils_api.sql("create table products(title text, price float) attr_update_reserve = '1M'", Some(true)).await;utilsApi.sql("create table test(content text, name string, cat int) attr_update_reserve = '1M'");apiClient.UtilsAPI.Sql(context.Background()).Body("create table test(content text, name string, cat int) attr_update_reserve = '1M'").Execute()table products {
attr_update_reserve = 1M
type = rt
path = tbl
rt_field = title
rt_attr_uint = price
}attr_flush_period = 900 # persist updates to disk every 15 minutes
更新属性时,变更首先写入属性的内存副本。此设置允许设置刷新更新到磁盘的间隔。默认值为0,表示禁用周期性刷新,但在正常关闭时仍会进行刷新。
删除文档仅在以下表类型的RT模式中支持:
您可以根据文档的 ID 或某些条件从表中删除现有文档。
此外,还提供了批量删除功能以删除多个文档。
文档的删除可以通过 SQL 和 JSON 接口完成。
对于 SQL,成功操作的响应将指示删除的行数。
对于 JSON,使用 json/delete 端点。服务器将响应一个 JSON 对象,指示操作是否成功以及删除的行数。
建议使用表截断来删除表中的所有文档,因为这是一种更快的操作。
在此示例中,我们从名为 test 的表中删除所有匹配全文查询 test document 的文档:
- SQL
- JSON
- PHP
- Python
- Python-asyncio
- javascript
- Java
- C#
- Rust
- TypeScript
- Go
mysql> SELECT * FROM TEST;
+------+------+-------------+------+
| id | gid | mva1 | mva2 |
+------+------+-------------+------+
| 100 | 1000 | 100,201 | 100 |
| 101 | 1001 | 101,202 | 101 |
| 102 | 1002 | 102,203 | 102 |
| 103 | 1003 | 103,204 | 103 |
| 104 | 1004 | 104,204,205 | 104 |
| 105 | 1005 | 105,206 | 105 |
| 106 | 1006 | 106,207 | 106 |
| 107 | 1007 | 107,208 | 107 |
+------+------+-------------+------+
8 rows in set (0.00 sec)
mysql> DELETE FROM TEST WHERE MATCH ('test document');
Query OK, 2 rows affected (0.00 sec)
mysql> SELECT * FROM TEST;
+------+------+-------------+------+
| id | gid | mva1 | mva2 |
+------+------+-------------+------+
| 100 | 1000 | 100,201 | 100 |
| 101 | 1001 | 101,202 | 101 |
| 102 | 1002 | 102,203 | 102 |
| 103 | 1003 | 103,204 | 103 |
| 104 | 1004 | 104,204,205 | 104 |
| 105 | 1005 | 105,206 | 105 |
+------+------+-------------+------+
6 rows in set (0.00 sec)POST /delete -d '
{
"table":"test",
"query":
{
"match": { "*": "test document" }
}
}'- JSON 中的
query包含全文搜索的子句;其语法与JSON/update中的相同。
$index->deleteDocuments(new MatchPhrase('test document','*'));indexApi.delete({"table" : "test", "query": { "match": { "*": "test document" }}})indexApi.delete({"table" : "test", "query": { "match": { "*": "test document" }}})res = await indexApi.delete({"table" : "test", "query": { "match": { "*": "test document" }}});DeleteDocumentRequest deleteRequest = new DeleteDocumentRequest();
query = new HashMap<String,Object>();
query.put("match",new HashMap<String,Object>(){{
put("*","test document");
}});
deleteRequest.index("test").setQuery(query);
indexApi.delete(deleteRequest);Dictionary<string, Object> match = new Dictionary<string, Object>();
match.Add("*", "test document");
Dictionary<string, Object> query = new Dictionary<string, Object>();
query.Add("match", match);
DeleteDocumentRequest deleteRequest = new DeleteDocumentRequest(index: "test", query: query);
indexApi.Delete(deleteRequest);let match_expr = HashMap::new();
match_expr.insert("*".to_string(), serde_json::json!("test document"));
let query = SearchQuery {
match: Some(serde_json::json!(match_expr).into()),
..Default::default()
};
let delete_req = DeleteDocumentRequest::new("test".to_string());
index_api.delete(delete_req).await;res = await indexApi.delete({
index: 'test',
query: { match: { '*': 'test document' } },
});deleteRequest := manticoresearch.NewDeleteDocumentRequest("test")
matchExpr := map[string]interface{} {"*": "test document"}
deleteQuery := map[string]interface{} {"match": matchExpr }
deleteRequest.SetQuery(deleteQuery){
"table":"test",
"deleted":2,
}Array(
[_index] => test
[deleted] => 2
){'deleted': 5, 'id': None, 'table': 'test', 'result': None}{'deleted': 5, 'id': None, 'table': 'test', 'result': None}{"table":"test","deleted":5}class DeleteResponse {
index: test
deleted: 5
id: null
result: null
}class DeleteResponse {
index: test
deleted: 5
id: null
result: null
}class DeleteResponse {
index: test
deleted: 5
id: null
result: null
}{"table":"test","deleted":5}{"table":"test","deleted":5}这里 - 从名为 test 的表中删除 id 等于 1 的文档:
- SQL
- JSON
- PHP
- Python
- Python-asyncio
- javascript
- Java
- C#
- Rust
- TypeScript
- Go
mysql> DELETE FROM TEST WHERE id=1;
Query OK, 1 rows affected (0.00 sec)POST /delete -d '
{
"table": "test",
"id": 1
}'- JSON 中的
id是应删除的行id。
$index->deleteDocument(1);indexApi.delete({"table" : "test", "id" : 1})indexApi.delete({"table" : "test", "id" : 1})res = await indexApi.delete({"table" : "test", "id" : 1});DeleteDocumentRequest deleteRequest = new DeleteDocumentRequest();
deleteRequest.index("test").setId(1L);
indexApi.delete(deleteRequest);DeleteDocumentRequest deleteRequest = new DeleteDocumentRequest(index: "test", id: 1);
indexApi.Delete(deleteRequest);let delete_req = DeleteDocumentRequest {
table: "test".to_string(),
id: serde_json::json!(1),
..Default::default(),
};
index_api.delete(delete_req).await;res = await indexApi.delete({ index: 'test', id: 1 });deleteRequest := manticoresearch.NewDeleteDocumentRequest("test")
deleteRequest.SetId(1){
"table": "test",
"_id": 1,
"found": true,
"result": "deleted"
}Array(
[_index] => test
[_id] => 1
[found] => true
[result] => deleted
){'deleted': None, 'id': 1, 'table': 'test', 'result': 'deleted'}{'deleted': None, 'id': 1, 'table': 'test', 'result': 'deleted'}{"table":"test","_id":1,"result":"deleted"}class DeleteResponse {
index: test
_id: 1
result: deleted
}class DeleteResponse {
index: test
_id: 1
result: deleted
}class DeleteResponse {
index: test
_id: 1
result: deleted
}{"table":"test","_id":1,"result":"deleted"}{"table":"test","_id":1,"result":"deleted"}这里,删除与名为 test 的表中值匹配的 id 的文档:
请注意,带有 id=N 或 id IN (X,Y) 的删除形式是最快的,因为它们在删除文档时不执行搜索。
还请注意,响应中仅包含对应 _id 字段中第一个被删除文档的 id。
- SQL
- JSON
- PHP
DELETE FROM TEST WHERE id IN (1,2);POST /delete -d '
{
"table":"test",
"id": [1,2]
}'$index->deleteDocumentsByIds([1,2]);Query OK, 2 rows affected (0.00 sec) {
"table":"test",
"_id":1,
"found":true,
"result":"deleted"
}Array(
[_index] => test
[_id] => 1
[found] => true
[result] => deleted
)Manticore SQL 允许对 DELETE 语句使用复杂条件。
例如,这里我们删除匹配全文查询 test document 并且属性 mva1 的值大于 206 或 mva1 值为 100 或 103 的文档,来自名为 test 的表:
- SQL
DELETE FROM TEST WHERE MATCH ('test document') AND ( mva1>206 or mva1 in (100, 103) );
SELECT * FROM TEST;Query OK, 4 rows affected (0.00 sec)
+------+------+-------------+------+
| id | gid | mva1 | mva2 |
+------+------+-------------+------+
| 101 | 1001 | 101,202 | 101 |
| 102 | 1002 | 102,203 | 102 |
| 104 | 1004 | 104,204,205 | 104 |
| 105 | 1005 | 105,206 | 105 |
+------+------+-------------+------+
6 rows in set (0.00 sec)这是在集群 cluster 的表 test 中删除文档的示例。请注意,我们必须提供集群名称属性以及表属性,才能从复制集群中的表删除行:
- SQL
- JSON
- PHP
- Python
- Python-asyncio
- javascript
- Java
- C#
- Rust
- TypeScript
- Go
delete from cluster:test where id=100;POST /delete -d '
{
"cluster": "cluster",
"table": "test",
"id": 100
}'- JSON 中的
cluster是包含所需表的复制集群的名称
$index->setCluster('cluster');
$index->deleteDocument(100);indexApi.delete({"cluster":"cluster","table" : "test", "id" : 1})indexApi.delete({"cluster":"cluster","table" : "test", "id" : 1})indexApi.delete({"cluster":"cluster_1","table" : "test", "id" : 1})DeleteDocumentRequest deleteRequest = new DeleteDocumentRequest();
deleteRequest.cluster("cluster").index("test").setId(1L);
indexApi.delete(deleteRequest);DeleteDocumentRequest deleteRequest = new DeleteDocumentRequest(index: "test", cluster: "cluster", id: 1);
indexApi.Delete(deleteRequest);let delete_req = DeleteDocumentRequest {
table: "test".to_string(),
cluster: "cluster".to_string(),
id: serde_json::json!(1),
..Default::default(),
};
index_api.delete(delete_req).await;res = await indexApi.delete({ cluster: 'cluster_1', index: 'test', id: 1 });deleteRequest := manticoresearch.NewDeleteDocumentRequest("test")
deleteRequest.SetCluster("cluster_1")
deleteRequest.SetId(1)Array(
[_index] => test
[_id] => 100
[found] => true
[result] => deleted
){'deleted': None, 'id': 1, 'table': 'test', 'result': 'deleted'}{'deleted': None, 'id': 1, 'table': 'test', 'result': 'deleted'}{"table":"test","_id":1,"result":"deleted"}class DeleteResponse {
index: test
_id: 1
result: deleted
}class DeleteResponse {
index: test
_id: 1
result: deleted
}class DeleteResponse {
index: test
_id: 1
result: deleted
}{"table":"test","_id":1,"result":"deleted"}{"table":"test","_id":1,"result":"deleted"}您还可以使用 /bulk 端点在单个调用中执行多个删除操作。此端点仅适用于 Content-Type 设置为 application/x-ndjson 的数据。数据应格式化为换行分隔的 JSON(NDJSON)。本质上,这意味着每行应包含一个完整的 JSON 语句,并以换行符 \n 结尾,可能还有一个 \r。
- JSON
- PHP
- Python
- Python-asyncio
- javascript
- Java
- C#
- Rust
- TypeScript
- Go
POST /bulk
{ "delete" : { "table" : "test", "id" : 1 } }
{ "delete" : { "table" : "test", "query": { "equals": { "int_data" : 20 } } } }$client->bulk([
['delete' => [
'table' => 'test',
'id' => 1
]
],
['delete'=>[
'table' => 'test',
'query' => [
'equals' => ['int_data' => 20]
]
]
]
]);docs = [ \
{ "delete" : { "table" : "test", "id": 1 } }, \
{ "delete" : { "table" : "test", "query": { "equals": { "int_data": 20 } } } } ]
indexApi.bulk('\n'.join(map(json.dumps,docs)))docs = [ \
{ "delete" : { "table" : "test", "id": 1 } }, \
{ "delete" : { "table" : "test", "query": { "equals": { "int_data": 20 } } } } ]
indexApi.bulk('\n'.join(map(json.dumps,docs)))docs = [
{ "delete" : { "table" : "test", "id": 1 } },
{ "delete" : { "table" : "test", "query": { "equals": { "int_data": 20 } } } } ];
res = await indexApi.bulk(docs.map(e=>JSON.stringify(e)).join('\n'));String body = "{ "delete" : { "table" : "test", "id": 1 } } "+"\n"+
"{ "delete" : { "table" : "test", "query": { "equals": { "int_data": 20 } } } }"+"\n";
indexApi.bulk(body);string body = "{ "delete" : { "table" : "test", "id": 1 } } "+"\n"+
"{ "delete" : { "table" : "test", "query": { "equals": { "int_data": 20 } } } }"+"\n";
indexApi.Bulk(body);let bulk_body = r#"{ "delete" : { "table" : "test", "id": 1 } }
{ "delete" : { "table" : "test", "query": { "equals": { "int_data": 20 } } } }"
"#;
index_api.bulk(bulk_body).await;docs = [
{ "delete" : { "table" : "test", "id": 1 } },
{ "delete" : { "table" : "test", "query": { "equals": { "int_data": 20 } } } }
];
body = await indexApi.bulk(
docs.map((e) => JSON.stringify(e)).join("\n")
);
res = await indexApi.bulk(body);docs = []string {
`{ "delete" : { "table" : "test", "id": 1 } }`,
`{ "delete" : { "table" : "test", "query": { "equals": { "int_data": 20 } } } }`
]
body = strings.Join(docs, "\n")
resp, httpRes, err := manticoreclient.IndexAPI.Bulk(context.Background()).Body(body).Execute(){
"items":
[
{
"bulk":
{
"table":"test",
"_id":0,
"created":0,
"deleted":2,
"updated":0,
"result":"created",
"status":201
}
}
],
"errors":false
}Array(
[items] => Array
(
[0] => Array
(
[bulk] => Array
(
[_index] => test
[_id] => 0
[created] => 0
[deleted] => 2
[updated] => 0
[result] => created
[status] => 201
)
)
)
[current_line] => 3
[skipped_lines] => 0
[errors] =>
[error] =>
){
'error': None,
'items': [{u'delete': {u'table': test', u'deleted': 2}}]
}{
'error': None,
'items': [{u'delete': {u'table': test', u'deleted': 2}}]
}{"items":[{"delete":{"table":"test","deleted":2}}],"errors":false}class BulkResponse {
items: [{delete={_index=test, _id=0, created=false, deleted=2, result=created, status=200}}]
error: null
additionalProperties: {errors=false}
}class BulkResponse {
items: [{replace={_index=test, _id=0, created=false, deleted=2, result=created, status=200}}]
error: null
additionalProperties: {errors=false}
}class BulkResponse {
items: [{replace={_index=test, _id=0, created=false, deleted=2, result=created, status=200}}]
error: null
additionalProperties: {errors=false}
}{"items":[{"delete":{"table":"test","deleted":2}}],"errors":false}{"items":[{"delete":{"table":"test","deleted":2}}],"errors":false}Manticore 支持对实时表和感知表进行基本的删除和插入数据的事务操作,但不支持对包含实时表或感知表的分布式表进行写操作。对表的每次更改首先保存在内部的变更集中,然后实际提交到表中。默认情况下,每个命令都被包装在一个独立的自动事务中,使其对用户透明:您只需执行“插入”操作,完成后即可看到插入的结果,无需担心事务。然而,这种行为可以通过手动启动和提交事务来显式管理。
以下命令支持事务:
以下命令不支持事务:
- UPDATE(与 REPLACE 不同,详见这里,因为它执行的是就地属性更新)
- ALTER - 用于更新表结构
- TRUNCATE - 用于清空实时表
- ATTACH - 用于将普通表附加到实时表
- CREATE - 创建表
- DROP - 删除表
请注意,Manticore 中的事务并不旨在提供隔离性。Manticore 中事务的目的是允许您累积多个写操作,并在提交时一次性执行,或者在必要时全部回滚。事务与二进制日志集成,以保证持久性和一致性。
SET AUTOCOMMIT = {0 | 1}
SET AUTOCOMMIT 控制当前会话的自动提交模式。默认情况下,AUTOCOMMIT 设置为 1。默认设置下,您无需担心事务,因为对任何表进行更改的每条语句都会隐式地包装在一个独立的事务中。将其设置为 0 则允许您手动管理事务,即事务在您显式提交之前不会生效。
事务仅限于单个实时表或感知表,并且大小有限。它们是原子性的、一致的、过度隔离的且持久的。过度隔离意味着更改不仅对并发事务不可见,甚至对当前会话本身也不可见。
START TRANSACTION | BEGIN
COMMIT
ROLLBACK
BEGIN 语句(或其别名 START TRANSACTION)会强制提交任何未完成的事务(如果存在),然后开始一个新的事务。
COMMIT 语句提交当前事务,使其所有更改永久生效。
ROLLBACK 语句回滚当前事务,取消所有更改。
使用 /bulk JSON 端点(批量插入、批量替换、批量删除)时,可以通过在文档批次后添加一个空行来强制提交该批次的文档。
insert into indexrt (id, content, title, channel_id, published) values (1, 'aa', 'blabla', 1, 10);
Query OK, 1 rows affected (0.00 sec)
select * from indexrt where id=1;
+------+------------+-----------+--------+
| id | channel_id | published | title |
+------+------------+-----------+--------+
| 1 | 1 | 10 | blabla |
+------+------------+-----------+--------+
1 row in set (0.00 sec)
插入的值在随后的 'select' 语句中立即可见。
set autocommit=0;
Query OK, 0 rows affected (0.00 sec)
insert into indexrt (id, content, title, channel_id, published) values (3, 'aa', 'bb', 1, 1);
Query OK, 1 row affected (0.00 sec)
insert into indexrt (id, content, title, channel_id, published) values (4, 'aa', 'bb', 1, 1);
Query OK, 1 row affected (0.00 sec)
select * from indexrt where id=3;
Empty set (0.01 sec)
select * from indexrt where id=4;
Empty set (0.00 sec)
在这种情况下,更改不会自动提交。因此,即使在同一会话中,插入的内容也不可见,因为它们尚未提交。尽管没有 BEGIN 语句,事务仍然隐式启动。
要使更改可见,您需要提交事务:
commit;
Query OK, 0 rows affected (0.00 sec)
select * from indexrt where id=4;
+------+------------+-----------+-------+
| id | channel_id | published | title |
+------+------------+-----------+-------+
| 4 | 1 | 1 | bb |
+------+------------+-----------+-------+
1 row in set (0.00 sec)
select * from indexrt where id=3;
+------+------------+-----------+-------+
| id | channel_id | published | title |
+------+------------+-----------+-------+
| 3 | 1 | 1 | bb |
+------+------------+-----------+-------+
1 row in set (0.00 sec)
提交语句执行后,插入的内容在表中可见。
通过使用 BEGIN 和 COMMIT,您可以显式定义事务的边界,因此无需担心自动提交。
begin;
Query OK, 0 rows affected (0.00 sec)
insert into indexrt (id, content, title, channel_id, published) values (2, 'aa', 'bb', 1, 1);
Query OK, 1 row affected (0.00 sec)
select * from indexrt where id=2;
Empty set (0.01 sec)
commit;
Query OK, 0 rows affected (0.01 sec)
select * from indexrt where id=2;
+------+------------+-----------+-------+
| id | channel_id | published | title |
+------+------------+-----------+-------+
| 2 | 1 | 1 | bb |
+------+------------+-----------+-------+
1 row in set (0.01 sec)