Skip to content

fix: make column.unnest().topk() work #11259

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
29 changes: 29 additions & 0 deletions ibis/backends/tests/test_generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import ibis.expr.datatypes as dt
import ibis.selectors as s
from ibis import _
from ibis.backends.tests.conftest import NO_ARRAY_SUPPORT
from ibis.backends.tests.errors import (
ClickHouseDatabaseError,
ExaQueryError,
Expand Down Expand Up @@ -2390,6 +2391,34 @@
assert result[0].as_py() == 1


@NO_ARRAY_SUPPORT
def test_topk_unnest_count(con: ibis.BaseBackend):
t = ibis.memtable({"x": [[1, 2, 3], [1, 2, None], []]})
tk = t.x.unnest().topk(name="n")
n_1s = tk.filter(_.x == 1)["n"].as_scalar()
result = con.to_pyarrow(n_1s).as_py()
assert result == 2

tk = t.x.unnest().topk()
n_1s = tk.filter(_.x == 1)["x_count"].as_scalar()
result = con.to_pyarrow(n_1s).as_py()
assert result == 2


@pytest.mark.xfail(reason="The unnest is not placed in the right place in the query")
def test_topk_unnest_max(con: ibis.BaseBackend):
t = con.create_table(
ibis.util.gen_name("topk_counts_unnest"),
{"x": [[1, 2, 3], [1, 2, None], []]},
temp=True,
)
v = t.x.unnest()
tk = v.topk(by=v.max(), name="n")
n_1s = tk.filter(_.x == 1)["n"].as_scalar()
result = con.to_pyarrow(n_1s).as_py()
assert result == 1

Check warning on line 2419 in ibis/backends/tests/test_generic.py

View check run for this annotation

Codecov / codecov/patch

ibis/backends/tests/test_generic.py#L2419

Added line #L2419 was not covered by tests


@pytest.mark.notyet(
"clickhouse",
raises=AssertionError,
Expand Down
14 changes: 5 additions & 9 deletions ibis/expr/types/generic.py
Original file line number Diff line number Diff line change
Expand Up @@ -2238,18 +2238,14 @@ def topk(
"""
from ibis.expr.types.relations import bind

if by is None:
return self.as_table().topk(k=k, name=name)

try:
(table,) = self.op().relations
(table_op,) = self.op().relations
except ValueError:
raise com.IbisTypeError("TopK must depend on exactly one table.")

table = table.to_expr()

if by is None and name is None:
# if `by` is something more complex, the _count doesn't make sense.
name = f"{self.get_name()}_count"
if by is None:
by = lambda t: t.count()
table: ibis.Table = table_op.to_expr()

(metric,) = bind(table, by)
if name is not None:
Expand Down
Loading