# Model

relationalai.semantics.frontend.base

```python
Model(
    name: str = "",
    exclude_core: bool = False,
    is_library: bool = False,
    config: Config | None = None,
)
```

Create and manage a semantic model.

A [`Model`](/api/python/v2.3/semantics/frontend/base/model_class/index.md) stores the concepts, relationships, definitions, and
requirements that make up your semantic model. Create them using methods
like [`Model.Concept`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-concept), [`Model.Relationship`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-relationship), [`Model.define`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-define),
and [`Model.require`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-require). Query methods like [`Model.where`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-where) and
[`Model.select`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-select) return a composable [`Fragment`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md) that you can further
refine and materialize with [`Fragment.to_df`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-to_df).

Many methods on [`Model`](/api/python/v2.3/semantics/frontend/base/model_class/index.md) can be accessed as top-level functions from
the [`relationalai.semantics`](/api/python/v2.3/semantics/index.md) module. For example, you can use
[`define`](/api/python/v2.3/semantics/define/index.md) instead of [`Model.define`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-define) to
add definitions to a model if you have a single active model (the common
case in interactive use). However, if you have multiple models or want to
be explicit about which model you're using, it's best to call methods
directly on the model instance.

## Parameters

- `name` (`str`, default: `""`) - Name of the model. Used only for identification and debugging.
- `exclude_core` (`bool`, default: `False`) - If True, do not include the core library by default.
- `is_library` (`bool`, default: `False`) - If True, this model is treated as a library and is not added to the global list of active models.
- `config` ([`Config`](/api/python/v2.3/config/config/config_class/index.md), default: `None`) - Configuration used when executing queries. Defaults to `None` which means configuration is loaded from the filesystem (for example, from a `raconfig.yaml` file if present).

## Examples

Define a few entities and query them:

```python
from relationalai.semantics import Model

m = Model()
Person = m.Concept("Person")
m.define(
    Person.new(name="Alice", age=10),
    Person.new(name="Bob", age=30),
)
m.where(Person.age > 18).select(Person.name).to_df()
```

## Attributes

### .`all_models`

```python
Model.all_models: weakref.WeakSet[Model]
```

Class-level weak set of live models created in this Python session
(excluding library-only models). Models drop out automatically once
garbage collected; keep a reference to a model to keep it active.
Most users do not need this.

### .`name`

```python
Model.name: str
```

The model name (optional; used for identification/debugging).

### .`config`

```python
Model.config: relationalai.config.config.Config
```

Configuration settings used when executing queries against this model.
If you have a `raconfig.yaml` file, or other valid configuration source,
these settings are automatically loaded into new models by default.
You can also override them by passing a custom config when creating the model.
See the [`relationalai.config`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#param-config) documentation for more details.

### .`defines`

```python
Model.defines: KeyedSet[Fragment]
```

Definitions added via [`Model.define`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-define).

### .`requires`

```python
Model.requires: KeyedSet[Fragment]
```

Requirements added via [`Model.require`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-require).

### .`exports`

```python
Model.exports: KeyedSet[Fragment]
```

Export artifacts created when exporting query results (advanced).

### .`libraries`

```python
Model.libraries: list[type[Model]]
```

Libraries included with this model (the core library is included by
default unless you set `exclude_core=True`).

### .`concepts`

```python
Model.concepts: list[Concept]
```

Concepts created in this model via [`Model.Concept`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-concept).

### .`tables`

```python
Model.tables: list[Table]
```

Table references created in this model via [`Model.Table`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-table).

### .`data_items`

```python
Model.data_items: list[Data]
```

Inline data loaded into this model via [`Model.data`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-data).

### .`relationships`

```python
Model.relationships: list[Relationship]
```

Relationships and properties created in this model via [`Model.Relationship`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-relationship).

### .`enums`

```python
Model.enums: list[type[ModelEnum]]
```

Enum types created in this model via [`Model.Enum`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#param-enum).

### .`concept_index`

```python
Model.concept_index: dict[str, Concept]
```

Dictionary mapping concept names to [`Concept`](/api/python/v2.3/semantics/frontend/base/concept_class/index.md) objects for quick lookup.

### .`table_index`

```python
Model.table_index: dict[str, Table]
```

Dictionary mapping table names to [`Table`](/api/python/v2.3/semantics/frontend/base/table_class/index.md) objects for quick lookup.

### .`relationship_index`

```python
Model.relationship_index: dict[str, Relationship]
```

Dictionary mapping relationship/property names to [`Relationship`](/api/python/v2.3/semantics/frontend/base/relationship_class/index.md) objects for quick lookup.

### .`enums_index`

```python
Model.enums_index: dict[str, type[ModelEnum]]
```

Dictionary mapping enum names to enum types for quick lookup.

### .`Enum`

```python
Model.Enum: type
```

Helper used to create enums associated with this model.

## Methods

### .`deploy`()

```python
Model.deploy(
    *,
    wait: bool = True,
    force: bool = False,
    redeploy_all: bool = False,
    wait_timeout: float | None = None,
    reviewed_plan: DeployPlanReport | str | Path | None = None
) -> "DeployReadinessResult"
```

Deploy this model and wait for its initial refresh.

Pass `redeploy_all=True` to redeploy every managed object even when its
saved definition is unchanged. This can rebuild materialized data. It does
not bypass ownership checks or reviewed-plan verification.

Waiting has no timeout by default. Set `wait_timeout` to a positive,
finite number of seconds to limit the initial-refresh wait. A timeout
raises `TimeoutError` without cancelling the refresh. Pass `wait=False`
to return without waiting; it cannot be combined with `wait_timeout`.

Uses the model's own configuration ([`Model.config`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#param-config)). This is the
programmatic equivalent of `rai models deploy`: when `config.oplog`
is enabled it provisions the schema, records the deploy to the oplog,
and regenerates the shared model exactly as the CLI does; when oplog is
disabled it installs only.

On the oplog-enabled path, when `config.model.path` is set this
deploys the model **as defined in that file** (loaded fresh, exactly as
the CLI does), not any in-memory changes to this object: the file is the
recorded source of truth, so installing and recording the same
freshly-loaded model keeps them from diverging, and [`Model.name`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#param-name) selects
which model in the file to deploy. When no `config.model.path` is set
(e.g. a model built inline in a notebook), this records the in-memory
model itself.

Pass `reviewed_plan` as a captured report from `plan_deployment()` or a path
(`str` or `Path`) to a saved .md or .json report. Report objects use canonical
JSON; files are compared byte for byte without normalization. `force=True` does
not bypass verification. A mismatch raises `ReviewedPlanMismatchError` before
applying planned operations; setup may already have updated metadata.

**Returns:**

- `DeployReadinessResult` - The backend's deploy-readiness result.

**Examples:**

Capture and review a report before deploying:

```
plan = model.plan_deployment()
display(plan)
model.deploy(reviewed_plan=plan)
```

Alternatively, review a saved report and deploy it later:

```
plan.save("deployment.json", format="json")
model.deploy(reviewed_plan="deployment.json")
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [What's new](/release-notes/index.md)1. [Python package and CLI release notes](/release-notes/python/index.md)1) [Python package and CLI 2.0.0](/release-notes/python/2.0.0/index.md)1. [New Features and Enhancements](/release-notes/python/2.0.0/index.md#new-features-and-enhancements)
         2) [Python package and CLI 2.1.0](/release-notes/python/2.1.0/index.md)1) [New Features and Enhancements](/release-notes/python/2.1.0/index.md#new-features-and-enhancements)

### .`plan_deployment`()

```python
Model.plan_deployment(
    *, force: bool = False, redeploy_all: bool = False
) -> "DeployPlanReport"
```

Preview the changes that deploying this model would make in Snowflake.

Returns a deployment plan that lists the objects the deployment would create,
replace, or remove, and the SQL it would run. Nothing is deployed. Review the
plan, then pass it to [`Model.deploy`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-deploy) to deploy exactly those changes. If the
model, its configuration, or the Snowflake objects change in the meantime,
`deploy()` refuses to run and you need to generate a new plan.

Pass `redeploy_all=True` to preview a full redeployment, and pass the
same flag to `deploy()` when applying that reviewed plan.

This is the Python equivalent of `rai models deploy --plan`. Planning uses
the same configuration, deployment role, and privileges as [`Model.deploy`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-deploy).
Call it from a notebook or a separate script, not from the model file itself.

Planning connects to Snowflake and can create or update the schemas and
metadata PyRel needs, even though the plan doesn't list them. It doesn't
install model outputs or start a refresh.

If you save the plan, don't edit the file: `deploy()` compares it exactly
with a freshly generated plan.

**Returns:**

- `DeployPlanReport` - The deployment plan. Display it in a notebook with `display(plan)`,
  save it with `plan.save()`, or pass it to `deploy(reviewed_plan=...)`.

**Examples:**

Review a plan in a notebook, then deploy it:

```
from model import model

plan = model.plan_deployment()
display(plan)
model.deploy(reviewed_plan=plan)
```

Save the plan to review or share it, and deploy it later:

```
plan.save("deployment-plan.md")
model.deploy(reviewed_plan="deployment-plan.md")
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [What's new](/release-notes/index.md)1. [Python package and CLI release notes](/release-notes/python/index.md)1) [Python package and CLI 2.0.0](/release-notes/python/2.0.0/index.md)1. [New Features and Enhancements](/release-notes/python/2.0.0/index.md#new-features-and-enhancements)
         2) [Python package and CLI 2.0.1](/release-notes/python/2.0.1/index.md)1) [New Features and Enhancements](/release-notes/python/2.0.1/index.md#new-features-and-enhancements)

### .`teardown`()

```python
Model.teardown(
    *,
    force: bool = False,
    quiet: bool = False,
    allow_unmerged: bool = False,
    allow_children: bool = False
) -> "TeardownResult"
```

Tear down this model's deployment — remove what RAI created in the configured
`deployment.public_schema` and its `_META` (oplog included), plus the paired local
replay state.

Only objects carrying RAI's ownership tag are removed. The schemas themselves are
always kept, whoever created them: Snowflake cannot prove a schema is empty, so
dropping one risks destroying objects you created.

The programmatic equivalent of `rai models teardown`. Because teardown is
destructive, it only drops when `force=True` (matching the CLI's
`--force`); the default previews what would be dropped and drops nothing.
Prints a concise summary of the outcome unless `quiet=True`. Uses the
model's own configuration ([`Model.config`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#param-config)), so no `raiconfig.yaml` on
disk is required when the model is built with an explicit `config=`.
Refuses to touch child branches or discard unmerged work unless the
matching `allow_*` override is set — see `allow_children` for exactly
how much that override covers. Leaves `raiconfig.yaml` untouched.

**Parameters:**

- `force` (`bool`, default: `False`) - Actually perform the teardown. Without it, gather and return what would be dropped without dropping anything.
- `quiet` (`bool`, default: `False`) - Suppress the printed summary (for scripts/pipelines that render the returned result themselves).
- `allow_unmerged` (`bool`, default: `False`) - Tear down even if the branch has unmerged changes (discards them). Requires stateful deployment.
- `allow_children` (`bool`, default: `False`) - Tear down downstream branches too, then this model (cascade). **Every** child goes, merged or not — a merged branch is still the readable record of what was merged, and this destroys it. Only a child with *unmerged* changes additionally blocks, until `allow_unmerged` is also set; a merged child produces no blocker at all. Read `cascade_children` off the result (or pass `force=False` for a preview) to see exactly what would go. Requires stateful deployment.

**Returns:**

- `TeardownResult` - The outcome (target, backend, whether teardown ran, any gate blockers).
  Also `cascade_children` — every child branch torn down alongside the
  target, in drop order, populated on a preview too — and
  `parent_exists`, a tri-state: `False` marks this model as an
  *orphaned* branch (its lineage tag names a schema that is no longer
  there, so it can neither pull nor merge), `None` means undecidable
  rather than absent. These are the machine-readable half of the lineage
  work, and this API is their natural consumer; `summarize_teardown`
  renders the same facts as text.

  After execution, `kept_schemas` maps each schema left standing to the
  number of RAI-owned objects removed from it. It is empty for a preview.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [What's new](/release-notes/index.md)1. [Python package and CLI release notes](/release-notes/python/index.md)1) [Python package and CLI 2.1.0](/release-notes/python/2.1.0/index.md)1. [Bug Fixes](/release-notes/python/2.1.0/index.md#bug-fixes)

### .`close`()

```python
Model.close() -> None
```

Release resources held by this model's executor.

### .`exec`()

```python
Model.exec()
```

Execute all export fragments registered on this model as one batch.

Call this after configuring one or more exports with
[`Fragment.into`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-into). Use [`Fragment.exec`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-exec) to run a single export
instead; `Model.exec()` submits every registered export together, and
the backend may run them in parallel.

**Returns:**

- `None` - This method executes the registered exports for their side effects.

**Raises:**

- `ValueError` - Raised when the registered exports cannot be batched together, for
  example if they mix `update=True` and `update=False` exports.

**Examples:**

```python
m = Model("SalesData")
Customer = m.Concept("Customer")
Product = m.Concept("Product")
m.select(Customer.id, Customer.name).into(customer_table)
m.select(Product.id, Product.name).into(product_table)
m.exec()
```

### .`Concept`()

```python
Model.Concept(
    name: str,
    extends: list[Concept] = [],
    identify_by: dict[str, Property | Concept] = {},
    identity_includes_type: bool = False,
) -> Concept
```

Create a concept type in this model.

This is the primary way to introduce a new [`Concept`](/api/python/v2.3/semantics/frontend/base/concept_class/index.md) (entity type)
into a [`Model`](/api/python/v2.3/semantics/frontend/base/model_class/index.md).

**Parameters:**

- `name` (`str`) - Name of the concept.
- `extends` (`list`\[[`Concept`](/api/python/v2.3/semantics/frontend/base/concept_class/index.md)], default: `[]`) - Base concepts this concept extends. Relationships declared on base concepts are inherited by (and available on) the derived concept.
- `identify_by` (`dict`\[`str`, [`Property`](/api/python/v2.3/semantics/frontend/base/property_class/index.md) | [`Concept`](/api/python/v2.3/semantics/frontend/base/concept_class/index.md)], default: `{}`) - Identity fields for this concept. The keys are identity attribute names and the values specify their types (most commonly a [`Concept`](/api/python/v2.3/semantics/frontend/base/concept_class/index.md) such as [`semantics.frontend.core.Integer`](/api/python/v2.3/semantics/frontend/core/integer/index.md) or [`semantics.frontend.core.String`](/api/python/v2.3/semantics/frontend/core/string/index.md)).

  Identity keys are used by `Concept.new`
  to refer to an entity by key (find-or-create).
- `identity_includes_type` (`bool`, default: `False`) - If True, the subtype is part of an entity's key. Example: when `A` and `B` share a base identified by `id`, `A.new(id=1)` and `B.new(id=1)` create two different entities. If False, both calls refer to the same entity (same key fields), which can cause collisions across a type hierarchy.

**Returns:**

- [`Concept`](/api/python/v2.3/semantics/frontend/base/concept_class/index.md) - The newly created concept.

**Raises:**

- `relationalai.util.error.RAIException` - If `extends` contains non-Concept values, or if `identify_by`
  contains values that are not Concepts or Properties.

**Examples:**

Create a concept and define a couple of entities:

```python
from relationalai.semantics import Model, String

m = Model()
Person = m.Concept("Person", identify_by={"name": String})
m.define(
    Person.new(name="Alice"),
    Person.new(name="Bob"),
)
```

Create a derived concept:

```python
Adult = m.Concept("Adult", extends=[Person])
m.where(Person.age >= 18).define(Adult(Person))
```

Define an identity key:

```python
from relationalai.semantics import Integer

Item = m.Concept("Item", identify_by={"id": Integer})
m.define(Item.new(id=1))
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Build a semantic model](/build/modeling/index.md)1) [Declare concepts](/build/modeling/declare-concepts/index.md)1. [What a concept is](/build/modeling/declare-concepts/index.md#what-a-concept-is)
            2. [Declare a concept](/build/modeling/declare-concepts/index.md#declare-a-concept)
            3. [Declare a subconcept](/build/modeling/declare-concepts/index.md#declare-a-subconcept)
         2) [Derive facts with logic](/build/modeling/derive-facts-with-logic/index.md)1) [Write conditional definitions with `Model.where` and `Model.define`](/build/modeling/derive-facts-with-logic/index.md#write-conditional-definitions-with-modelwhere-and-modeldefine)
            2) [Match multiple entities of the same type with `Concept.ref`](/build/modeling/derive-facts-with-logic/index.md#match-multiple-entities-of-the-same-type-with-conceptref)
      2. [Use advanced reasoning](/build/reasoning/index.md) / [Predictive reasoning](/build/reasoning/predictive/index.md)1) [Solve a classification problem](/build/reasoning/predictive/solve-a-classification-problem/index.md)1. [Import the libraries and create a model](/build/reasoning/predictive/solve-a-classification-problem/index.md#import-the-libraries-and-create-a-model)

### .`Table`()

```python
Model.Table(
    path: str, schema: dict[str, Concept] = {}, type: Iceberg | Native | None = None
) -> Table
```

Create a table reference in this model.

A [`Table`](/api/python/v2.3/semantics/frontend/base/table_class/index.md) represents an external table name (such as a SQL table)
that you can use as a source of schema/data for defining entities, or as
a target for exports via [`Fragment.into`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-into).

**Parameters:**

- `path` (`str`) - Table name or path (for example `"MY_DB.MY_SCHEMA.CUSTOMERS"`).

  Each part of the path follows Snowflake's identifier resolution
  rules. An unquoted part is case-insensitive because Snowflake folds
  it to uppercase, so `customers`, `Customers`, and `CUSTOMERS`
  all resolve to the table `CUSTOMERS`. A double-quoted part is
  case-sensitive and matched exactly, so
  `'MY_DB.MY_SCHEMA."customers"'` resolves to a table named
  `customers`, not `CUSTOMERS`. Double-quote a part only when the
  table was created with a lowercase or mixed-case name.
- `schema` (`dict`\[`str`, [`Concept`](/api/python/v2.3/semantics/frontend/base/concept_class/index.md)], default: `{}`) - Optional mapping of column names to their types.
- `type` (`Iceberg or Native`, default: `None`) - Explicit table type. Overrides any default set in `tables:` config. Use `Iceberg()` or `Iceberg(external_volume="...")` to mark the table as an Iceberg table, or `Native()` to opt out of an iceberg default.

**Returns:**

- [`Table`](/api/python/v2.3/semantics/frontend/base/table_class/index.md) - The created table reference.

**Examples:**

Create a table reference for use as an export target:

```python
from relationalai.semantics import Integer, Model, String

m = Model()
Person = m.Concept("Person", identify_by={"id": Integer})
Person.name = m.Property(f"{Person} is named {String:name}")
m.define(Person.new(id=1, name="Alice"))
out = m.Table("DB.SCHEMA.PERSONS_EXPORT")
m.select(Person.id, Person.name).into(out).exec()
```

Use a table with a known schema as an input when defining entities:

```python
from relationalai.semantics import Model, Integer, String

m = Model()
source = m.Table("DB.SCHEMA.CUSTOMERS", schema={"id": Integer, "name": String})
Customer = m.Concept("Customer", extends=[Person])
m.define(Customer.new(source.to_schema()))
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Build a semantic model](/build/modeling/index.md)1) [Declare data sources](/build/modeling/declare-data-sources/index.md)1. [Choose the right source type](/build/modeling/declare-data-sources/index.md#choose-the-right-source-type)
            2. [Use a Snowflake table with `Model.Table`](/build/modeling/declare-data-sources/index.md#use-a-snowflake-table-with-modeltable)
         2) [Define base facts](/build/modeling/define-base-facts/index.md)
      2. [Use advanced reasoning](/build/reasoning/index.md) / [Predictive reasoning](/build/reasoning/predictive/index.md)1) [Solve a classification problem](/build/reasoning/predictive/solve-a-classification-problem/index.md)1. [Import the libraries and create a model](/build/reasoning/predictive/solve-a-classification-problem/index.md#import-the-libraries-and-create-a-model)
   2) [Interact with RelationalAI](/interact/index.md)1) [Query a model with PyRel](/interact/query-a-model-with-pyrel/index.md)1. [Export results to Snowflake tables with `into` and `exec`](/interact/query-a-model-with-pyrel/index.md#export-results-to-snowflake-tables-with-into-and-exec)

### .`Relationship`()

```python
Model.Relationship(
    reading: str = "", fields: list[Field] = [], short_name: str = ""
) -> Relationship
```

Create a relationship in this model.

This is the primary way to introduce a new [`Relationship`](/api/python/v2.3/semantics/frontend/base/relationship_class/index.md) type into a
[`Model`](/api/python/v2.3/semantics/frontend/base/model_class/index.md). The most common way to define a relationship is with a Python
f-string `reading` that embeds concept/type placeholders. Each embedded
placeholder becomes a field of the relationship, in order.

Reading strings have the following format:

- Use an f-string and embed types with `{...}`, e.g. `f"{Person} has {Pet}"`.
- Name fields with `{Type:name}`, e.g. `f"{Person:owner} has {Pet:pet}"`.
- For full control (including multi-field relationships), pass an
  explicit `fields=[Field(...), ...]` list instead of a reading.

**Parameters:**

- `reading` (`str`, default: `""`) - A reading that describes the relationship fields. Typically an f-string, for example `f"{Person} has {Pet}"` or `f"{Integer:i} has {String:name}"`.
- `fields` (`list`\[[`Field`](/api/python/v2.3/semantics/frontend/base/field_class/index.md)], default: `[]`) - Explicit fields for the relationship. If provided and `reading` is empty, a default reading is generated from the fields.
- `short_name` (`str`, default: `""`) - Optional identifier used as the key in `model.relationship_index`.

**Returns:**

- [`Relationship`](/api/python/v2.3/semantics/frontend/base/relationship_class/index.md) - The created relationship.

**Raises:**

- `ValueError` - If neither `reading` nor `fields` is provided.

**Examples:**

Create a relationship between two concepts and define one fact:

```python
from relationalai.semantics import Model, String, define, where

m = Model()
Person = m.Concept("Person", identify_by={"name": String})
Pet = m.Concept("Pet", identify_by={"name": String})
Person.name = m.Property(f"{Person} has {String:name}")
Person.pets = m.Relationship(f"{Person} has {Pet}")
define(
    alice := Person.new(name="Alice"),
    boots := Pet.new(),
    alice.pets(boots),
)
where(Person.pets).select(Person.name).to_df()
```

Create a relationship by specifying fields directly and give it a
stable name via `short_name`:

```python
from relationalai.semantics import Model, String, define
from relationalai.semantics.frontend.base import Field

m = Model()
Person = m.Concept("Person", identify_by={"name": String})
has_pet = m.Relationship(
    fields=[Field("person", Person), Field("pet_name", String)],
    short_name="has_pet",
)
define(alice := Person.new(name="Alice"), has_pet(alice, "boots"))
has_pet.to_df()
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Build a semantic model](/build/modeling/index.md)1) [Declare relationships and properties](/build/modeling/declare-relationships-and-properties/index.md)1. [Declare a relationship with `Model.Relationship`](/build/modeling/declare-relationships-and-properties/index.md#declare-a-relationship-with-modelrelationship)
      2. [Use advanced reasoning](/build/reasoning/index.md) / [Predictive reasoning](/build/reasoning/predictive/index.md)1) [Overview](/build/reasoning/predictive/index.md)1. [What predictive reasoning is](/build/reasoning/predictive/index.md#what-predictive-reasoning-is)

### .`Property`()

```python
Model.Property(
    reading: str = "", fields: list[Field] = [], short_name: str = ""
) -> Property
```

Create a property in this model.

This is the primary way to introduce a new [`Property`](/api/python/v2.3/semantics/frontend/base/property_class/index.md) into a
[`Model`](/api/python/v2.3/semantics/frontend/base/model_class/index.md). The most common way to define a property is with a Python
f-string `reading` that embeds concept/type placeholders. Each embedded
placeholder becomes a field of the property, in order.

Reading strings have the following format:

- Use an f-string and embed types with `{...}`, e.g. `f"{Person} has {Integer:age}"`.
- Name fields with `{Type:name}` (the `name` becomes the attribute
  you access, e.g. `Person.age`).
- For full control, pass an explicit `fields=[Field(...), ...]` list.

**Parameters:**

- `reading` (`str`, default: `""`) - A reading that describes the property fields. Typically an f-string, for example `f"{Person} has {Integer:age}"`.
- `fields` (`list`\[[`Field`](/api/python/v2.3/semantics/frontend/base/field_class/index.md)], default: `[]`) - Explicit fields for the property. If provided and `reading` is empty, a default reading is generated from the fields.
- `short_name` (`str`, default: `""`) - Optional identifier used as the key in `model.relationship_index`.

**Returns:**

- [`Property`](/api/python/v2.3/semantics/frontend/base/property_class/index.md) - The created property.

**Raises:**

- `ValueError` - If neither `reading` nor `fields` is provided.

**Examples:**

Declare a property on a concept, define a couple of entities, and query:

```python
from relationalai.semantics import Integer, Model, String

m = Model()
Person = m.Concept("Person", identify_by={"name": String})
Person.age = m.Property(f"{Person} has {Integer:age}")
m.define(Person.new(name="Alice", age=10), Person.new(name="Bob", age=30))
m.where(Person.age >= 18).select(Person.age).to_df()
```

Create a property by specifying fields directly and give it a stable
name via `short_name`:

```python
from relationalai.semantics import Integer, Model, String
from relationalai.semantics.frontend.base import Field

m = Model()
Person = m.Concept("Person", identify_by={"name": String})
age = m.Property(
    fields=[Field("person", Person), Field("age", Integer)],
    short_name="age",
)
Person.age = age
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Build a semantic model](/build/modeling/index.md)1) [Declare relationships and properties](/build/modeling/declare-relationships-and-properties/index.md)1. [Declare a property with `Model.Property`](/build/modeling/declare-relationships-and-properties/index.md#declare-a-property-with-modelproperty)

### .`select`()

```python
Model.select(*args: StatementAndSchema | None) -> Fragment
```

Return a selection fragment in this model.

This starts a new [`Fragment`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md) with a `select` clause. The
returned fragment is composable and can be chained with
[`Fragment.where`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-where), [`Fragment.define`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-define), and
[`Fragment.require`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-require), then materialized via [`Fragment.to_df`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-to_df).

You can select most values and expressions, including:

- Concepts, relationships/properties, and fields
- Variables and expressions (including arithmetic and comparisons)
- Aggregates and grouped expressions (for example `per(x).sum(y)`)
- Python literals like strings, integers, floats, and booleans
- `None` to produce a null-filled output column

Passing a [`TableSchema`](/api/python/v2.3/semantics/frontend/base/tableschema_class/index.md)
(typically created via `Table.to_schema`)
expands to selecting each column of the table. Selecting a comparison
expression like `Person.age >= 18` produces a boolean output column.

**Parameters:**

- `*args` ([`StatementAndSchema`](/api/python/v2.3/semantics/frontend/base/statementandschema/index.md), default: `()`) - Items to select. Each item may be a [`semantics.frontend.base.Statement`](/api/python/v2.3/semantics/frontend/base/statement/index.md) or a [`TableSchema`](/api/python/v2.3/semantics/frontend/base/tableschema_class/index.md).

**Returns:**

- [`Fragment`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md) - A composable query fragment representing the selection.

**Examples:**

Select a value and a computed boolean column:

```python
from relationalai.semantics import Integer, Model, String

m = Model()
Person = m.Concept("Person", identify_by={"name": String})
Person.age = m.Property(f"{Person} has {Integer:age}")
m.define(Person.new(name="Alice", age=10), Person.new(name="Bob", age=30))
m.select(Person.name, Person.age >= 18).to_df()
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Build a semantic model](/build/modeling/index.md)1) [Derive facts with logic](/build/modeling/derive-facts-with-logic/index.md)1. [Understand PyRel logic constructs](/build/modeling/derive-facts-with-logic/index.md#understand-pyrel-logic-constructs)
   2) [Interact with RelationalAI](/interact/index.md)1) [Query a model with PyRel](/interact/query-a-model-with-pyrel/index.md)1. [Understand fragments and materialization](/interact/query-a-model-with-pyrel/index.md#understand-fragments-and-materialization)
   3) [What's new](/release-notes/index.md)1) [Python package and CLI release notes](/release-notes/python/index.md)1. [Python package and CLI 2.0.0](/release-notes/python/2.0.0/index.md)1) [Bug Fixes](/release-notes/python/2.0.0/index.md#bug-fixes)

### .`where`()

```python
Model.where(*args: Statement) -> Fragment
```

Return a fragment filtered by the given conditions.

This starts a new [`Fragment`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md) with a `where` clause. The
returned fragment is composable and can be chained with
[`Fragment.select`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-select), [`Fragment.define`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-define), and
[`Fragment.require`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-require), then materialized via [`Fragment.to_df`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-to_df).

Multiple conditions passed in a single call are combined with AND. You
can add additional filters by chaining
[`Fragment.where`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-where).

**Parameters:**

- `*args` ([`Statement`](/api/python/v2.3/semantics/frontend/base/statement/index.md), default: `()`) - One or more [`semantics.frontend.base.Statement`](/api/python/v2.3/semantics/frontend/base/statement/index.md) items to use as filter conditions.

**Returns:**

- [`Fragment`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md) - A composable query fragment representing the filter(s).

**Examples:**

Filter and select:

```python
from relationalai.semantics import Integer, Model, String

m = Model()
Person = m.Concept("Person", identify_by={"name": String})
Person.age = m.Property(f"{Person} has {Integer:age}")
m.define(Person.new(name="Alice", age=10), Person.new(name="Bob", age=30))
m.where(Person.age > 21).select(Person.name).to_df()
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Build a semantic model](/build/modeling/index.md)1) [Derive facts with logic](/build/modeling/derive-facts-with-logic/index.md)1. [Understand PyRel logic constructs](/build/modeling/derive-facts-with-logic/index.md#understand-pyrel-logic-constructs)
            2. [Write conditional definitions with `Model.where` and `Model.define`](/build/modeling/derive-facts-with-logic/index.md#write-conditional-definitions-with-modelwhere-and-modeldefine)
         2) [Define requirements](/build/modeling/define-requirements/index.md)1) [Add a scoped requirement with `Model.where`](/build/modeling/define-requirements/index.md#add-a-scoped-requirement-with-modelwhere)
   2) [Interact with RelationalAI](/interact/index.md)1) [Query a model with PyRel](/interact/query-a-model-with-pyrel/index.md)1. [Filter results with `where`](/interact/query-a-model-with-pyrel/index.md#filter-results-with-where)
   3) [What's new](/release-notes/index.md)1) [Python package and CLI release notes](/release-notes/python/index.md)1. [Python package and CLI 2.0.0](/release-notes/python/2.0.0/index.md)1) [Bug Fixes](/release-notes/python/2.0.0/index.md#bug-fixes)

### .`require`()

```python
Model.require(*args: Statement) -> Fragment
```

Return a fragment that adds requirements (constraints).

This starts a new [`Fragment`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md) with a `require` clause. The
returned fragment is composable and can be chained with
[`Fragment.where`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-where) to make a requirement conditional, or with
[`Fragment.require`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-require) to add additional requirements.

A requirement is an existence check: it fails when there are *no* matches.
Roughly speaking, `m.require(expr)` asserts `EXISTS(expr)` and fails
when `NOT EXISTS(expr)`.

For example, `m.require(Person.age > 0)` fails in the following cases:

- There are no `Person` entities.
- There are `Person` entities, but none have an `age` value.
- There are `age` values, but none are greater than zero.

It does *not* fail just because some `Person` entities are missing an
`age` value, or because some ages are non-positive, as long as there
is at least one match for `Person.age > 0`.

To enforce a per-entity requirement, scope it with
[`Model.where`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-where) (for example,
`where(Person).require(Person.age > 0)`) or use `Concept.require`
(for example, `Person.require(Person.age > 0)`). Both of those forms are
equivalent and the choice is mostly a matter of style.

Multiple requirements passed in a single call are enforced together.
You can also apply requirements to an existing fragment by calling
[`Fragment.require`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-require).

**Parameters:**

- `*args` ([`Statement`](/api/python/v2.3/semantics/frontend/base/statement/index.md), default: `()`) - One or more [`semantics.frontend.base.Statement`](/api/python/v2.3/semantics/frontend/base/statement/index.md) items to enforce as requirements.

**Returns:**

- [`Fragment`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md) - A composable fragment representing the requirement(s).

**Examples:**

Require that at least one match exists:

```python
from relationalai.semantics import Integer, Model, String

m = Model()
Person = m.Concept("Person", identify_by={"name": String})
Person.age = m.Property(f"{Person} has {Integer:age}")
m.define(Person.new(name="Alice", age=1), Person.new(name="Bob", age=2))
# Passes because there exists a Person with age >= 0.
m.require(Person.age >= 0)
```

Scope a requirement to enforce it per entity:

```python
# Requires every Person to have an age >= 0.
m.where(Person).require(Person.age >= 0)
```

**Notes:**

Requirements can affect performance:

- Adding more requirements generally increases compilation and execution
  work, especially if a requirement introduces large joins, broad
  disjunctions (for example via
  [`Model.union`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-union)), or
  aggregates over large domains.
- A well-chosen requirement can also improve performance by narrowing
  what needs to be considered (for example by reducing the number
  of matches that flow into later joins or aggregates).
- Prefer scoped requirements (for example `m.require(...).where(...)`)
  when the constraint should only apply under certain conditions.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Build a semantic model](/build/modeling/index.md)1) [Define requirements](/build/modeling/define-requirements/index.md)1. [How a requirement works](/build/modeling/define-requirements/index.md#how-a-requirement-works)
            2. [Add a global requirement with `Model.require`](/build/modeling/define-requirements/index.md#add-a-global-requirement-with-modelrequire)
      2. [Use advanced reasoning](/build/reasoning/index.md) / [Prescriptive reasoning](/build/reasoning/prescriptive/index.md) / [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/index.md)1) [Overview](/build/reasoning/prescriptive/decision-problems/index.md)
         2) [Add constraints](/build/reasoning/prescriptive/decision-problems/constraints/index.md)

### .`define`()

```python
Model.define(*args: Statement) -> Fragment
```

Return a fragment that adds definitions (facts or logic).

This starts a new [`Fragment`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md) with a `define` clause. The
returned fragment is composable and can be chained with
[`Fragment.where`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-where) to make definitions conditional, or with
[`Fragment.define`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-define) to add additional definitions.

Calling [`Model.define`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-define) also
registers the resulting definition fragment with the model, so the
definitions are included when the model is compiled and evaluated by
later queries.

**Parameters:**

- `*args` ([`Statement`](/api/python/v2.3/semantics/frontend/base/statement/index.md), default: `()`) - One or more [`semantics.frontend.base.Statement`](/api/python/v2.3/semantics/frontend/base/statement/index.md) items to define. Common examples include entity creations (`Person.new(...)`) and relationship/property facts.

**Returns:**

- [`Fragment`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md) - A composable fragment representing the definition(s).

**Examples:**

Define some base facts:

```python
from relationalai.semantics import Integer, Model, String

m = Model()
Person = m.Concept("Person", identify_by={"name": String})
Person.age = m.Property(f"{Person} has {Integer:age}")
m.define(Person.new(name="Alice", age=10), Person.new(name="Bob", age=30))
```

Define a derived concept under a condition:

```python
Adult = m.Concept("Adult", extends=[Person])
m.where(Person.age >= 18).define(Adult(Person))
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use RelationalAI with AI Agents](/build/agents/index.md)1) [Get started with a coding agent](/build/agents/start-with-a-coding-agent/index.md)1. [Start building with `/rai-ontology`](/build/agents/start-with-a-coding-agent/index.md#start-building-with-rai-ontology)
      2. [Build a semantic model](/build/modeling/index.md)1) [Declare concepts](/build/modeling/declare-concepts/index.md)1. [What a concept is](/build/modeling/declare-concepts/index.md#what-a-concept-is)
         2) [Define base facts](/build/modeling/define-base-facts/index.md)1) [Define entities and their properties with `Concept.new`](/build/modeling/define-base-facts/index.md#define-entities-and-their-properties-with-conceptnew)
            2) [Define relationship facts](/build/modeling/define-base-facts/index.md#define-relationship-facts)
         3) [Derive facts with logic](/build/modeling/derive-facts-with-logic/index.md)1) [Understand PyRel logic constructs](/build/modeling/derive-facts-with-logic/index.md#understand-pyrel-logic-constructs)
            2) [Write conditional definitions with `Model.where` and `Model.define`](/build/modeling/derive-facts-with-logic/index.md#write-conditional-definitions-with-modelwhere-and-modeldefine)
            3) [Compute derived property values](/build/modeling/derive-facts-with-logic/index.md#compute-derived-property-values)

### .`union`()

```python
Model.union(*items: Value) -> Union
```

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

This constructs a [`Union`](/api/python/v2.3/semantics/frontend/base/union_class/index.md) object that represents a disjunction over multiple *branches*.

Unlike the `|` operator (see [`Variable.__or__`](/api/python/v2.3/semantics/frontend/base/variable_class/index.md#method-__or__)), which picks the
first branch that can succeed, `union` combines the results from *all* branches.

`union` is commonly used in two ways:

- As an OR-combinator in [`Model.where`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-where)
  clauses, for example `m.where(m.union(cond1, cond2))`.
- As a union of multiple derived tables/fragments that return the same
  number of values. The resulting union behaves like a derived table
  whose columns can be selected or unpacked.

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

**Parameters:**

- `*items` ([`Value`](/api/python/v2.3/semantics/frontend/base/value/index.md), default: `()`) - One or more [`semantics.frontend.base.Value`](/api/python/v2.3/semantics/frontend/base/value/index.md) items to union. Each branch must return the same number of values. Branches used purely as filters (for example comparisons, or [`Not`](/api/python/v2.3/semantics/frontend/base/not_class/index.md)) contribute zero output values and are intended to be used as conditions in a `where` clause.

**Returns:**

- [`Union`](/api/python/v2.3/semantics/frontend/base/union_class/index.md) - A composable union object.

**Raises:**

- `relationalai.util.error.RAIException` - Raised if the union branches return different numbers of values.

**Examples:**

Use `union` to OR conditions in a `where` clause:

```python
from relationalai.semantics import Integer, Model, String

m = Model()
Person = m.Concept("Person", identify_by={"name": String})
Person.age = m.Property(f"{Person} has {Integer:age}")
m.define(Person.new(name="Alice", age=10), Person.new(name="Bob", age=70))
m.where(m.union(Person.age < 18, Person.age >= 65)).select(Person.name).to_df()
```

Union two fragments that select the same number of values:

```python
Edge = m.Concept("Edge")
Edge.src = m.Property(f"{Edge} has {Integer:src}")
Edge.dst = m.Property(f"{Edge} has {Integer:dst}")
m.define(Edge.new(src=1, dst=2), Edge.new(src=4, dst=3))
e, src, dst = m.union(
    m.where(Edge, Edge.src <= Edge.dst).select(Edge, Edge.src, Edge.dst),
    m.where(Edge, Edge.src > Edge.dst).select(Edge, Edge.dst, Edge.src),
)
m.select(src, dst).to_df()
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Build a semantic model](/build/modeling/index.md)1) [Derive facts with logic](/build/modeling/derive-facts-with-logic/index.md)1. [Write conditional definitions with `Model.where` and `Model.define`](/build/modeling/derive-facts-with-logic/index.md#write-conditional-definitions-with-modelwhere-and-modeldefine)
         2) [Define requirements](/build/modeling/define-requirements/index.md)1) [How a requirement works](/build/modeling/define-requirements/index.md#how-a-requirement-works)
   2) [What's new](/release-notes/index.md)1) [Python package and CLI release notes](/release-notes/python/index.md)1. [Python package and CLI 2.1.1](/release-notes/python/2.1.1/index.md)1) [Bug Fixes](/release-notes/python/2.1.1/index.md#bug-fixes)

### .`data`()

```python
Model.data(
    data: DataFrame | list[tuple] | list[dict],
    columns: list[str] | None = None,
    schema: dict[str, Concept] | None = None,
) -> Data
```

Create a temporary table from in-memory Python or pandas data.

This converts the provided data into a pandas `DataFrame` and wraps it
as a [`Data`](/api/python/v2.3/semantics/frontend/base/data_class/index.md) object. The resulting object behaves like a table in
the semantics DSL: you can refer to its columns in [`Model.select`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-select),
[`Model.where`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-where), and [`Model.define`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-define), or convert it to a schema
via `Table.to_schema`.

This method is the underlying implementation used by the convenience
wrapper [`data`](/api/python/v2.3/semantics/data/index.md).

**Parameters:**

- `data` (`pandas.DataFrame` | `list`\[`tuple`] | `list`\[`dict`]) - The input data. Supported forms are:

  - A pandas `DataFrame`
  - A list of tuples (each tuple is a row)
  - A list of dicts (each dict is a row)
- `columns` (`list`\[`str`], default: `None`) - Column names to use when `data` is a list of tuples. If omitted, the data will use default integer column labels `0`, `1`, `2`, ... . Those default labels are exposed as `col0`, `col1`, `col2`, ... so you can write `d.col0`, `d.col1`, etc.
- `schema` (`dict`\[`str`, [`Concept`](/api/python/v2.3/semantics/frontend/base/concept_class/index.md)], default: `None`) - Explicit column type overrides. Keys are column names and values are [`Concept`](/api/python/v2.3/semantics/frontend/base/concept_class/index.md) types (for example `Integer` or `String`). When provided, the type for each named column is taken from this mapping instead of being inferred from the data. Columns not present in the mapping are still inferred from the data as usual.

**Returns:**

- [`Data`](/api/python/v2.3/semantics/frontend/base/data_class/index.md) - A table-like object backed by the provided data.

**Raises:**

- `TypeError` - If `data` cannot be converted into a pandas `DataFrame`.

**Examples:**

Create data from a list of dicts and use it directly:

```python
from relationalai.semantics import Model

m = Model()
people_rows = m.data(
    [
        {"name": "Alice", "age": 10},
        {"name": "Bob", "age": 30},
    ]
)
m.select(people_rows.name, people_rows.age).to_df()
```

Provide column names when loading tuple rows:

```python
measurements = m.data([(0, 72.5), (1, 71.9)], columns=["minute", "temperature"])
m.select(measurements.minute, measurements.temperature).to_df()
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Build a semantic model](/build/modeling/index.md)1) [Declare data sources](/build/modeling/declare-data-sources/index.md)1. [Choose the right source type](/build/modeling/declare-data-sources/index.md#choose-the-right-source-type)
            2. [Use CSV data with `Model.data`](/build/modeling/declare-data-sources/index.md#use-csv-data-with-modeldata)
            3. [Use a DataFrame with `Model.data`](/build/modeling/declare-data-sources/index.md#use-a-dataframe-with-modeldata)
            4. [Use inline Python data with `Model.data`](/build/modeling/declare-data-sources/index.md#use-inline-python-data-with-modeldata)
         2) [Define base facts](/build/modeling/define-base-facts/index.md)

### .`not_`()

```python
Model.not_(*items: Statement) -> Not
```

Return a negated condition for use in query filters.

Use [`Model.not_`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-not_) inside [`Model.where`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-where) (or [`Fragment.where`](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md#method-where))
to say “exclude anything that matches this pattern”. For example,
`m.not_(Person.pets)` can be read as “people with no pets”.

If you pass multiple statements, they are treated as a single grouped
condition and the *whole group* is negated. In other words,
`m.not_(a, b)` means “NOT (a AND b)”, not “(NOT a) AND (NOT b)”.
Note that `NOT (a AND b)` is equivalent to `(NOT a) OR (NOT b)`.

**Parameters:**

- `*items` ([`Statement`](/api/python/v2.3/semantics/frontend/base/statement/index.md), default: `()`) - One or more [`semantics.frontend.base.Statement`](/api/python/v2.3/semantics/frontend/base/statement/index.md) items to negate (for example, comparisons, relationship/property patterns, or other filter statements).

**Returns:**

- [`Not`](/api/python/v2.3/semantics/frontend/base/not_class/index.md) - A negation expression.

**Examples:**

Filter to people who have no pets:

```python
from relationalai.semantics import Model, String

m = Model()
Person = m.Concept("Person", identify_by={"name": String})
Pet = m.Concept("Pet", identify_by={"name": String})
Person.pets = m.Relationship(f"{Person} has {Pet}")
m.define(
    alice := Person.new(name="Alice"),
    bob := Person.new(name="Bob"),
    boots := Pet.new(name="boots"),
    bob.pets(boots),
)
m.where(Person, m.not_(Person.pets)).select(Person.name).to_df()
```

Exclude people who have a pet named "boots":

```python
m.where(Person, m.not_(Person.pets.name == "boots")).select(Person.name).to_df()
```

Contrast grouped vs separate negation:

```python
# Exclude people people who have no pets and people who have a pet named "boots".
m.where(Person, m.not_(Person.pets, Person.pets.name == "boots"))
# Exclude only people who have no pets.
m.where(Person, m.not_(Person.pets))
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Build a semantic model](/build/modeling/index.md)1) [Derive facts with logic](/build/modeling/derive-facts-with-logic/index.md)1. [Write conditional definitions with `Model.where` and `Model.define`](/build/modeling/derive-facts-with-logic/index.md#write-conditional-definitions-with-modelwhere-and-modeldefine)

### .`distinct`()

```python
Model.distinct(*items: Value) -> Distinct
```

Mark values as distinct (unique) for use in [`Model.select`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-select) and
aggregates.

This constructs a [`Distinct`](/api/python/v2.3/semantics/frontend/base/distinct_class/index.md) wrapper tied to this model. Use it
to request “unique values only” in two common situations:

- As a SQL `SELECT DISTINCT`-style wrapper by passing it as the *only*
  argument to [`Model.select`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-select), e.g. `m.select(m.distinct(x, y))`.
- As an argument wrapper for aggregates to make them count/sum/etc. over
  unique values, e.g. `count(m.distinct(Person.name))`.

**Parameters:**

- `*items` ([`Value`](/api/python/v2.3/semantics/frontend/base/value/index.md), default: `()`) - One or more [`semantics.frontend.base.Value`](/api/python/v2.3/semantics/frontend/base/value/index.md) items to consider when removing duplicates.

**Returns:**

- [`Distinct`](/api/python/v2.3/semantics/frontend/base/distinct_class/index.md) - An object you pass to [`Model.select`](/api/python/v2.3/semantics/frontend/base/model_class/index.md#method-select)
  or to aggregate functions to request “unique values only”.

**Raises:**

- `relationalai.util.error.RAIException` - Raised when the returned object is used incorrectly (for example, not
  applied to the entire `select(...)`, or not applied to all aggregate
  arguments).

**Examples:**

Count unique names (like SQL `COUNT(DISTINCT name)`):

```python
from relationalai.semantics import Model, String, count

m = Model()
Person = m.Concept("Person")
Person.name = m.Property(f"{Person} has {String:name}")
m.define(
    Person.new(name="Chris"),
    Person.new(name="Chris"),
    Person.new(name="Joe"),
)
m.select(count(m.distinct(Person.name))).to_df()
```

Select unique rows by wrapping all selected values:

```python
name_counts = count(Person).per(Person.name)
m.select(m.distinct(Person.name, name_counts)).to_df()
```

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Rules-based reasoning](/build/reasoning/rules-based/index.md)1) [Aggregate and group data](/build/reasoning/rules-based/aggregate-and-group-data/index.md)1. [Deduplicate aggregate inputs with `distinct()`](/build/reasoning/rules-based/aggregate-and-group-data/index.md#deduplicate-aggregate-inputs-with-distinct)

### .`path`()

```python
Model.path(
    *args: Ref | Concept | Chain | PathPattern | Relationship | Union,
) -> PathPattern
```

Create a path pattern over this model's concepts and relationships.

This is the entry point to the path library. Pass the pattern elements
(nodes and edges) in traversal order; see
[`PathPattern`](/api/python/v2.3/semantics/std/path/pathpattern_class/index.md) for the
argument grammar and usage examples.

**Parameters:**

- `*args` ([`Ref`](/api/python/v2.3/semantics/frontend/base/ref_class/index.md) | [`Concept`](/api/python/v2.3/semantics/frontend/base/concept_class/index.md) | [`Chain`](/api/python/v2.3/semantics/frontend/base/chain_class/index.md) | `PathPattern` | [`Relationship`](/api/python/v2.3/semantics/frontend/base/relationship_class/index.md) | [`Union`](/api/python/v2.3/semantics/frontend/base/union_class/index.md), default: `()`) - One or more arguments defining the path pattern to be matched. Each argument may be a node ([`Concept`](/api/python/v2.3/semantics/frontend/base/concept_class/index.md) or [`Ref`](/api/python/v2.3/semantics/frontend/base/ref_class/index.md)), an edge ([`Chain`](/api/python/v2.3/semantics/frontend/base/chain_class/index.md) or [`Relationship`](/api/python/v2.3/semantics/frontend/base/relationship_class/index.md)), or a nested sub-path ([`PathPattern`](/api/python/v2.3/semantics/std/path/pathpattern_class/index.md)). See [`PathPattern`](/api/python/v2.3/semantics/std/path/pathpattern_class/index.md) for how they join.

**Returns:**

- `PathPattern` - A reusable path pattern specification.

**Raises:**

- `ValueError` - If called with no arguments.

**Examples:**

```python
# A single edge, any ``Person`` as the initial node.
m.path(Person.follows)
# An explicit initial node concept and a variable number of edges.
m.path(Person, Person.follows.repeat(1, 3))
# Explicit initial and final node Refs, selected based on existence of a matching path.
A, Z = Person.ref(), Person.ref()
m.where(m.path(A, Person.follows.repeat(1, 5), Z).exists()).select(A, Z)
```

**Notes:**

The path library is currently in **preview**; see
[`relationalai.semantics.std.path`](/api/python/v2.3/semantics/std/path/index.md) for the preview status.

**Referenced By:**

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use advanced reasoning](/build/reasoning/index.md) / [Path reasoning](/build/reasoning/path/index.md)1) [Create a path pattern](/build/reasoning/path/create-a-path-pattern/index.md)1. [Understand path basics](/build/reasoning/path/create-a-path-pattern/index.md#understand-path-basics)
         2) [Use path results](/build/reasoning/path/use-path-results/index.md)1) [Available API](/build/reasoning/path/use-path-results/index.md#available-api)

## Used By

1. [semantics](/api/python/v2.3/semantics/index.md)1) [frontend](/api/python/v2.3/semantics/frontend/index.md) / [base](/api/python/v2.3/semantics/frontend/base/index.md)1. [Concept](/api/python/v2.3/semantics/frontend/base/concept_class/index.md)
      2. [DSLBase](/api/python/v2.3/semantics/frontend/base/dslbase_class/index.md)
      3. [Data](/api/python/v2.3/semantics/frontend/base/data_class/index.md)
      4. [DerivedTable](/api/python/v2.3/semantics/frontend/base/derivedtable_class/index.md)
      5. [Distinct](/api/python/v2.3/semantics/frontend/base/distinct_class/index.md)
      6. [Fragment](/api/python/v2.3/semantics/frontend/base/fragment_class/index.md)
      7. [Literal](/api/python/v2.3/semantics/frontend/base/literal_class/index.md)
      8. [Match](/api/python/v2.3/semantics/frontend/base/match_class/index.md)
      9. [Not](/api/python/v2.3/semantics/frontend/base/not_class/index.md)
      10. [NumberConcept](/api/python/v2.3/semantics/frontend/base/numberconcept_class/index.md)
      11. [Property](/api/python/v2.3/semantics/frontend/base/property_class/index.md)
      12. [Reading](/api/python/v2.3/semantics/frontend/base/reading_class/index.md)
      13. [Relationship](/api/python/v2.3/semantics/frontend/base/relationship_class/index.md)
      14. [Table](/api/python/v2.3/semantics/frontend/base/table_class/index.md)
      15. [Union](/api/python/v2.3/semantics/frontend/base/union_class/index.md)
      16. [Variable](/api/python/v2.3/semantics/frontend/base/variable_class/index.md)
   2) [inspect](/api/python/v2.3/semantics/inspect/index.md)1) [schema](/api/python/v2.3/semantics/inspect/schema/index.md)
   3) [reasoners](/api/python/v2.3/semantics/reasoners/index.md)1) [graph](/api/python/v2.3/semantics/reasoners/graph/index.md) / [core](/api/python/v2.3/semantics/reasoners/graph/core/index.md)1. [Graph](/api/python/v2.3/semantics/reasoners/graph/core/graph_class/index.md)
      2) [prescriptive](/api/python/v2.3/semantics/reasoners/prescriptive/index.md) / [problem](/api/python/v2.3/semantics/reasoners/prescriptive/problem/index.md)1) [Problem](/api/python/v2.3/semantics/reasoners/prescriptive/problem/problem_class/index.md)

## Referenced By

1. [RelationalAI Documentation](/index.md)1) [Build With RelationalAI](/build/index.md)1. [Use RelationalAI with AI Agents](/build/agents/index.md)1) [Get started with a coding agent](/build/agents/start-with-a-coding-agent/index.md)1. [Start building with `/rai-ontology`](/build/agents/start-with-a-coding-agent/index.md#start-building-with-rai-ontology)
      2. [Configure PyRel](/build/configuration/index.md)1) [Overview](/build/configuration/index.md)1. [How validation works](/build/configuration/index.md#how-validation-works)
      3. [Meet PyRel](/build/meet-pyrel/index.md)1) [Define concepts and properties](/build/meet-pyrel/index.md#define-concepts-and-properties)
      4. [Build a semantic model](/build/modeling/index.md)1) [Create a model instance](/build/modeling/create-model-instance/index.md)1. [Create a Model instance](/build/modeling/create-model-instance/index.md#create-a-model-instance)
            2. [Configure a model's connection](/build/modeling/create-model-instance/index.md#configure-a-models-connection)
         2) [Declare concepts](/build/modeling/declare-concepts/index.md)1) [What a concept is](/build/modeling/declare-concepts/index.md#what-a-concept-is)
            2) [Declare a concept](/build/modeling/declare-concepts/index.md#declare-a-concept)
            3) [Declare a subconcept](/build/modeling/declare-concepts/index.md#declare-a-subconcept)
            4) [View all of a model's concepts](/build/modeling/declare-concepts/index.md#view-all-of-a-models-concepts)
         3) [Declare relationships and properties](/build/modeling/declare-relationships-and-properties/index.md)1) [Declare a property with `Model.Property`](/build/modeling/declare-relationships-and-properties/index.md#declare-a-property-with-modelproperty)
            2) [Declare a relationship with `Model.Relationship`](/build/modeling/declare-relationships-and-properties/index.md#declare-a-relationship-with-modelrelationship)
         4) [Declare data sources](/build/modeling/declare-data-sources/index.md)1) [Choose the right source type](/build/modeling/declare-data-sources/index.md#choose-the-right-source-type)
            2) [Use a Snowflake table with `Model.Table`](/build/modeling/declare-data-sources/index.md#use-a-snowflake-table-with-modeltable)
            3) [Use CSV data with `Model.data`](/build/modeling/declare-data-sources/index.md#use-csv-data-with-modeldata)
            4) [Use a DataFrame with `Model.data`](/build/modeling/declare-data-sources/index.md#use-a-dataframe-with-modeldata)
            5) [Use inline Python data with `Model.data`](/build/modeling/declare-data-sources/index.md#use-inline-python-data-with-modeldata)
            6) [Create model constants with `Model.Enum`](/build/modeling/declare-data-sources/index.md#create-model-constants-with-modelenum)
         5) [Define base facts](/build/modeling/define-base-facts/index.md)1) [Define entities and their properties with `Concept.new`](/build/modeling/define-base-facts/index.md#define-entities-and-their-properties-with-conceptnew)
            2) [Define relationship facts](/build/modeling/define-base-facts/index.md#define-relationship-facts)
         6) [Derive facts with logic](/build/modeling/derive-facts-with-logic/index.md)1) [Understand PyRel logic constructs](/build/modeling/derive-facts-with-logic/index.md#understand-pyrel-logic-constructs)
            2) [Write conditional definitions with `Model.where` and `Model.define`](/build/modeling/derive-facts-with-logic/index.md#write-conditional-definitions-with-modelwhere-and-modeldefine)
            3) [Compute derived property values](/build/modeling/derive-facts-with-logic/index.md#compute-derived-property-values)
            4) [Match multiple entities of the same type with `Concept.ref`](/build/modeling/derive-facts-with-logic/index.md#match-multiple-entities-of-the-same-type-with-conceptref)
         7) [Define requirements](/build/modeling/define-requirements/index.md)1) [How a requirement works](/build/modeling/define-requirements/index.md#how-a-requirement-works)
            2) [Add a global requirement with `Model.require`](/build/modeling/define-requirements/index.md#add-a-global-requirement-with-modelrequire)
            3) [Add a scoped requirement with `Model.where`](/build/modeling/define-requirements/index.md#add-a-scoped-requirement-with-modelwhere)
      5. [Use advanced reasoning](/build/reasoning/index.md)1) [Path reasoning](/build/reasoning/path/index.md)1. [Create a path pattern](/build/reasoning/path/create-a-path-pattern/index.md)1) [Understand path basics](/build/reasoning/path/create-a-path-pattern/index.md#understand-path-basics)
            2. [Use path results](/build/reasoning/path/use-path-results/index.md)1) [Available API](/build/reasoning/path/use-path-results/index.md#available-api)
         2) [Predictive reasoning](/build/reasoning/predictive/index.md)1) [Overview](/build/reasoning/predictive/index.md)1. [What predictive reasoning is](/build/reasoning/predictive/index.md#what-predictive-reasoning-is)
            2) [Solve a classification problem](/build/reasoning/predictive/solve-a-classification-problem/index.md)1) [Import the libraries and create a model](/build/reasoning/predictive/solve-a-classification-problem/index.md#import-the-libraries-and-create-a-model)
         3) [Prescriptive reasoning](/build/reasoning/prescriptive/index.md) / [Solve a decision problem](/build/reasoning/prescriptive/decision-problems/index.md)1) [Overview](/build/reasoning/prescriptive/decision-problems/index.md)1. [How PyRel represents a decision problem](/build/reasoning/prescriptive/decision-problems/index.md#how-pyrel-represents-a-decision-problem)
            2) [Create a Problem object](/build/reasoning/prescriptive/decision-problems/create/index.md)
            3) [Add constraints](/build/reasoning/prescriptive/decision-problems/constraints/index.md)
            4) [Work with solutions](/build/reasoning/prescriptive/decision-problems/solutions/index.md)1) [Read solver-level variable values](/build/reasoning/prescriptive/decision-problems/solutions/index.md#read-solver-level-variable-values)
         4) [Rules-based reasoning](/build/reasoning/rules-based/index.md)1) [Aggregate and group data](/build/reasoning/rules-based/aggregate-and-group-data/index.md)1. [Deduplicate aggregate inputs with `distinct()`](/build/reasoning/rules-based/aggregate-and-group-data/index.md#deduplicate-aggregate-inputs-with-distinct)
   2) [Interact with RelationalAI](/interact/index.md)1) [Query a model with PyRel](/interact/query-a-model-with-pyrel/index.md)1. [Import your model definitions in PyRel](/interact/query-a-model-with-pyrel/index.md#import-your-model-definitions-in-pyrel)
         2. [Understand fragments and materialization](/interact/query-a-model-with-pyrel/index.md#understand-fragments-and-materialization)
         3. [Filter results with `where`](/interact/query-a-model-with-pyrel/index.md#filter-results-with-where)
         4. [Export results to Snowflake tables with `into` and `exec`](/interact/query-a-model-with-pyrel/index.md#export-results-to-snowflake-tables-with-into-and-exec)
   3) [What's new](/release-notes/index.md)1) [Python package and CLI release notes](/release-notes/python/index.md)1. [Python package and CLI 2.0.0](/release-notes/python/2.0.0/index.md)1) [New Features and Enhancements](/release-notes/python/2.0.0/index.md#new-features-and-enhancements)
            2) [Bug Fixes](/release-notes/python/2.0.0/index.md#bug-fixes)
         2. [Python package and CLI 2.0.1](/release-notes/python/2.0.1/index.md)1) [New Features and Enhancements](/release-notes/python/2.0.1/index.md#new-features-and-enhancements)
         3. [Python package and CLI 2.1.0](/release-notes/python/2.1.0/index.md)1) [New Features and Enhancements](/release-notes/python/2.1.0/index.md#new-features-and-enhancements)
            2) [Bug Fixes](/release-notes/python/2.1.0/index.md#bug-fixes)
         4. [Python package and CLI 2.1.1](/release-notes/python/2.1.1/index.md)1) [Bug Fixes](/release-notes/python/2.1.1/index.md#bug-fixes)
