Skip to content

union

relationalai.semantics
union(*args: Value) -> Union

Combine items with a logical OR or a set-style union.

This is a convenience wrapper around Model.union that operates on the single active model. It returns a Union object.

Unlike the | operator (see Variable.__or__), which picks the first branch that can succeed and is commonly used for fallback/default values, union combines the results from all branches.

union is used in two common ways:

  • As an OR-combinator in where clauses, e.g., where(union(cond1, cond2)).
  • As a union of multiple fragments/tables that return the same number of values. This produces a derived table whose columns can be selected or unpacked. (All branches must have the same “shape”, i.e. number of selected values.)

Nested unions are flattened, so union(union(a, b), c) is equivalent to union(a, b, c).

If you have more than one model, call Model.union on the specific model instead.

  • Union - A composable union object.
  • relationalai.util.error.RAIException - Raised in the following cases:
    • There is no active model, or multiple models exist and the active model would be ambiguous.
    • The union branches return different numbers of values.

Use union to OR conditions:

>>> from relationalai.semantics import Model, select, union, where
>>> m = Model()
>>> Person = m.Concept("Person")
>>> define(
... Person.new(name="Alice", age=10),
... Person.new(name="Bob", age=30),
... Person.new(name="Charlie", age=70),
... )
>>> where(union(Person.age < 18, Person.age >= 65)).select(Person.name).to_df()

Union two fragments that select the same number of values:

>>> Edge = m.Concept("Edge")
>>> e, src, dst = union(
... where(Edge, Edge.src <= Edge.dst).select(Edge, Edge.src, Edge.dst),
... where(Edge, Edge.src > Edge.dst).select(Edge, Edge.dst, Edge.src),
... )
>>> where(Edge).select(src, dst).to_df()