根据官方文档(1、2 和 3)、GitHub 和 nice article,对于您提供的示例,您应该使用以下内容:
requests.patch("https://firestore.googleapis.com/v1beta1/projects{projectId}/databases/{databaseId}/documents/{document_path}?updateMask.fieldPaths=field")
您的请求正文应为:
{
"fields": {
"field": {
"integerValue": Value
}
}
}
另外请记住,如果您想更新多个字段和值,您应该分别指定每一个。
示例:
https://firestore.googleapis.com/v1beta1/projects/{projectId}/databases/{databaseId}/documents/{document_path}?updateMask.fieldPaths=[Field1]&updateMask.fieldPaths=[Field2]
请求正文是:
{
"fields": {
"field": {
"integerValue": Value
},
"Field2": {
"stringValue": "Value2"
}
}
}
编辑:
这是我测试过的一种方法,它允许您更新文档的某些字段而不影响其余部分。
此示例代码在集合 users 下创建一个包含 4 个字段的文档,然后尝试更新 4 个字段中的 3 个(这使未提及的字段不受影响)
from google.cloud import firestore
db = firestore.Client()
#Creating a sample new Document “aturing” under collection “users”
doc_ref = db.collection(u'users').document(u'aturing')
doc_ref.set({
u'first': u'Alan',
u'middle': u'Mathison',
u'last': u'Turing',
u'born': 1912
})
#updating 3 out of 4 fields (so the last should remain unaffected)
doc_ref = db.collection(u'users').document(u'aturing')
doc_ref.update({
u'first': u'Alan',
u'middle': u'Mathison',
u'born': 2000
})
#printing the content of all docs under users
users_ref = db.collection(u'users')
docs = users_ref.stream()
for doc in docs:
print(u'{} => {}'.format(doc.id, doc.to_dict()))
编辑:2019 年 10 月 12 日
使用 REST API 进行修补
我已经重现了您的问题,但您似乎没有正确地将请求正文转换为 json 格式。
您需要使用json.dumps() 将您的请求正文转换为有效的 json 格式。
一个工作示例如下:
import requests
import json
endpoint = "https://firestore.googleapis.com/v1/projects/[PROJECT_ID]/databases/(default)/documents/[COLLECTION]/[DOCUMENT_ID]?currentDocument.exists=true&updateMask.fieldPaths=[FIELD_1]"
body = {
"fields" : {
"[FIELD_1]" : {
"stringValue" : "random new value"
}
}
}
data = json.dumps(body)
headers = {"Authorization": "Bearer [AUTH_TOKEN]"}
print(requests.patch(endpoint, data=data, headers=headers).json())