> ## Documentation Index
> Fetch the complete documentation index at: https://learn.nextedy.com/llms.txt
> Use this file to discover all available pages before exploring further.

# EntityQuery

> The EntityQuery is the top-level query object in Nextedy POWERSHEET that encapsulates all parameters for retrieving data from Siemens Polarion ALM.

<img src="https://mintcdn.com/none-17b4493f/_GvZqQF94OXoqCqL/powersheet-v3/diagrams/reference/query-api/entity-query/diagram-1.svg?fit=max&auto=format&n=_GvZqQF94OXoqCqL&q=85&s=9fdfd38b2b5f92afbaeda54f07005161" alt="diagram" style={{ maxWidth: "520px", width: "100%" }} width="520" height="210" data-path="powersheet-v3/diagrams/reference/query-api/entity-query/diagram-1.svg" />

***

## Query Properties

| Name         | Type     | Default      | Description                                                                                                                                                                                      |
| ------------ | -------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `from`       | `string` | **Required** | Root entity type to query. Must match a valid entity type defined in the [domain model](/powersheet-v3/reference/data-model/domainmodeltypes) (e.g., `UserNeed`, `SystemRequirement`, `Hazard`). |
| `where`      | `object` | `None`       | Filter [predicates](/powersheet-v3/reference/query-api/predicates) applied to query results. Supports property comparisons, null checks, and composite AND/OR logic.                             |
| `expand`     | `array`  | `None`       | [Expand clause](/powersheet-v3/reference/query-api/expand-clause) specifying navigation properties to load inline. Supports nested expansion for multi-level relationships.                      |
| `orderBy`    | `array`  | `None`       | Sorting clause with property paths and sort direction. Ascending is the default; append `desc` for descending order.                                                                             |
| `parameters` | `object` | `None`       | Runtime [query context](/powersheet-v3/reference/query-api/query-context) parameters controlling execution behavior (baseline queries, document scoping, debug).                                 |

EntityQuery does not support a `select` clause for projecting specific properties. All properties defined for the entity type in the domain model are returned automatically.

***

## The `from` Clause

The `from` clause specifies the root entity type for the query. The value must exactly match an entity type name defined in the `domainModelTypes` section of the domain model YAML. Entity type names use PascalCase.

```yaml theme={null}
sources:
  - id: user_needs
    query:
      from: UserNeed
```

The server resolves the `from` value against the metadata system to locate the entity type definition, including its mapped Polarion work item type, properties, and available navigation properties. If the entity type is not found in the metadata registry, the query fails with a validation error.

**Common entity types** (using the standard RTM example model):

| Entity Type         | Polarion Type  | Typical Use                 |
| ------------------- | -------------- | --------------------------- |
| `UserNeed`          | `user_need`    | Top-level requirements      |
| `SystemRequirement` | `sys_req`      | System-level requirements   |
| `DesignRequirement` | `des_req`      | Design-level requirements   |
| `Hazard`            | `hazard`       | Risk analysis entities      |
| `RiskControl`       | `risk_control` | Risk mitigation measures    |
| `Chapter`           | `heading`      | Document structure headings |

For the complete list of entity type properties and Polarion type mappings, see [Domain Model Types](/powersheet-v3/reference/data-model/domainmodeltypes) and [Polarion Type Mapping](/powersheet-v3/reference/data-model/polarion-mapping).

***

## The `where` Clause

The `where` clause defines filter predicates that restrict the result set. Predicates are split during execution into two categories:

* **Lucene-compatible predicates** -- translated to Polarion Lucene queries and executed server-side for performance
* **In-memory post-filters** -- complex predicates that cannot be expressed in Lucene, applied after the initial fetch

This splitting is transparent to the query author. See [Predicates](/powersheet-v3/reference/query-api/predicates) for the full predicate syntax and [Query Splitting](/powersheet-v3/reference/query-api/query-splitting) for details on how predicates are categorized.

```yaml theme={null}
sources:
  - id: active_requirements
    query:
      from: SystemRequirement
      where:
        status:
          ne: "rejected"
```

**Null checks** are supported for filtering by field presence:

```yaml theme={null}
# Find entities where title is not null
where:
  title:
    ne: null

# Find entities where title is null
where:
  title:
    eq: null
```

For composite filtering with AND/OR logic, see the [Predicates](/powersheet-v3/reference/query-api/predicates) reference.

***

## The `expand` Clause

The `expand` clause specifies which navigation properties to load inline with the query results. Navigation properties represent [relationships](/powersheet-v3/reference/data-model/relationships) between entity types defined in the domain model. The expand syntax differs based on the relationship cardinality.

### Many-to-One (N:1) Expansion

For many-to-one relationships, the expand loads a single related entity. Uses the `direct` navigation property name from the relationship definition.

```yaml theme={null}
sources:
  - id: user_needs
    query:
      from: UserNeed
    expand:
      - name: chapter
```

This loads the parent `Chapter` for each `UserNeed`. In the domain model, the relationship defines `direct.name: chapter` on the many side.

### One-to-Many (1:N) Expansion

For one-to-many relationships (the reverse of N:1), the expand loads a collection of child entities. Uses the `back` navigation property name.

```yaml theme={null}
sources:
  - id: chapters
    query:
      from: Chapter
    expand:
      - name: userNeeds
```

This loads all child `UserNeed` entities for each `Chapter`. In the sheet, these appear as expandable child rows creating a new hierarchy level.

### Many-to-Many (M:N) Expansion

Many-to-many relationships require a **two-level expand** that traverses through an association entity to reach the target entity.

```yaml theme={null}
sources:
  - id: user_needs
    query:
      from: UserNeed
    expand:
      - name: systemRequirements
        expand:
          - name: systemRequirement
```

The first level (`systemRequirements`) navigates to the association entities. The second level (`systemRequirement`) navigates from each association to the actual target `SystemRequirement` entity. This two-level pattern is required because the domain model represents M:N links through an intermediate association.

For complete expand syntax including nested multi-level expansion, see [Expand Clause](/powersheet-v3/reference/query-api/expand-clause).

***

## The `orderBy` Clause

The `orderBy` clause defines the sort order for query results. Each item specifies a property path and an optional sort direction.

| Property       | Type     | Default  | Description                                                                                                          |
| -------------- | -------- | -------- | -------------------------------------------------------------------------------------------------------------------- |
| Property path  | `string` | Required | Dot-notation path to the property to sort by (e.g., `title`, `severity`, `chapter.title`).                           |
| Sort direction | `string` | `asc`    | Append `desc` after the property path for descending order. Ascending is the default when no direction is specified. |

```yaml theme={null}
sources:
  - id: sorted_requirements
    query:
      from: SystemRequirement
      orderBy:
        - severity desc
        - title
```

**Property path syntax** supports both direct properties and navigation paths using dot notation. The path is validated against the entity type metadata to ensure it references a valid property.

The `orderBy` clause in the source configuration maps to the `sortBy` property in the sheet configuration, which uses a slightly different format:

```yaml theme={null}
sortBy:
  - id: severity
    direction: desc
  - id: title
    direction: asc
```

<Tip title="Sort Order Validation">
  All property paths in the `orderBy` clause are validated against the entity type metadata during query construction. If a property path references a non-existent property, the query returns a validation error. Use property names exactly as defined in the domain model.
</Tip>

***

## The `parameters` Object

Runtime parameters control query execution behavior without modifying the core query structure. Parameters are passed as key-value pairs in the `parameters` object.

| Parameter              | Type      | Default | Description                                                                                                                                                                                                           |
| ---------------------- | --------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `revision`             | `string`  | `None`  | Execute the query against a specific project baseline or revision instead of current data. See [Baseline and Revision Queries](/powersheet-v3/reference/query-api/baseline-and-revision-queries).                     |
| `currentDoc`           | `string`  | `None`  | Document ID for scoping query results to a specific Polarion LiveDoc. Used with `currentDocConstraint`. See [Document Filtering](/powersheet-v3/reference/query-api/document-filtering).                              |
| `currentDocConstraint` | `string`  | `None`  | Entity type name or navigation property path specifying how document scoping is applied. Can be the entity type name (scopes directly) or a dot-notation path to a navigation property (scopes through relationship). |
| `explain`              | `boolean` | `false` | Enables debug output showing the generated Lucene query, predicate splitting decisions, and execution plan.                                                                                                           |

<Note title="Document Scoping">
  When both `currentDoc` and `currentDocConstraint` are provided, the query engine restricts results to work items linked to or contained within the specified document. The constraint value determines how the scope is applied -- either directly on the queried entity type or through a navigation property path. This is the mechanism behind Powersheet's document-centric filtering.
</Note>

***

## Query Execution Flow

The server API processes an EntityQuery through the following stages:

1. **Metadata resolution** -- The `from` clause is resolved against the metadata registry to identify the target entity type, its Polarion work item type mapping, and available properties.
2. **Security enforcement** -- The server verifies the current user has read permission for the entity type. If the entity type is not readable, the query fails immediately.
3. **Predicate splitting** -- The `where` clause predicates are analyzed and split into Lucene-compatible server queries and in-memory post-filters.
4. **Document pre-filtering** -- If document-level predicates exist in the `where` clause, documents are pre-resolved to narrow the work item query scope.
5. **Lucene query execution** -- Lucene-compatible predicates are translated and executed against Polarion to fetch matching work items.
6. **Post-filtering** -- In-memory filters are applied to the fetched results to handle predicates that cannot be expressed in Lucene.
7. **Constraint application** -- Domain model constraints and project scoping rules are enforced on the result set.
8. **Navigation property expansion** -- Properties specified in the `expand` clause are loaded for each result entity, following the relationship paths defined in the domain model.
9. **Sorting** -- Results are ordered per the `orderBy` clause.
10. **Result assembly** -- The final result set is returned with entity metadata.

***

## Query Result Structure

Each entity returned by an EntityQuery includes standard metadata fields alongside the domain model properties:

| Field            | Type       | Description                                                            |
| ---------------- | ---------- | ---------------------------------------------------------------------- |
| `$type`          | `string`   | Fully qualified entity type name from the metadata system.             |
| `entityTypeName` | `string`   | Domain model entity type name (e.g., `UserNeed`, `SystemRequirement`). |
| `id`             | `string`   | Polarion work item ID.                                                 |
| `title`          | `string`   | Work item title.                                                       |
| `updated`        | `datetime` | Last modification timestamp.                                           |
| `project`        | `object`   | Project foreign key reference.                                         |

Additional fields depend on the properties defined for the entity type in the domain model. Custom fields, enum properties, and computed (server-rendered) properties are included when defined.

<Info title="Server-Rendered Properties">
  Properties backed by Velocity templates are evaluated server-side during query execution. The Velocity context includes variables `item`, `tx`, `context`, and `pObject` for template evaluation. See [Velocity Templates](/powersheet-v3/reference/server-rendering/velocity-templates) and [Context Variables](/powersheet-v3/reference/server-rendering/context-variables).
</Info>

***

## Primitive Field Type Mapping

When entity properties are returned in query results, Polarion custom field types are mapped to their runtime equivalents:

| Polarion Field Type | Runtime Type | Notes                    |
| ------------------- | ------------ | ------------------------ |
| `string`            | `string`     | Plain text values        |
| `text`              | `string`     | Multi-line text          |
| `richtext`          | `string`     | HTML-formatted rich text |
| `boolean`           | `boolean`    | `true` / `false`         |
| `integer`           | `number`     | Whole numbers            |
| `float`             | `number`     | Decimal numbers          |
| `currency`          | `number`     | Currency values          |
| `date`              | `datetime`   | Date values              |
| `time`              | `datetime`   | Time values              |
| `duration`          | `string`     | Duration representation  |

***

## Enum Property Resolution

When the metadata system discovers enum properties on an entity type, Powersheet automatically creates data sources for loading the available enum options. This powers dropdown pickers in the sheet without manual source configuration.

The auto-generated enum source uses the following resolution pattern:

* **Source ID**: `system.enums.<enumId>` (e.g., `system.enums.severity`)
* **Query construction**: Filters by `polarionProto`, `polarionType`, `projectId`, and `enumId` from the entity metadata
* **Display mapping**: Each enum option provides a display label and internal value for the picker

This process is triggered during metadata initialization and completes before any user queries execute.

***

## Complete YAML Example

A complete source configuration demonstrating all EntityQuery properties within a sheet configuration:

```yaml theme={null}
sources:
  - id: rtm_matrix
    query:
      from: UserNeed
      where:
        status:
          ne: "rejected"
      orderBy:
        - severity desc
        - title
    expand:
      - name: chapter
      - name: systemRequirements
        expand:
          - name: systemRequirement
            expand:
              - name: designRequirements
                expand:
                  - name: designRequirement

columns:
  title:
    title: User Need
    hasFocus: true
    width: 250
  severity:
    title: Severity
    width: 80
  chapter:
    title: Chapter
    display: title
    isReadOnly: true
    list:
      search:
        - title
  chapter.title:
    title: Chapter Title
    isReadOnly: true
  systemRequirements.systemRequirement:
    title: System Req
    list:
      search:
        - objectId
        - title
      createNew: true
  systemRequirements.systemRequirement.title:
    title: SysReq Title
    hasFocus: true
  systemRequirements.systemRequirement.designRequirements.designRequirement:
    title: Design Req
    list:
      search:
        - objectId
        - title
  systemRequirements.systemRequirement.designRequirements.designRequirement.title:
    title: DesReq Title
    hasFocus: true
```

This configuration demonstrates:

* **Root query** with `from`, `where`, and `orderBy` on `UserNeed`
* **N:1 expansion** via `chapter` (direct navigation property)
* **M:N expansion** via `systemRequirements.systemRequirement` (two-level association traversal)
* **Deep nesting** continuing through `designRequirements.designRequirement` for a full traceability chain
* **Column bindings** using dot-notation matching the expansion path structure
* **Picker configuration** with `list.search` and `list.createNew` on reference columns

***

## Cardinality and Query Pattern Summary

| Cardinality | Domain Model                                                 | Source Expand                                                 | Column Binding                         | Sheet Behavior                   |
| ----------- | ------------------------------------------------------------ | ------------------------------------------------------------- | -------------------------------------- | -------------------------------- |
| **N:1**     | `cardinality: many-to-one`, `direct.name: chapter`           | `- name: chapter`                                             | `chapter`, `chapter.title`             | Single-value reference picker    |
| **1:N**     | Reverse of N:1, `back.name: userNeeds`                       | `- name: userNeeds`                                           | `userNeeds`                            | Child rows (new hierarchy level) |
| **M:N**     | `cardinality: many-to-many`, `back.name: systemRequirements` | `- name: systemRequirements` then `- name: systemRequirement` | `systemRequirements.systemRequirement` | Multi-item reference picker      |

***

## Related Pages

* [Predicates](/powersheet-v3/reference/query-api/predicates) -- filter syntax for `where` clauses
* [Expand Clause](/powersheet-v3/reference/query-api/expand-clause) -- detailed expand syntax and nesting rules
* [Query Context](/powersheet-v3/reference/query-api/query-context) -- runtime parameter reference
* [Document Filtering](/powersheet-v3/reference/query-api/document-filtering) -- document-scoped query patterns
* [Baseline and Revision Queries](/powersheet-v3/reference/query-api/baseline-and-revision-queries) -- historical data queries
* [Domain Model Types](/powersheet-v3/reference/data-model/domainmodeltypes) -- entity type definitions
* [Relationships](/powersheet-v3/reference/data-model/relationships) -- relationship and navigation property configuration
* [Sources](/powersheet-v3/reference/sheet-config/sources) -- sheet source configuration referencing EntityQuery
