collections.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. import csv
  2. import json
  3. import logging
  4. import tempfile
  5. from typing import IO, Any, Optional
  6. from uuid import UUID, uuid4
  7. from asyncpg.exceptions import UniqueViolationError
  8. from fastapi import HTTPException
  9. from core.base import (
  10. DatabaseConfig,
  11. GraphExtractionStatus,
  12. Handler,
  13. R2RException,
  14. generate_default_user_collection_id,
  15. )
  16. from core.base.abstractions import (
  17. DocumentResponse,
  18. DocumentType,
  19. IngestionStatus,
  20. )
  21. from core.base.api.models import CollectionResponse
  22. from .base import PostgresConnectionManager
  23. logger = logging.getLogger()
  24. class PostgresCollectionsHandler(Handler):
  25. TABLE_NAME = "collections"
  26. def __init__(
  27. self,
  28. project_name: str,
  29. connection_manager: PostgresConnectionManager,
  30. config: DatabaseConfig,
  31. ):
  32. self.config = config
  33. super().__init__(project_name, connection_manager)
  34. async def create_tables(self) -> None:
  35. # 1. Create the table if it does not exist.
  36. create_table_query = f"""
  37. CREATE TABLE IF NOT EXISTS {self._get_table_name(PostgresCollectionsHandler.TABLE_NAME)} (
  38. id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  39. owner_id UUID,
  40. name TEXT NOT NULL,
  41. description TEXT,
  42. graph_sync_status TEXT DEFAULT 'pending',
  43. graph_cluster_status TEXT DEFAULT 'pending',
  44. created_at TIMESTAMPTZ DEFAULT NOW(),
  45. updated_at TIMESTAMPTZ DEFAULT NOW(),
  46. user_count INT DEFAULT 0,
  47. document_count INT DEFAULT 0
  48. );
  49. """
  50. await self.connection_manager.execute_query(create_table_query)
  51. # 2. Check for duplicate rows that would violate the uniqueness constraint.
  52. check_duplicates_query = f"""
  53. SELECT owner_id, name, COUNT(*) AS cnt
  54. FROM {self._get_table_name(PostgresCollectionsHandler.TABLE_NAME)}
  55. GROUP BY owner_id, name
  56. HAVING COUNT(*) > 1
  57. """
  58. duplicates = await self.connection_manager.fetch_query(
  59. check_duplicates_query
  60. )
  61. if duplicates:
  62. logger.warning(
  63. "Cannot add unique constraint (owner_id, name) because duplicates exist. "
  64. "Please resolve duplicates first. Found duplicates: %s",
  65. duplicates,
  66. )
  67. return # or raise an exception, depending on your use case
  68. # 3. Parse the qualified table name into schema and table.
  69. qualified_table = self._get_table_name(
  70. PostgresCollectionsHandler.TABLE_NAME
  71. )
  72. if "." in qualified_table:
  73. # Remove the quotes from schema and table names
  74. schema_with_quotes, table_with_quotes = qualified_table.split(
  75. ".", 1
  76. )
  77. schema = schema_with_quotes.replace('"', "")
  78. table = table_with_quotes.replace('"', "")
  79. else:
  80. schema = "public"
  81. table = qualified_table.replace('"', "")
  82. # 4. Add the unique constraint if it does not already exist.
  83. alter_table_constraint = f"""
  84. DO $$
  85. BEGIN
  86. IF NOT EXISTS (
  87. SELECT 1
  88. FROM pg_constraint c
  89. JOIN pg_class t ON c.conrelid = t.oid
  90. JOIN pg_namespace n ON n.oid = t.relnamespace
  91. WHERE t.relname = '{table}'
  92. AND n.nspname = '{schema}'
  93. AND c.conname = 'unique_owner_collection_name'
  94. ) THEN
  95. ALTER TABLE {qualified_table}
  96. ADD CONSTRAINT unique_owner_collection_name
  97. UNIQUE (owner_id, name);
  98. END IF;
  99. END;
  100. $$;
  101. """
  102. await self.connection_manager.execute_query(alter_table_constraint)
  103. async def collection_exists(self, collection_id: UUID) -> bool:
  104. """Check if a collection exists."""
  105. query = f"""
  106. SELECT 1 FROM {self._get_table_name(PostgresCollectionsHandler.TABLE_NAME)}
  107. WHERE id = $1
  108. """
  109. result = await self.connection_manager.fetchrow_query(
  110. query, [collection_id]
  111. )
  112. return result is not None
  113. async def create_collection(
  114. self,
  115. owner_id: UUID,
  116. name: Optional[str] = None,
  117. description: str | None = None,
  118. collection_id: Optional[UUID] = None,
  119. ) -> CollectionResponse:
  120. if not name and not collection_id:
  121. name = self.config.default_collection_name
  122. collection_id = generate_default_user_collection_id(owner_id)
  123. query = f"""
  124. INSERT INTO {self._get_table_name(PostgresCollectionsHandler.TABLE_NAME)}
  125. (id, owner_id, name, description)
  126. VALUES ($1, $2, $3, $4)
  127. RETURNING id, owner_id, name, description, graph_sync_status, graph_cluster_status, created_at, updated_at
  128. """
  129. params = [
  130. collection_id or uuid4(),
  131. owner_id,
  132. name,
  133. description,
  134. ]
  135. try:
  136. result = await self.connection_manager.fetchrow_query(
  137. query=query,
  138. params=params,
  139. )
  140. if not result:
  141. raise R2RException(
  142. status_code=404, message="Collection not found"
  143. )
  144. return CollectionResponse(
  145. id=result["id"],
  146. owner_id=result["owner_id"],
  147. name=result["name"],
  148. description=result["description"],
  149. graph_cluster_status=result["graph_cluster_status"],
  150. graph_sync_status=result["graph_sync_status"],
  151. created_at=result["created_at"],
  152. updated_at=result["updated_at"],
  153. user_count=0,
  154. document_count=0,
  155. )
  156. except UniqueViolationError:
  157. raise R2RException(
  158. message="Collection with this ID already exists",
  159. status_code=409,
  160. ) from None
  161. except Exception as e:
  162. raise HTTPException(
  163. status_code=500,
  164. detail=f"An error occurred while creating the collection: {e}",
  165. ) from e
  166. async def update_collection(
  167. self,
  168. collection_id: UUID,
  169. name: Optional[str] = None,
  170. description: Optional[str] = None,
  171. ) -> CollectionResponse:
  172. """Update an existing collection."""
  173. if not await self.collection_exists(collection_id):
  174. raise R2RException(status_code=404, message="Collection not found")
  175. update_fields = []
  176. params: list = []
  177. param_index = 1
  178. if name is not None:
  179. update_fields.append(f"name = ${param_index}")
  180. params.append(name)
  181. param_index += 1
  182. if description is not None:
  183. update_fields.append(f"description = ${param_index}")
  184. params.append(description)
  185. param_index += 1
  186. if not update_fields:
  187. raise R2RException(status_code=400, message="No fields to update")
  188. update_fields.append("updated_at = NOW()")
  189. params.append(collection_id)
  190. query = f"""
  191. WITH updated_collection AS (
  192. UPDATE {self._get_table_name(PostgresCollectionsHandler.TABLE_NAME)}
  193. SET {", ".join(update_fields)}
  194. WHERE id = ${param_index}
  195. RETURNING id, owner_id, name, description, graph_sync_status, graph_cluster_status, created_at, updated_at
  196. )
  197. SELECT
  198. uc.*,
  199. COUNT(DISTINCT u.id) FILTER (WHERE u.id IS NOT NULL) as user_count,
  200. COUNT(DISTINCT d.id) FILTER (WHERE d.id IS NOT NULL) as document_count
  201. FROM updated_collection uc
  202. LEFT JOIN {self._get_table_name("users")} u ON uc.id = ANY(u.collection_ids)
  203. LEFT JOIN {self._get_table_name("documents")} d ON uc.id = ANY(d.collection_ids)
  204. GROUP BY uc.id, uc.owner_id, uc.name, uc.description, uc.graph_sync_status, uc.graph_cluster_status, uc.created_at, uc.updated_at
  205. """
  206. try:
  207. result = await self.connection_manager.fetchrow_query(
  208. query, params
  209. )
  210. if not result:
  211. raise R2RException(
  212. status_code=404, message="Collection not found"
  213. )
  214. return CollectionResponse(
  215. id=result["id"],
  216. owner_id=result["owner_id"],
  217. name=result["name"],
  218. description=result["description"],
  219. graph_sync_status=result["graph_sync_status"],
  220. graph_cluster_status=result["graph_cluster_status"],
  221. created_at=result["created_at"],
  222. updated_at=result["updated_at"],
  223. user_count=result["user_count"],
  224. document_count=result["document_count"],
  225. )
  226. except Exception as e:
  227. raise HTTPException(
  228. status_code=500,
  229. detail=f"An error occurred while updating the collection: {e}",
  230. ) from e
  231. async def delete_collection_relational(self, collection_id: UUID) -> None:
  232. # Remove collection_id from users
  233. user_update_query = f"""
  234. UPDATE {self._get_table_name("users")}
  235. SET collection_ids = array_remove(collection_ids, $1)
  236. WHERE $1 = ANY(collection_ids)
  237. """
  238. await self.connection_manager.execute_query(
  239. user_update_query, [collection_id]
  240. )
  241. # Remove collection_id from documents
  242. document_update_query = f"""
  243. WITH updated AS (
  244. UPDATE {self._get_table_name("documents")}
  245. SET collection_ids = array_remove(collection_ids, $1)
  246. WHERE $1 = ANY(collection_ids)
  247. RETURNING 1
  248. )
  249. SELECT COUNT(*) AS affected_rows FROM updated
  250. """
  251. await self.connection_manager.fetchrow_query(
  252. document_update_query, [collection_id]
  253. )
  254. # Delete the collection
  255. delete_query = f"""
  256. DELETE FROM {self._get_table_name(PostgresCollectionsHandler.TABLE_NAME)}
  257. WHERE id = $1
  258. RETURNING id
  259. """
  260. deleted = await self.connection_manager.fetchrow_query(
  261. delete_query, [collection_id]
  262. )
  263. if not deleted:
  264. raise R2RException(status_code=404, message="Collection not found")
  265. async def documents_in_collection(
  266. self, collection_id: UUID, offset: int, limit: int
  267. ) -> dict[str, list[DocumentResponse] | int]:
  268. """Get all documents in a specific collection with pagination.
  269. Args:
  270. collection_id (UUID): The ID of the collection to get documents from.
  271. offset (int): The number of documents to skip.
  272. limit (int): The maximum number of documents to return.
  273. Returns:
  274. List[DocumentResponse]: A list of DocumentResponse objects representing the documents in the collection.
  275. Raises:
  276. R2RException: If the collection doesn't exist.
  277. """
  278. if not await self.collection_exists(collection_id):
  279. raise R2RException(status_code=404, message="Collection not found")
  280. query = f"""
  281. SELECT d.id, d.owner_id, d.type, d.metadata, d.title, d.version,
  282. d.size_in_bytes, d.ingestion_status, d.extraction_status, d.created_at, d.updated_at, d.summary,
  283. COUNT(*) OVER() AS total_entries
  284. FROM {self._get_table_name("documents")} d
  285. WHERE $1 = ANY(d.collection_ids)
  286. ORDER BY d.created_at DESC
  287. OFFSET $2
  288. """
  289. conditions = [collection_id, offset]
  290. if limit != -1:
  291. query += " LIMIT $3"
  292. conditions.append(limit)
  293. results = await self.connection_manager.fetch_query(query, conditions)
  294. documents = [
  295. DocumentResponse(
  296. id=row["id"],
  297. collection_ids=[collection_id],
  298. owner_id=row["owner_id"],
  299. document_type=DocumentType(row["type"]),
  300. metadata=json.loads(row["metadata"]),
  301. title=row["title"],
  302. version=row["version"],
  303. size_in_bytes=row["size_in_bytes"],
  304. ingestion_status=IngestionStatus(row["ingestion_status"]),
  305. extraction_status=GraphExtractionStatus(
  306. row["extraction_status"]
  307. ),
  308. created_at=row["created_at"],
  309. updated_at=row["updated_at"],
  310. summary=row["summary"],
  311. )
  312. for row in results
  313. ]
  314. total_entries = results[0]["total_entries"] if results else 0
  315. return {"results": documents, "total_entries": total_entries}
  316. async def get_collections_overview(
  317. self,
  318. offset: int,
  319. limit: int,
  320. filter_user_ids: Optional[list[UUID]] = None,
  321. filter_document_ids: Optional[list[UUID]] = None,
  322. filter_collection_ids: Optional[list[UUID]] = None,
  323. owner_only: bool = False,
  324. ) -> dict[str, list[CollectionResponse] | int]:
  325. conditions = []
  326. params: list[Any] = []
  327. param_index = 1
  328. if filter_user_ids:
  329. if owner_only:
  330. conditions.append(f"c.owner_id = ANY(${param_index})")
  331. else:
  332. conditions.append(f"""
  333. c.id IN (
  334. SELECT unnest(collection_ids)
  335. FROM {self.project_name}.users
  336. WHERE id = ANY(${param_index})
  337. )
  338. """)
  339. params.append(filter_user_ids)
  340. param_index += 1
  341. if filter_document_ids:
  342. conditions.append(f"""
  343. c.id IN (
  344. SELECT unnest(collection_ids)
  345. FROM {self.project_name}.documents
  346. WHERE id = ANY(${param_index})
  347. )
  348. """)
  349. params.append(filter_document_ids)
  350. param_index += 1
  351. if filter_collection_ids:
  352. conditions.append(f"c.id = ANY(${param_index})")
  353. params.append(filter_collection_ids)
  354. param_index += 1
  355. where_clause = (
  356. f"WHERE {' AND '.join(conditions)}" if conditions else ""
  357. )
  358. query = f"""
  359. SELECT
  360. c.*,
  361. COUNT(*) OVER() as total_entries
  362. FROM {self.project_name}.collections c
  363. {where_clause}
  364. ORDER BY created_at DESC
  365. OFFSET ${param_index}
  366. """
  367. params.append(offset)
  368. param_index += 1
  369. if limit != -1:
  370. query += f" LIMIT ${param_index}"
  371. params.append(limit)
  372. try:
  373. results = await self.connection_manager.fetch_query(query, params)
  374. if not results:
  375. return {"results": [], "total_entries": 0}
  376. total_entries = results[0]["total_entries"] if results else 0
  377. collections = [CollectionResponse(**row) for row in results]
  378. return {"results": collections, "total_entries": total_entries}
  379. except Exception as e:
  380. raise HTTPException(
  381. status_code=500,
  382. detail=f"An error occurred while fetching collections: {e}",
  383. ) from e
  384. async def assign_document_to_collection_relational(
  385. self,
  386. document_id: UUID,
  387. collection_id: UUID,
  388. ) -> UUID:
  389. """Assign a document to a collection.
  390. Args:
  391. document_id (UUID): The ID of the document to assign.
  392. collection_id (UUID): The ID of the collection to assign the document to.
  393. Raises:
  394. R2RException: If the collection doesn't exist, if the document is not found,
  395. or if there's a database error.
  396. """
  397. try:
  398. if not await self.collection_exists(collection_id):
  399. raise R2RException(
  400. status_code=404, message="Collection not found"
  401. )
  402. # First, check if the document exists
  403. document_check_query = f"""
  404. SELECT 1 FROM {self._get_table_name("documents")}
  405. WHERE id = $1
  406. """
  407. document_exists = await self.connection_manager.fetchrow_query(
  408. document_check_query, [document_id]
  409. )
  410. if not document_exists:
  411. raise R2RException(
  412. status_code=404, message="Document not found"
  413. )
  414. # If document exists, proceed with the assignment
  415. assign_query = f"""
  416. UPDATE {self._get_table_name("documents")}
  417. SET collection_ids = array_append(collection_ids, $1)
  418. WHERE id = $2 AND NOT ($1 = ANY(collection_ids))
  419. RETURNING id
  420. """
  421. result = await self.connection_manager.fetchrow_query(
  422. assign_query, [collection_id, document_id]
  423. )
  424. #if not result:
  425. # Document exists but was already assigned to the collection
  426. # raise R2RException(
  427. # status_code=409,
  428. # message="Document is already assigned to the collection",
  429. # )
  430. update_collection_query = f"""
  431. UPDATE {self._get_table_name("collections")}
  432. SET document_count = document_count + 1
  433. WHERE id = $1
  434. """
  435. await self.connection_manager.execute_query(
  436. query=update_collection_query, params=[collection_id]
  437. )
  438. return collection_id
  439. except R2RException:
  440. # Re-raise R2RExceptions as they are already handled
  441. raise
  442. except Exception as e:
  443. raise HTTPException(
  444. status_code=500,
  445. detail=f"An error '{e}' occurred while assigning the document to the collection",
  446. ) from e
  447. async def remove_document_from_collection_relational(
  448. self, document_id: UUID, collection_id: UUID
  449. ) -> None:
  450. """Remove a document from a collection.
  451. Args:
  452. document_id (UUID): The ID of the document to remove.
  453. collection_id (UUID): The ID of the collection to remove the document from.
  454. Raises:
  455. R2RException: If the collection doesn't exist or if the document is not in the collection.
  456. """
  457. if not await self.collection_exists(collection_id):
  458. raise R2RException(status_code=404, message="Collection not found")
  459. query = f"""
  460. UPDATE {self._get_table_name("documents")}
  461. SET collection_ids = array_remove(collection_ids, $1)
  462. WHERE id = $2 AND $1 = ANY(collection_ids)
  463. RETURNING id
  464. """
  465. result = await self.connection_manager.fetchrow_query(
  466. query, [collection_id, document_id]
  467. )
  468. if not result:
  469. raise R2RException(
  470. status_code=404,
  471. message="Document not found in the specified collection",
  472. )
  473. await self.decrement_collection_document_count(
  474. collection_id=collection_id
  475. )
  476. async def decrement_collection_document_count(
  477. self, collection_id: UUID, decrement_by: int = 1
  478. ) -> None:
  479. """Decrement the document count for a collection.
  480. Args:
  481. collection_id (UUID): The ID of the collection to update
  482. decrement_by (int): Number to decrease the count by (default: 1)
  483. """
  484. collection_query = f"""
  485. UPDATE {self._get_table_name("collections")}
  486. SET document_count = document_count - $1
  487. WHERE id = $2
  488. """
  489. await self.connection_manager.execute_query(
  490. collection_query, [decrement_by, collection_id]
  491. )
  492. async def export_to_csv(
  493. self,
  494. columns: Optional[list[str]] = None,
  495. filters: Optional[dict] = None,
  496. include_header: bool = True,
  497. ) -> tuple[str, IO]:
  498. """Creates a CSV file from the PostgreSQL data and returns the path to
  499. the temp file."""
  500. valid_columns = {
  501. "id",
  502. "owner_id",
  503. "name",
  504. "description",
  505. "graph_sync_status",
  506. "graph_cluster_status",
  507. "created_at",
  508. "updated_at",
  509. "user_count",
  510. "document_count",
  511. }
  512. if not columns:
  513. columns = list(valid_columns)
  514. elif invalid_cols := set(columns) - valid_columns:
  515. raise ValueError(f"Invalid columns: {invalid_cols}")
  516. select_stmt = f"""
  517. SELECT
  518. id::text,
  519. owner_id::text,
  520. name,
  521. description,
  522. graph_sync_status,
  523. graph_cluster_status,
  524. to_char(created_at, 'YYYY-MM-DD HH24:MI:SS') AS created_at,
  525. to_char(updated_at, 'YYYY-MM-DD HH24:MI:SS') AS updated_at,
  526. user_count,
  527. document_count
  528. FROM {self._get_table_name(self.TABLE_NAME)}
  529. """
  530. params = []
  531. if filters:
  532. conditions = []
  533. param_index = 1
  534. for field, value in filters.items():
  535. if field not in valid_columns:
  536. continue
  537. if isinstance(value, dict):
  538. for op, val in value.items():
  539. if op == "$eq":
  540. conditions.append(f"{field} = ${param_index}")
  541. params.append(val)
  542. param_index += 1
  543. elif op == "$gt":
  544. conditions.append(f"{field} > ${param_index}")
  545. params.append(val)
  546. param_index += 1
  547. elif op == "$lt":
  548. conditions.append(f"{field} < ${param_index}")
  549. params.append(val)
  550. param_index += 1
  551. else:
  552. # Direct equality
  553. conditions.append(f"{field} = ${param_index}")
  554. params.append(value)
  555. param_index += 1
  556. if conditions:
  557. select_stmt = f"{select_stmt} WHERE {' AND '.join(conditions)}"
  558. select_stmt = f"{select_stmt} ORDER BY created_at DESC"
  559. temp_file = None
  560. try:
  561. temp_file = tempfile.NamedTemporaryFile(
  562. mode="w", delete=True, suffix=".csv"
  563. )
  564. writer = csv.writer(temp_file, quoting=csv.QUOTE_ALL)
  565. async with self.connection_manager.pool.get_connection() as conn: # type: ignore
  566. async with conn.transaction():
  567. cursor = await conn.cursor(select_stmt, *params)
  568. if include_header:
  569. writer.writerow(columns)
  570. chunk_size = 1000
  571. while True:
  572. rows = await cursor.fetch(chunk_size)
  573. if not rows:
  574. break
  575. for row in rows:
  576. row_dict = {
  577. "id": row[0],
  578. "owner_id": row[1],
  579. "name": row[2],
  580. "description": row[3],
  581. "graph_sync_status": row[4],
  582. "graph_cluster_status": row[5],
  583. "created_at": row[6],
  584. "updated_at": row[7],
  585. "user_count": row[8],
  586. "document_count": row[9],
  587. }
  588. writer.writerow([row_dict[col] for col in columns])
  589. temp_file.flush()
  590. return temp_file.name, temp_file
  591. except Exception as e:
  592. if temp_file:
  593. temp_file.close()
  594. raise HTTPException(
  595. status_code=500,
  596. detail=f"Failed to export data: {str(e)}",
  597. ) from e
  598. async def get_collection_by_name(
  599. self, owner_id: UUID, name: str
  600. ) -> Optional[CollectionResponse]:
  601. """Fetch a collection by owner_id + name combination.
  602. Return None if not found.
  603. """
  604. query = f"""
  605. SELECT
  606. id, owner_id, name, description, graph_sync_status,
  607. graph_cluster_status, created_at, updated_at, user_count, document_count
  608. FROM {self._get_table_name(PostgresCollectionsHandler.TABLE_NAME)}
  609. WHERE owner_id = $1 AND name = $2
  610. LIMIT 1
  611. """
  612. result = await self.connection_manager.fetchrow_query(
  613. query, [owner_id, name]
  614. )
  615. if not result:
  616. raise R2RException(
  617. status_code=404,
  618. message="No collection found with the specified name",
  619. )
  620. return CollectionResponse(
  621. id=result["id"],
  622. owner_id=result["owner_id"],
  623. name=result["name"],
  624. description=result["description"],
  625. graph_sync_status=result["graph_sync_status"],
  626. graph_cluster_status=result["graph_cluster_status"],
  627. created_at=result["created_at"],
  628. updated_at=result["updated_at"],
  629. user_count=result["user_count"],
  630. document_count=result["document_count"],
  631. )