Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGES/7831.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Optimized the ``q`` complex filter to compose ``NOT``/``AND``/``OR`` operands using ``pk__in``
subqueries instead of the ``EXCEPT``/``INTERSECT``/``UNION`` set operations, avoiding full-table
scans and disk-spilling sorts on large content sets.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is supposed to be markdown, not ReST.
Single backticks work better, as far as I recall.

16 changes: 9 additions & 7 deletions pulpcore/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,27 +215,29 @@ def __init__(self, tokens):
self.complexity = self.expr.complexity + 1

def evaluate(self, qs):
return qs.difference(self.expr.evaluate(qs))
return qs.exclude(pk__in=self.expr.evaluate(qs).values("pk"))

class _AndAction:
def __init__(self, tokens):
self.exprs = tokens[0]
self.complexity = sum((expr.complexity for expr in self.exprs)) + 1

def evaluate(self, qs):
return (
self.exprs[0]
.evaluate(qs)
.intersection(*[expr.evaluate(qs) for expr in self.exprs[1:]])
)
result = qs
for expr in self.exprs:
result = result.filter(pk__in=expr.evaluate(qs).values("pk"))
return result

class _OrAction:
def __init__(self, tokens):
self.exprs = tokens[0]
self.complexity = sum((expr.complexity for expr in self.exprs)) + 1

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FYI, the complexity is meant to prevent easy dos attacks by generating arbitrarily complex queries. I guess you can already get quite far with the current setting.


def evaluate(self, qs):
return self.exprs[0].evaluate(qs).union(*[expr.evaluate(qs) for expr in self.exprs[1:]])
query = models.Q()
for expr in self.exprs:
query |= models.Q(pk__in=expr.evaluate(qs).values("pk"))
return qs.filter(query)

def __init__(self, *args, **kwargs):
self.filterset = kwargs.pop("filter").parent
Expand Down
Loading