Queries
Introduction
Section titled “Introduction”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.
Definitions
Section titled “Definitions”| 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. |
Examples
Section titled “Examples”A simple moving-entity query:
ecs_query_id_t q = ecs_query({ .components = { ecs_inout(Position), ecs_in(Velocity), },});auto q = ecs::query().build();q.each([](Position &position, const Velocity &velocity) { position.x += velocity.x; position.y += velocity.y;});An optional component query:
ecs_query_id_t q = ecs_query({ .components = { ecs_inout(Position), ecs_in_optional(Velocity), },});auto q = ecs::query().build();q.each([](Position &position, ecs::optional<const Velocity> velocity) { if (velocity) { position.x += velocity->x; position.y += velocity->y; }});An exclusion query:
ecs_query_id_t q = ecs_query({ .components = { ecs_in(Position), ecs_not(Frozen), },});auto q = ecs::query() .without<Frozen>() .build();
q.each([](const Position &position) { // Frozen entities do not reach this callback.});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.
Performance and Caching
Section titled “Performance and Caching”Caching: what is it?
Section titled “Caching: what is it?”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.
Query cache maintenance
Section titled “Query cache maintenance”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.
Tradeoffs
Section titled “Tradeoffs”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.
Table count matters
Section titled “Table count matters”Query cost is affected by both matching entity count and matching table count.
100000 rows in 2 tablesusually has less outer-loop overhead than:
100000 rows in 2000 tableseven 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.
Creating queries
Section titled “Creating queries”Persistent query
Section titled “Persistent query”ecs_query_id_t q = ecs_query({ .components = { ecs_inout(Position), ecs_in(Velocity), },});
/* use q */ecs_query_fini(q);auto q = ecs::query().build();q.each([](Position &position, const Velocity &velocity) { position.x += velocity.x; position.y += velocity.y;});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.
Iteration
Section titled “Iteration”Iteration
Section titled “Iteration”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; }}q.each([](Position &position, const Velocity &velocity) { position.x += velocity.x; position.y += velocity.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.
Field numbering
Section titled “Field numbering”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.
Optional fields
Section titled “Optional fields”An optional component term does not require the component to exist.
.components = { ecs_inout(Position), ecs_in_optional(Velocity),}q.each([](Position &position, ecs::optional<const Velocity> velocity) { if (velocity) { position.x += velocity->x; }});For each batch, the Velocity field pointer is either a valid pointer for the
entire batch or NULL for the entire batch.
Field kind
Section titled “Field kind”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.
Reference
Section titled “Reference”Components
Section titled “Components”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 */ecs::query() .with<Enemy>() .without<Disabled>() .each([](Position &position) { // Position& is read/write; use const Position& for read-only access. });Access modifiers
Section titled “Access modifiers”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.
Not Operator
Section titled “Not Operator”SIECS supports component exclusion directly with EcsNot / ecs_not().
ecs_query({ .components = { ecs_in(Position), ecs_not(Frozen), },});ecs::query() .without<Frozen>() .each([](const Position &position) { // Frozen entities are excluded. });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 Operator
Section titled “Optional Operator”Optional terms return data when available without affecting whether the table matches.
ecs_in_optional(Velocity)ecs_inout_optional(Health)ecs::query().each([]( ecs::optional<const Velocity> velocity, ecs::optional<Health> health) { // Test each optional before dereferencing it.});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.
Relation terms
Section titled “Relation terms”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::query().with_relation<GroupOf>();ecs::query().with<GroupOf>(group);ecs::query().depth<ChildOf>(3);
// Optional/excluded relation checks use the typed entity handle.ecs::query().each([](ecs::entity entity) { bool has_group = entity.has_relation<GroupOf>(); (void)has_group;});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);q.each([](ecs::entity source) { ecs::entity target = source.target<GroupOf>(); (void)target;});For ByTarget, all rows in a target-grouped table share the target:
ecs_entity_t group = ecs_target_shared(&it, GroupOf);q.each([](ecs::entity source) { ecs::entity group = source.target<GroupOf>(); (void)group;});Relationship Traversal
Section titled “Relationship Traversal”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)struct TransformParent {};ecs::relation<TransformParent>({ .storage = EcsRelationByTarget, .on_delete_target = EcsRemoveRelation, .acyclic = true,});ecs::query() .up<Transform, TransformParent>() .each([](const Transform &transform) {});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)ecs::query() .up<Transform, TransformParent>() .each([](ecs::optional<const Transform> transform) { if (transform) { // use inherited transform } });Traversal is limited to the operations described above.
Source
Section titled “Source”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.
Component Inheritance
Section titled “Component Inheritance”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,});auto q = ecs::query() .is_a(enemy_base) .build();
q.each([](const Position &position) {});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.
Sorting
Section titled “Sorting”SIECS exposes table ordering rather than arbitrary per-row component sorting.
Order by relation target:
.order_by = ecs_order_by_target(GroupOf)ecs::query().order_by_target<GroupOf>();Order by hierarchy depth:
.order_by = ecs_order_by_depth(ChildOf)ecs::query().order_by_depth<ChildOf>();The order applies to matching table batches. It does not define row order inside a table.
Temporary queries
Section titled “Temporary queries”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]);}ecs::query().each([](const Position &position) { use(position);});For repeated frame work, keep a persistent query or use a system.
Structural mutation during iteration
Section titled “Structural mutation during iteration”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.
Query count
Section titled “Query count”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.
Performance checklist
Section titled “Performance checklist”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.
Query descriptor anatomy
Section titled “Query descriptor anatomy”ecs_query_desc_t contains four major pieces:
components[]resources[]relations[]order_byis_aThe 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.
Component term capacity
Section titled “Component term capacity”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.
Resource term capacity
Section titled “Resource term capacity”Resources are separate metadata:
.resources = { { .id = ecs_id(Time), .access = EcsIn },}ecs::system("ReadTime") .each([](ecs::res<const Time> time) { use(*time); });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 term capacity
Section titled “Relation term capacity”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.
Table matching
Section titled “Table matching”At query creation/table creation time, SIECS determines whether a table satisfies the descriptor.
Conceptually, component matching checks:
required terms ⊆ table effective componentsexcluded 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.
Bloom prefilter
Section titled “Bloom prefilter”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.
Exact versus effective component presence
Section titled “Exact versus effective component presence”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.
C++ query API
Section titled “C++ query API”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,});ecs::query() .with<Position>() .optional<Velocity>() .without<Frozen>() .with<GroupOf>(group) .is_a(base) .build();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;q.each([](Position &p, const Velocity &v) { p.x += v.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.
Iteration internals
Section titled “Iteration internals”Batch lifetime
Section titled “Batch lifetime”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.
Non-empty iteration
Section titled “Non-empty iteration”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.
Entity handles
Section titled “Entity handles”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.
Owned arrays
Section titled “Owned arrays”For an owned field:
Position *p = ecs_field(&it, field);q.each([](Position &position) { position.x += 1;});p[i] corresponds to it.entities[i].
This row alignment across columns is the core table invariant.
Shared fields
Section titled “Shared fields”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.
Access modes in more detail
Section titled “Access modes in more detail”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.
EcsOut
Section titled “EcsOut”Required local writable data.
Use when old contents are not semantically needed by the callback.
The scheduler treats it as a write.
EcsInOut
Section titled “EcsInOut”Required local read/write data.
This is the common mutable component term.
EcsInOptional
Section titled “EcsInOptional”Optional read.
The table may or may not provide the field.
When present, inherited/shared reads are possible according to component/query semantics.
EcsInOutOptional
Section titled “EcsInOutOptional”Optional local writable field.
The query can match tables where it is absent, but when present it is writable local storage.
EcsFilter
Section titled “EcsFilter”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.
EcsNot
Section titled “EcsNot”Required absence.
Exclusion is evaluated at table matching time.
EcsInUp / EcsInUpOptional
Section titled “EcsInUp / EcsInUpOptional”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.
Relation query semantics by storage
Section titled “Relation query semantics by storage”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
Section titled “ByDepth”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
Section titled “ByTarget”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.
Query ordering
Section titled “Query ordering”Custom comparator
Section titled “Custom comparator”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.
Stable assumptions
Section titled “Stable assumptions”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.
Persistent versus temporary lifetime
Section titled “Persistent versus temporary lifetime”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.
Query creation during parallel scheduling
Section titled “Query creation during parallel scheduling”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.
Default filters
Section titled “Default filters”SIECS normal query behavior excludes:
Disabled;Abstract.
This means an ordinary query:
ecs_in(Position)ecs::query().each([](const Position &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.
Query patterns
Section titled “Query patterns”Hot update
Section titled “Hot update”Position + VelocityUse required fields, persistent query/system, value mutation only.
Marker-filtered update
Section titled “Marker-filtered update”Position + Velocity + Enemy(filter)Use EcsFilter for the marker if its data is not needed.
Optional enhancement
Section titled “Optional enhancement”Position + optional AccelerationGood when both cases share most of the same loop.
If the branches are large/different, two queries may be better.
Parent/ancestor read
Section titled “Parent/ancestor read”local Transform + up WorldSettings through ChildOfUse upward read only when the relation’s storage/acyclic rules support it.
Target-group iteration
Section titled “Target-group iteration”Position + GroupOf(target = selected_group)Choose ByTarget storage and exact-target term.
Common query mistakes
Section titled “Common query mistakes”Recreating a system query every frame
Section titled “Recreating a system query every frame”This repeatedly pays registration/cache creation cost.
Keep a handle or create a system.
Using filter data as a field
Section titled “Using filter data as a field”If a component only determines membership, use EcsFilter.
Writing shared inherited data
Section titled “Writing shared inherited data”A shared field belongs to a base/ancestor.
Create an override.
Mutating structure while holding pointers
Section titled “Mutating structure while holding pointers”Structural change can move/compact rows.
Defer it or mutate after the current batch.
Modeling every boolean as a tag
Section titled “Modeling every boolean as a tag”This can generate many structural combinations.
Use a field when the state is volatile and not a major query partition.
Random lookups inside a contiguous loop
Section titled “Random lookups inside a contiguous loop”Repeated ecs_get(other_entity, ...) can destroy locality.
When possible, express the needed data as query fields, relation grouping or resources.
Query debugging checklist
Section titled “Query debugging checklist”When a query unexpectedly matches nothing:
- confirm component ids are registered;
- confirm entity is alive;
- check whether it owns/is effectively exposing required components;
- check
Disabled/Abstract; - validate relation storage mode against
ecs_to/ecs_depth/ecs_up; - check the
is_arestriction; - check exclusions;
- inspect whether expected structural changes have flushed from a defer scope.
When a query matches too much:
- add missing filter/tag terms;
- verify relation target restriction;
- check optional terms were not intended to be required;
- remember inheritance can make read-only components effectively available.

