Remove all matching documents. :param cond: the condition to check against :param doc_ids: a list of document IDs :returns: a list containing the removed documents' ID
(
self,
cond: Optional[QueryLike] = None,
doc_ids: Optional[Iterable[int]] = None,
)
| 552 | return [self.insert(document)] |
| 553 | |
| 554 | def remove( |
| 555 | self, |
| 556 | cond: Optional[QueryLike] = None, |
| 557 | doc_ids: Optional[Iterable[int]] = None, |
| 558 | ) -> List[int]: |
| 559 | """ |
| 560 | Remove all matching documents. |
| 561 | |
| 562 | :param cond: the condition to check against |
| 563 | :param doc_ids: a list of document IDs |
| 564 | :returns: a list containing the removed documents' ID |
| 565 | """ |
| 566 | if doc_ids is not None: |
| 567 | # This function returns the list of IDs for the documents that have |
| 568 | # been removed. When removing documents identified by a set of |
| 569 | # document IDs, it's this list of document IDs we need to return |
| 570 | # later. |
| 571 | # We convert the document ID iterator into a list, so we can both |
| 572 | # use the document IDs to remove the specified documents and |
| 573 | # to return the list of affected document IDs |
| 574 | removed_ids = list(doc_ids) |
| 575 | |
| 576 | def updater(table: dict): |
| 577 | for doc_id in removed_ids: |
| 578 | table.pop(doc_id) |
| 579 | |
| 580 | # Perform the remove operation |
| 581 | self._update_table(updater) |
| 582 | |
| 583 | return removed_ids |
| 584 | |
| 585 | if cond is not None: |
| 586 | removed_ids = [] |
| 587 | |
| 588 | # This updater function will be called with the table data |
| 589 | # as its first argument. See ``Table._update`` for details on this |
| 590 | # operation |
| 591 | def updater(table: dict): |
| 592 | # We need to convince MyPy (the static type checker) that |
| 593 | # the ``cond is not None`` invariant still holds true when |
| 594 | # the updater function is called |
| 595 | _cond = cast(QueryLike, cond) |
| 596 | |
| 597 | # We need to convert the keys iterator to a list because |
| 598 | # we may remove entries from the ``table`` dict during |
| 599 | # iteration and doing this without the list conversion would |
| 600 | # result in an exception (RuntimeError: dictionary changed size |
| 601 | # during iteration) |
| 602 | for doc_id in list(table.keys()): |
| 603 | if _cond(table[doc_id]): |
| 604 | # Add document ID to list of removed document IDs |
| 605 | removed_ids.append(doc_id) |
| 606 | |
| 607 | # Remove document from the table |
| 608 | table.pop(doc_id) |
| 609 | |
| 610 | # Perform the remove operation |
| 611 | self._update_table(updater) |