Skip to content

Queries

Queries find entities that match structural conditions.

SIECS is an archetype ECS, so a query primarily matches tables, not individual entity records. Once a table matches, all rows in that table satisfy the table-level component conditions and can be iterated as a batch.

Queries are used directly by applications and internally by systems and observers.

SIECS queries support required component fields, read/write access metadata, optional fields, filter-only and exclusion terms, relation filters, inherited upward reads, IsA restriction, table ordering and persistent table-match caches.

SIECS does not implement a textual query language, query variables, arbitrary boolean expression trees or configurable cache kinds. Those features are therefore intentionally absent from this manual.

Name Meaning in SIECS
Entity Generation-aware ecs_entity_t identity.
Component Registered per-entity data or tag.
Relation Registered source-to-target edge in the relation namespace.
Resource One-per-world typed value, used as access metadata by systems.
Archetype Exact structural type represented by one table.
Term One condition/access item in a query descriptor.
Field Component data exposed by an iterator.
Iterator Batch cursor returned by ecs_query_iter().
Owned field Component data stored in the current table.
Shared field Read-only data resolved outside the current table.

A simple moving-entity query:

ecs_query_id_t q = ecs_query({
.components = {
ecs_inout(Position),
ecs_in(Velocity),
},
});

An optional component query:

ecs_query_id_t q = ecs_query({
.components = {
ecs_inout(Position),
ecs_in_optional(Velocity),
},
});

An exclusion query:

ecs_query_id_t q = ecs_query({
.components = {
ecs_in(Position),
ecs_not(Frozen),
},
});

C++ queries can declare their callback signature explicitly, for example ecs::query<Position&, const Velocity&>(). This permits generic lambda parameters such as [](auto& position, const auto& velocity) { ... } while keeping scheduler access metadata explicit. Without a signature, callback parameters must declare their types.

build() returns a move-only RAII handle that releases its query on scope exit. Use build_raw() only when transferring ownership to C code, which must call ecs_query_fini(). An explicitly typed handle keeps the same access signature across callbacks. An untyped handle infers its accesses from each callback and rebuilds its cache only when that signature changes.

An archetype query can cache matching tables because a table has a stable structural type.

Suppose the world has these tables:

T0 {}
T1 {Position}
T2 {Position, Velocity}
T3 {Position, Velocity, Enemy}
T4 {Health, Enemy}

A query requiring Position and Velocity matches T2 and T3.

A persistent SIECS query stores this table relationship in its query cache. Iteration then walks cached table ids and returns the current rows from those tables.

Entities may continuously move in and out of T2 and T3; the query does not need to rebuild an entity list for every frame.

When a new archetype table appears, SIECS checks active query caches and adds the table to those that match.

When table storage moves because capacity grows, cached field metadata is refreshed so later iteration points at the new column addresses.

This makes table creation and query registration slightly more expensive in exchange for cheap repeated iteration.

Persistent queries are appropriate when the same structural condition is evaluated repeatedly: systems, repeated game-loop scans, tools and observers.

Temporary query helpers are convenient for one-off setup or tests.

Cache policy is fixed by the query implementation. SIECS query ids are backed by query cache structures. The meaningful lifetime choice is whether application code creates a short-lived query or keeps the id or C++ handle for repeated use.

Query cost is affected by both matching entity count and matching table count.

100000 rows in 2 tables

usually has less outer-loop overhead than:

100000 rows in 2000 tables

even though the same number of entities is processed.

Many independent structural tags can fragment a world into many archetypes. Use structural distinctions when they improve matching, not as a default replacement for every boolean value.

ecs_query_id_t q = ecs_query({
.components = {
ecs_inout(Position),
ecs_in(Velocity),
},
});
/* use q */
ecs_query_fini(q);

The C descriptor uses fixed-capacity, zero-terminated arrays for components, resources and relations. The C++ query_handle is move-only, infers returned component access from the callback and releases its query id on destruction.

ecs_iter_t it = ecs_query_iter(q);
while (ecs_iter_next(&it)) {
Position *position = ecs_field(&it, 0);
const Velocity *velocity = ecs_field(&it, 1);
for (uint32_t i = 0; i < it.count; i++) {
position[i].x += velocity[i].x;
position[i].y += velocity[i].y;
}
}

The outer loop advances through matching table batches. The inner loop advances through rows of the current table.

it.entities points to the entity handle array for the current batch.

Fields are numbered by field-producing component term order.

These produce fields: EcsIn, EcsOut, EcsInOut, optional variants and EcsInUp variants.

These affect matching but do not produce fields: EcsFilter, EcsNot, relation terms and resource terms.

An optional component term does not require the component to exist.

.components = {
ecs_inout(Position),
ecs_in_optional(Velocity),
}

For each batch, the Velocity field pointer is either a valid pointer for the entire batch or NULL for the entire batch.

Use ecs_field_kind() to determine whether a field is EcsFieldOwned, EcsFieldShared or EcsFieldNone.

Shared fields usually come from inherited data and must be treated as read-only for that batch.

ecs_in(Position) /* const field */
ecs_out(Position) /* writable field; old value is not required */
ecs_inout(Position) /* readable and writable field */
ecs_filter(Enemy) /* required, without a returned field */
ecs_not(Disabled) /* excluded component */

Access metadata serves two purposes: it describes how iteration code may use a field and systems use it for scheduler dependency analysis.

EcsIn means read-only. EcsOut means write. EcsInOut means read/write. Optional versions preserve the same access intent when the component exists.

Correct access declarations allow independent systems to run in parallel while preventing unsafe overlap between writers and readers.

SIECS supports component exclusion directly with EcsNot / ecs_not().

ecs_query({
.components = {
ecs_in(Position),
ecs_not(Frozen),
},
});

Relation exclusion uses ecs_not_rel(Relation).

SIECS does not expose general nested boolean query operators such as arbitrary OR scopes. Model such cases as separate queries, structural tags or application logic.

Optional terms return data when available without affecting whether the table matches.

ecs_in_optional(Velocity)
ecs_inout_optional(Health)

Avoid making every component optional merely to reduce query count. A callback full of optional branches can be harder to optimize than several focused queries.

ecs_rel(GroupOf) /* required relation */
ecs_rel_opt(GroupOf) /* optional relation */
ecs_not_rel(GroupOf) /* excluded relation */
ecs_to(GroupOf, group) /* exact target */
ecs_depth(ChildOf, 3) /* exact depth */

ecs_to() requires a ByTarget relation. ecs_depth() requires a ByDepth relation.

Inspecting relation targets while iterating

Section titled “Inspecting relation targets while iterating”

For Dense and ByDepth relations:

const ecs_relation_target_t *targets = ecs_targets(&it, GroupOf);

For ByTarget, all rows in a target-grouped table share the target:

ecs_entity_t group = ecs_target_shared(&it, GroupOf);

SIECS supports upward component lookup through an acyclic ByTarget relation:

ECS_RELATION(TransformParent, {
.storage = EcsRelationByTarget,
.on_delete_target = EcsRemoveRelation,
.acyclic = true,
});
ECS_RELATION_REGISTER(TransformParent);
ecs_up(Transform, TransformParent)

The built-in ChildOf relation uses ByDepth storage; use a separate acyclic ByTarget relation for these upward component reads. The same relation can also provide optional reads:

ecs_up_optional(Transform, TransformParent)

Traversal is limited to the operations described above.

SIECS query component terms normally use the currently iterated entity as their source.

Cross-entity data is modeled through upward relation reads, explicit relation target inspection, resources or direct entity access outside the hot field loop.

A query can restrict matches to entities inheriting from a specific base:

ecs_query_id_t q = ecs_query({
.components = { ecs_in(Position) },
.is_a = enemy_base,
});

Read-only queries can see shared inherited components.

Writable terms require local writable storage. If an entity only has a shared inherited value, create an owned override before writing.

SIECS exposes table ordering rather than arbitrary per-row component sorting.

Order by relation target:

.order_by = ecs_order_by_target(GroupOf)

Order by hierarchy depth:

.order_by = ecs_order_by_depth(ChildOf)

The order applies to matching table batches. It does not define row order inside a table.

ecs_query_each is useful for short C scans:

ecs_query_each(it, i, ecs_in(Position)) {
const Position *p = ecs_field(&it, 0);
use(p[i]);
}

For repeated frame work, keep a persistent query or use a system.

Field pointers refer directly to table storage.

Adding or removing components from an iterated entity can move rows, compact the table and invalidate pointers.

The safest patterns are to modify ordinary values in place, defer structural changes, collect entity handles for later mutation or use systems whose normal execution participates in SIECS deferred command handling.

ecs_query_count(query) returns the current number of matching entities.

It is useful for diagnostics, sizing output buffers and tool displays. Avoid calling it repeatedly inside an inner entity loop.

For hot queries:

  • keep persistent queries instead of recreating them each frame;
  • prefer focused required terms;
  • declare read/write intent accurately;
  • avoid unnecessary archetype fragmentation;
  • keep structural mutation out of the inner row loop;
  • use table batches directly rather than per-entity random lookup;
  • treat shared inherited fields as read-only;
  • measure the real workload, including migration and scheduler cost.

ecs_query_desc_t contains four major pieces:

components[]
resources[]
relations[]
order_by
is_a

The component, resource and relation arrays are zero-terminated fixed-capacity descriptor arrays.

This keeps query creation allocation-light and makes descriptor construction straightforward in C.

The component term array has ECS_QUERY_TERM_CAPACITY slots.

A term stores a component id and encoded access mode.

Typed macros such as ecs_in(Position) build these terms for compile-time component declarations.

For dynamic component ids, fill ecs_component_term_t directly.

Resources are separate metadata:

.resources = {
{ .id = ecs_id(Time), .access = EcsIn },
}

Resource terms never determine whether an entity table matches.

They exist primarily so systems can describe global read/write dependencies.

Direct query iteration may carry resource metadata, but resources are accessed through the resource API rather than ecs_field().

Relation filters have their own array because relations are not component ids.

Each term records:

  • relation id;
  • optional target/depth value;
  • relation query kind.

This lets SIECS validate storage-mode-specific operations at query creation.

At query creation/table creation time, SIECS determines whether a table satisfies the descriptor.

Conceptually, component matching checks:

required terms ⊆ table effective components
excluded terms ∩ table effective components = ∅

Optional terms do not affect acceptance.

Relation terms add relation-specific structural conditions.

The query also applies default exclusion rules for Disabled and Abstract unless explicitly mentioned.

The runtime can use compact metadata such as bloom masks to quickly reject tables that cannot possibly contain required components before doing more exact matching.

This is an implementation detail, but it explains why component ids/structural types are organized for efficient table-level tests.

Application code should not depend on the exact bloom representation.

With inheritance, a table can expose a component effectively even when the value is shared from a base rather than owned as a local column.

Query matching therefore distinguishes:

  • structural/local ownership;
  • effective readable availability;
  • writable local availability.

A read-only query may match shared inherited data.

A writable query cannot treat a shared base value as writable instance storage.

The C++ query builder wraps the same descriptor model.

Typical operations include:

ecs_query_id_t q = ecs_query({
.components = {
ecs_filter(Position),
ecs_inout_optional(Velocity),
ecs_not(Frozen),
},
.relations = {
ecs_to(GroupOf, group), /* implies the relation is present */
},
.is_a = base,
});

Typed callback signatures communicate component access:

Position *p = ecs_field(&it, 0);
const Velocity *v = ecs_field(&it, 1);
p[i].x += v[i].x;

Const references express read intent. Mutable references express writable intent.

Optional wrappers express optional fields.

The C++ API does not create a different query engine; it builds the C descriptor and owns the query id.

After ecs_iter_next() succeeds, the iterator contains a view of one current batch.

That view is valid until the next iterator advance or until structural mutation invalidates the underlying table storage.

Treat:

  • it.entities;
  • field pointers;
  • relation target arrays;

as borrowed batch views.

ecs_iter_next() skips empty batches for normal iteration.

A persistent query may still know that an empty table structurally matches so it can immediately iterate it if entities later enter that table.

it.entities[i] is the generation-aware handle for row i.

Use it when a callback needs identity, relation operations or deferred structural commands.

Do not infer identity from row index.

For an owned field:

Position *p = ecs_field(&it, field);

p[i] corresponds to it.entities[i].

This row alignment across columns is the core table invariant.

A shared field is not an array with one independent element per row.

It can point to a value provided by a base/ancestor that applies to all entities in the batch.

Use field-kind information and treat the shared pointer as read-only.

Do not index a shared value as if every row owned a different object unless the API specifically documents that representation.

Required readable data.

It can be owned or shared according to inheritance semantics.

A system declaring only EcsIn does not conflict with another reader of the same data.

Required local writable data.

Use when old contents are not semantically needed by the callback.

The scheduler treats it as a write.

Required local read/write data.

This is the common mutable component term.

Optional read.

The table may or may not provide the field.

When present, inherited/shared reads are possible according to component/query semantics.

Optional local writable field.

The query can match tables where it is absent, but when present it is writable local storage.

Required presence without field materialization.

Useful for tags or components that select a population but whose value is not read.

It avoids spending a field slot/pointer on data the callback does not use.

Required absence.

Exclusion is evaluated at table matching time.

Read through an acyclic target-grouped relation to the nearest ancestor/source with the component.

This is useful for hierarchy-like configuration/transform reads.

Because the resolved data belongs to another entity, it is read-only.

A Dense relation can be required/optional/excluded.

The target for each source row is available as an array through ecs_targets_id().

Exact-target matching is not the primary optimized operation for Dense storage.

ByDepth includes per-source target information plus depth.

Queries can filter depth and order table batches by depth.

Use it for parent/child-like relations where layer information is part of the workload.

ByTarget organizes matching around target identity.

It enables efficient:

  • exact target filters;
  • shared target retrieval for a batch;
  • upward access through compatible acyclic relations.

The structural grouping can increase table count when target cardinality is large.

ecs_query_order_t can hold a comparator callback and user data.

The callback compares tables, not arbitrary entity rows.

It must not mutate the world.

Use custom table ordering when built-in target/depth ordering does not cover a table-level scheduling need.

Even if table ordering is stable for equal keys in an implementation path, do not treat row order as persistent identity.

Packed rows change when entities enter/leave a table.

If deterministic entity ordering is a simulation requirement, create explicit ordering data/structures.

Creating a query has work:

  • compile/validate terms;
  • find current matching tables;
  • allocate/cache query state;
  • register for future table updates.

Destroying it releases that state.

For work performed every frame, repeated create/destroy throws away the main benefit of persistent cache setup.

Systems already own persistent queries, so prefer a system when work belongs to the scheduler.

Temporary query helpers remain ideal for setup tools, tests and rare commands.

Registering queries while the scheduler is executing parallel work is restricted.

Registration changes global query indexes and table-cache relationships.

Create long-lived queries during initialization/module import rather than dynamically from worker callbacks.

SIECS normal query behavior excludes:

  • Disabled;
  • Abstract.

This means an ordinary query:

ecs_in(Position)

does not process paused entities or template bases.

To query disabled entities, explicitly include/filter Disabled.

To inspect abstract/template entities, explicitly include/filter Abstract.

This design reduces repetition in normal simulation systems.

Position + Velocity

Use required fields, persistent query/system, value mutation only.

Position + Velocity + Enemy(filter)

Use EcsFilter for the marker if its data is not needed.

Position + optional Acceleration

Good when both cases share most of the same loop.

If the branches are large/different, two queries may be better.

local Transform + up WorldSettings through ChildOf

Use upward read only when the relation’s storage/acyclic rules support it.

Position + GroupOf(target = selected_group)

Choose ByTarget storage and exact-target term.

This repeatedly pays registration/cache creation cost.

Keep a handle or create a system.

If a component only determines membership, use EcsFilter.

A shared field belongs to a base/ancestor.

Create an override.

Structural change can move/compact rows.

Defer it or mutate after the current batch.

This can generate many structural combinations.

Use a field when the state is volatile and not a major query partition.

Repeated ecs_get(other_entity, ...) can destroy locality.

When possible, express the needed data as query fields, relation grouping or resources.

When a query unexpectedly matches nothing:

  1. confirm component ids are registered;
  2. confirm entity is alive;
  3. check whether it owns/is effectively exposing required components;
  4. check Disabled/Abstract;
  5. validate relation storage mode against ecs_to/ecs_depth/ecs_up;
  6. check the is_a restriction;
  7. check exclusions;
  8. inspect whether expected structural changes have flushed from a defer scope.

When a query matches too much:

  1. add missing filter/tag terms;
  2. verify relation target restriction;
  3. check optional terms were not intended to be required;
  4. remember inheritance can make read-only components effectively available.