Element query reference¶
This page describes the current engine contract. Start with the practical guide for complete script examples, or query editing for discovery and editor integration.
Public API and compatibility¶
The supported scripting and editor API consists of the query/test models,
operators, presets, catalogues, field descriptors, input descriptions, results,
validation functions and errors exported by multiconn_archicad.utilities.queries.
The draft API (QueryRow, QueryRows, RowIssue, QueryBuildResult,
validate_row, and build_query) is public in queries.editing.
Supported extension interfaces are TestModel, PropertyTestModel,
TestRegistry, FieldInfo, ContextSource, ContextBuilder, and
EvaluationContext. New serialized kinds require library integration into the
declared unions; runtime registration of arbitrary predicate kinds is not supported.
Concrete source loaders and their singleton instances, ColumnData, execution
orchestration, FieldCheck, FieldPredicate, QueryValidationContext, and
BUILTIN_QUERY_FIELDS are internal implementation details. They are not exported
from queries and carry no public compatibility promise. Tests and implementation
examples may import them directly from their defining modules.
Query structure¶
Import executable models from multiconn_archicad.utilities.queries.
| Model | Required data | Meaning |
|---|---|---|
Query |
where |
Versioned executable expression |
PropertyPredicate |
field_id, test |
Property GUID and a compatible property test |
ClassificationPredicate |
field_id, test |
Classification system GUID and classification test |
ElementTypePredicate |
test |
Membership in the test's concrete type tuple |
LayerPredicate |
test |
Assignment to a selected layer GUID |
LayerNamePredicate |
test |
Assignment to a layer whose name passes a text test |
LayerCombinationPredicate |
test |
Layer visibility in a selected combination GUID |
LayerCombinationNamePredicate |
test |
Layer visibility in any combination whose name passes a text test |
AllOf |
Nonempty items |
All children must match |
AnyOf |
Nonempty items |
At least one child must match |
Each predicate and test has a kind discriminator. Python constructors supply
the default discriminator; JSON must contain it. Query/test models are frozen,
reject unknown fields, and validate on construction. Collections use tuples in
Python and arrays in JSON. Groups may nest. There is no general negation node;
negative comparisons are operators on individual test families.
from multiconn_archicad.models.tapir.types import ElementType
from multiconn_archicad.utilities.queries import ElementTypePredicate, ElementTypeTest, Query
query = Query(where=ElementTypePredicate(test=ElementTypeTest(types=(ElementType.WALL, ElementType.DOOR))))
assert query.schema_version == "1.0"
ElementTypeTest accepts valid individual types and combinations, including the
five presets. The presets are
convenience values; a query stores concrete types and has no preset identifier.
Unknown is an API response sentinel and is rejected as a query operand.
Comparisons and property conditions¶
| Test family | Operators | Operand |
|---|---|---|
TextTest |
is, is not, contains, does not contain, starts with, ends with |
String |
IntegerTest |
is, is not, is greater than, is greater than or equal to, is less than, is less than or equal to |
Integer |
RealTest |
Same six numeric operators | Finite number |
BooleanTest |
is, is not |
Boolean |
EnumTest |
is, is not |
Single-choice enumeration label |
GuidTest |
is, is not |
UUID |
LayerTest |
is, is not |
Layer attribute UUID |
LayerCombinationTest |
is, is not |
Layer combination attribute UUID |
MultiEnumTest |
is, contains, does not contain |
Choice-label tuple |
StringListTest |
is, contains, does not contain |
String tuple |
IntegerListTest |
Same collection operators | Strict integer tuple |
RealListTest |
Same collection operators | Finite-number tuple |
ClassificationTest |
Equality, presence, branch, direct-child comparisons | Item UUID when required; see classification operator table |
ElementTypeTest |
Membership through types |
Concrete element-type tuple |
Text comparisons use Unicode casefold(). Whitespace is significant. For
example, External equals EXTERNAL, but not External. Serialization keeps
the original operand; it does not save the case-folded form.
IntegerTest accepts only Integer properties and integer operands, excluding
Booleans and floats (including 3.0). It parses returned strings with int()
and uses exact equality and ordering, preserving integer precision.
RealTest accepts only Real properties, including unitless reals and all measure
types. Its operands accept finite integers/floats, excluding Booleans. Strings,
null, NaN, and infinity are rejected. Returned values must also be finite.
It parses returned strings with float() and compares using
math.isclose(actual, operand, rel_tol=1e-10, abs_tol=1e-10):
| Operator | Real comparison |
|---|---|
is |
Close |
is not |
Not close |
is greater than |
Greater and not close |
is greater than or equal to |
Greater or close |
is less than |
Less and not close |
is less than or equal to |
Less or close |
Closeness means abs(actual - operand) <= max(1e-10 * max(abs(actual), abs(operand)), 1e-10).
The constants are fixed for Real tests. They were selected using property
round trips and geometry within +/-10,000 metres on each coordinate axis;
they are an empirical comparison policy, not a universal error bound.
Values within the band compare as equal for all six operators. For example,
"29.999999999999996" matches is 30 and fails is less than 30.
Near zero the absolute term applies; at larger magnitudes the relative term grows.
Comparison does not round or modify the returned value or saved operand.
Query reads explicitly request
GetPropertyValuesOfElements.useSIUnits=True together with availability. Tapir
returns precise locale-independent numeric strings: operands use SI units for
quantities, except angles use degrees, deliberately matching architectural
practice. The evaluator performs no further unit conversion or locale parsing.
A malformed numeric string such as "3,00" remains
an evaluation error; there is no fallback to display values.
Discovery selects IntegerTest or RealTest from the property's value type.
Serialized tests use kind="integer" and kind="real", respectively.
Existing property utility callers retain display strings. The optional keyword
use_si_units=True on get_property_values_per_element_result() opts into these
canonical reads and requires Tapir 2.0.0 or newer. With its default False, the
new wire flag is omitted so older Tapir versions keep their existing behavior.
Boolean operands must be actual Booleans. Tapir value strings are interpreted
using its "True"/"False" representation.
EnumTest and MultiEnumTest use exact, case-sensitive display labels, including
whitespace. Operands must occur in the property's current possibleEnumValues.
Discovery publishes these labels as choices; option GUIDs are not operands.
Definitions with missing choices or duplicate labels remain unsupported because
the read path cannot identify those choices reliably. A multi-enum definition
with an empty label is also unsupported: an empty read represents no selection.
MultiEnumTest(operator=CollectionOperator.IS, value=("Red", "Blue")) compares the entire selected
set, ignoring order. Repeated operand choices are rejected. An empty tuple matches
an empty selection. contains requires every requested label to be present;
does not contain requires none of the requested labels to be present. Partial
overlap therefore matches neither operator. They compare whole items: Blue
does not match Light Blue. Python uses tuples for selection operands; JSON uses
arrays. All three operators require collection operands, including for one label.
An empty operand collection matches both membership operators.
The test parses the returned ; separator. This initial implementation assumes
choice labels do not contain semicolons. Such labels are accepted but queries
against them may give incorrect results; no escaping or structured-read fallback
is implemented.
GuidTest compares parsed UUID identity, so letter case and UUID spelling do not
change equality. An invalid returned UUID is an evaluation error. The all-zero
UUID is compared as an ordinary UUID, without an inferred unassigned state.
StringListTest, IntegerListTest, and RealListTest compare ordered lists.
is requires the same length, order, and repeated items; (1, 2) differs from
(2, 1) and (1, 1, 2). contains requires every requested item to occur;
does not contain requires none of them to occur. Membership ignores operand
order and multiplicity: requesting (1, 1) only requires one occurrence of 1.
Item comparisons use these rules:
- Strings use Unicode casefold, preserving whitespace, like TextTest.
- Integers compare exactly, preserving precision above the float integer range.
- Reals use the same
1e-10relative and absolute tolerance as RealTest. All measures use SI units, except degrees for angles.
All three operators take a tuple (JSON array), including for one item. An empty operand tuple matches both membership operators. Repeated list operands are allowed. All returned numeric items are parsed before comparison: a malformed or non-finite item is an evaluation error even if another item matches. Numeric reads use the existing canonical SI path.
List reads split the ; separator. String-list items follow the same
no-semicolon assumption as multi-enum labels. An empty returned string means
an empty list. It cannot distinguish [] from [""]; queries involving that
ambiguity may give incorrect results. Empty items alongside other items are
preserved when their separator is present. There is no structured-read fallback.
Property discovery supports scalar single-string, integer/real, Boolean and GUID properties, single-choice and multiple-choice String enumerations with the metadata described above, and String/Integer/Real lists. Boolean lists, GUID lists, undefined metadata, and unsupported enumeration metadata remain visible as unsupported fields.
Unavailable and undefined property values make every currently supported
property comparison false, including negative comparisons. They do not mean
that is not matches. Other read/parse failures remain errors. Property-state
operators such as an availability test are not currently implemented.
A successfully unclassified assignment has different semantics: it matches
negative classification comparisons and has no value. An assignment read
error remains an error. Branch matching includes the chosen item; direct-child
matching excludes it. See classification semantics.
Layers and saved layer combinations¶
The combined field catalogue offers four fixed fields under Layer: Layer,
Layer Name, Layer Combination, and Layer Combination Name. Their references are
{"kind": "layer"}, {"kind": "layer_name"},
{"kind": "layer_combination"}, and {"kind": "layer_combination_name"}.
They have no field_id: the selected attribute GUID belongs in test.value.
LayerTest and LayerCombinationTest store one UUID, with is or is not.
Their descriptors offer GUID-valued choices labelled with current attribute
names. A missing selected GUID is an invalid test, including for negative tests
and empty candidate populations. Names and indices are not saved alongside it.
Renaming an attribute preserves the selection; deleting/recreating it requires
repairing the query. Tapir's layer reindex operation also recreates the attribute.
Both name predicates use TextTest, including Unicode casefold matching and
significant whitespace. Layer Name applies that test to each layer name.
Layer Combination Name first selects matching combination names, then matches
elements on the union of their visible layers. Thus does not contain Structural
means visibility in any combination whose name does not contain that text; an
element can also be visible in a Structural combination. No matching names means
no matching elements, including with negative text operators.
Layer Combination is not instead matches elements outside the selected
combination's visible-layer set. Visibility means isHidden == false in that
saved combination; current layer visibility, locking, wireframe, intersection
groups, and other view settings do not affect the test. Execution never activates
a combination or changes project settings.
Discovery captures GetAttributesByType headers for reference validation and
editor choices. Execution reuses discovered layer headers when available and
reads the built-in GeneralElemProperties / LayerIndex Integer property in one
batch through the normal property-reading utility. Its SDK property GUID is
a74b66a1-629a-4807-83ac-5fff0553a3ac; the official property-name lookup does not
expose this technical definition on the verified Archicad 27 instances.
Canonical reads return integer strings, which are parsed exactly with int().
Per-element API errors, unavailable/undefined values, malformed integer strings,
and indices missing from the layer catalogue remain evaluation errors, including
for negative tests. No element-details projection or custom response adapter is
needed.
Combination predicates load all saved combinations and their visible layer
GUIDs in one batch, shared by every combination predicate in the query. Loading
all combinations keeps this first implementation independent of query operators;
combination-name text tests run during evaluation. Layer metadata and whole
command failures remain query-wide errors. Empty populations validate references
without reading element properties or combination visibility. Execution uses neither
FilterElements.layerIndices nor API.GetAttributesIndices for layer criteria.
The public LayerAttribute(guid, index, name) snapshot record and LayerInfo,
LayerNameInfo, LayerCombinationInfo, LayerCombinationNameInfo descriptors
also support offline catalogues through QueryFieldCatalogue(fields=[...]).
Sources load raw data only: element layer indices, layer names and GUIDs, and
saved combination visibility. Each predicate reads the actual element layer from
that context and applies its test in evaluate(). Layer Name calls
TextTest.evaluate(layer.name) directly. Layer Combination Name applies its text
test to the names of combinations in which the element's layer is visible and
requires any match. No query comparison runs during preparation or loading, and
there are no selection callbacks, request models, or cached predicate answers.
Validation¶
There are three distinct boundaries:
- Model construction checks shape, discriminators, operators, and operands.
validate_query()checks references and test compatibility against supplied metadata snapshots. It makes no API calls.- Bound discovery/search/filter methods check the supported Tapir version; execution also checks query-schema compatibility and discovers current referenced fields before evaluating candidates.
from multiconn_archicad.utilities.queries import validate_query
# This query references only built-in element-type metadata.
validation = validate_query(query, [])
assert validation.is_valid
validation.raise_for_errors()
For property/classification expressions, pass their catalogues or a
QueryFieldCatalogue. Validation visits all branches, even branches that cannot
match or inputs with no elements. Issue codes are unknown_field,
unsupported_field, and invalid_test. Each issue includes its expression
location, field reference, message, and available display metadata.
raise_for_errors() raises QueryValidationError with the validation result.
Duplicate property/system identities in a catalogue are invalid. Duplicate display labels are allowed: labels are not identities. A compatible test model alone does not prove an operand belongs to the chosen classification system.
Search scope and candidate collection¶
api.utilities.element.find_elements(query) and find_elements_result(query)
share the same candidate listing and evaluation path. Query execution requires
Tapir 2.0.0 or newer.
Default listing arguments are:
| Setting | Default |
|---|---|
| Databases | Main/floor-plan database, explicitly identified by GUID d5d16dd4-093f-4674-895d-410d634d8c7e |
| Filters | IncludeSubElemObjects and IsIndependent |
The default is independent of the active window. No additional visibility or editability filter is added. Explicit structural component types can still be queried: independence is not a general exclusion of every hierarchical child.
The existing keyword arguments databases= and filters= are advanced listing
overrides. None selects the respective default. A supplied sequence replaces
that default; it is not merged with it. Empty sequences are forwarded to Tapir,
so they should not be used as a synonym for a documented default. The supported
first-release query workflow is floor-plan search. Cross-database predicates,
provenance, and mixed-branch scope semantics remain deferred.
The engine derives a safe element-type upper bound from the expression. AND intersects bounds; OR unions them, with an unrestricted alternative making the bound unrestricted. A finite bound uses typed listing; an unrestricted bound uses general listing. An impossible bound avoids listing after validation. The original expression is always evaluated, preserving branch relationships.
Candidate GUIDs are deduplicated in first-listing order. Typed requests follow the element enum's declaration order. Required property/system reads are deduplicated and batched; repeated predicates share prepared columns.
get_3d_elements() is a separate convenience utility with a main-3D type
whitelist. It retains its existing current-database behavior. It uses both flags
on Tapir 1.5.3+, and IsIndependent alone on older versions. Do not infer its
database scope or IFC-export eligibility from the query defaults.
Results and failures¶
Method on api.utilities.element |
Return / error policy |
|---|---|
find_elements(query) |
Matching unique IDs; omits ordinary per-element errors |
find_elements_result(query) |
FindElementsResult: candidates plus aligned diagnostic outcomes |
filter_elements_by_query(elements, query) |
Matching supplied IDs; raises BatchOperationError if any element has an evaluation error |
filter_elements_by_query_result(elements, query) |
Aligned BatchResult, preserving per-element errors |
For diagnostic search, len(result.candidates) == len(result.outcomes.slots).
For supplied filtering, outcomes align with the original sequence, including
duplicates. Successful slots hold matching element IDs; FILTERED slots are
non-matches; ERROR slots retain failures and their causes. Use .successes
for the matching values.
Supplied filtering does not collect a new population, apply the floor-plan listing default, or change selection. Neither search method changes selection.
Invalid queries and query-wide failures raise from all methods. This includes metadata discovery, transport, whole-command errors, and unsuccessful database listings, even if another database succeeded. The core client already raises whole-command Tapir errors; diagnostic outcomes represent element-level failures.
Groups evaluate child outcomes before aggregation. A decisive Boolean sibling
does not hide another child's error. An unavailable property is an ordinary
false result; a failed property read is not. Error details retain predicate
paths and field identities. At leaf level, successful False becomes a filtered
element only when the final result is translated to matching IDs.
Serialization and compatibility¶
from multiconn_archicad.utilities.queries import validate_query_version
payload = query.model_dump_json(indent=2)
loaded = Query.model_validate_json(payload, context={"require_schema_version": True})
validate_query_version(loaded.schema_version)
assert loaded == query
The current QUERY_SCHEMA_VERSION is "1.0". Compatibility requires a valid
nonnegative major.minor string, the same major, and an equal or older minor.
Malformed versions raise ValueError; unsupported versions raise
UnsupportedQueryVersionError.
require_schema_version requires an explicit version when loading saved data;
it does not itself establish compatibility for an executable Query.
Execution checks compatibility before API reads, including for empty inputs.
Editable QueryRows checks compatibility when constructed or loaded as well.
Saved queries contain definitions, not metadata snapshots or results. GUIDs may be invalid in another project or after project changes. Validate them against fresh discovery before use. Executable queries and editable rows share the library schema version; the row document is a separate shape for unfinished input, described in query editing.