获取集合的所有文档id的RavenDB以进行“perdocument”修改

2024-04-28 03:41:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在ravendb数据库中更新我的文档。问题是我有一个方法可以更新一个文档,但是它将文档的id作为参数。 因此,我使用python:pyravenDB作为接口。在

方法如下:

def updateDocument(self,id,newAttribute)

        with self.store.open_session() as session:
            doc = session.load(id)
            doc.newAttribute= newAttribute
            session.save_changes()

我的想法是我将使用一个简单的for循环和目标集合的所有id,并调用updateDocument方法。在

我认为有一个updatebyindex方法,但是我不知道如何使它适应我的用例。在

我怎样才能得到这个?在

谢谢!在


Tags: 方法store文档selfid数据库参数doc
2条回答

就像maqduni说的,update_by_index是你想要使用的方法。 只需创建一个索引来索引所需的文档。 如果您遇到麻烦,您可以尝试查询您想要的文档,然后ravendb将为您创建自动索引。创建索引后,只需使用index_name和{}调用{}(只需确保索引没有过时

您的代码需要如下所示:

from pyravendb.data.indexes import IndexQuery
from pyravendb.data.patches import ScriptedPatchRequest
   self.store.database_commands.update_by_index(index_name="YOUR_INDEX_NAME",
        query=IndexQuery(query="TAG:collection_name;"),
        scripted_patch=ScriptedPatchRequest("this.Attribute = newAttribute;"))

IndexQuery中的查询是lucene语法,索引中的example标记是my collection names。scripted_patch使用js语法,这是将在您查询的每个文档上运行的脚本。在

我将试图解释两者之间的区别:

get_index方法将为您提供有关索引的信息响应是IndexDefinition。在

update_by_index是一个很长的任务操作,这就是为什么您只得到operation_id的原因,您需要等待它完成。(将在下一个pyravendb版本中为此提供一个特性)。 此操作不会提供修补的文档。新功能将为您提供有关该过程的信息。在

page_size只用于查询结果而不是用于索引操作

我不是Python专家,但是快速查看PyRavenDb的源代码,我可以找到在database_commands.py中定义的^{}。在

语法与等价的C# command的语法一样

def update_by_index(self, index_name, query, scripted_patch=None, options=None):
    """
    @param index_name: name of an index to perform a query on
    :type str
    @param query: query that will be performed
    :type IndexQuery
    @param options: various operation options e.g. AllowStale or MaxOpsPerSec
    :type BulkOperationOptions
    @param scripted_patch: JavaScript patch that will be executed on query results( Used only when update)
    :type ScriptedPatchRequest
    @return: json
    :rtype: dict
    """
    if not isinstance(query, IndexQuery):
        raise ValueError("query must be IndexQuery Type")
    path = Utils.build_path(index_name, query, options)
    if scripted_patch:
        if not isinstance(scripted_patch, ScriptedPatchRequest):
            raise ValueError("scripted_patch must be ScriptedPatchRequest Type")
        scripted_patch = scripted_patch.to_json()

    response = self._requests_handler.http_request_handler(path, "EVAL", data=scripted_patch)
    if response.status_code != 200 and response.status_code != 202:
        raise response.raise_for_status()
    return response.json()

该函数接受索引的名称用于查找待更新文档的查询,以及用于修改文档数据的JavaScript补丁。在

如果需要更新特定集合的所有文档,请考虑使用Raven/DocumentsByEntityName索引更新它们。它是一个自动创建的系统索引,它保存对整个数据库中所有文档的引用。因此,您可以编写一个查询来查找包含标记的所有文档,该标记的值对应于您的集合的名称,例如Query = "Tag:Groups",并将查询传递到update_by_index方法中。在

您还可以通过batch命令完成文档的更新,该命令也在database_commands.py和文档化的here中定义。注意:这只适用于你知道文件的ID。

如果您对C示例感兴趣,可以使用我在去年访问达拉斯的RavenDB会议后创建的演示项目。在

相关问题 更多 >