Skip to main content
Version: Next

Querying the model

Building a model is half the story. The other half is reading it back — to compute metrics, validate rules, or drive a transformation into some other format. ontouml-js gives you five families of query methods, from "give me everything of type X" down to "walk this class's supertypes."

Every example below runs against this small university model:

import { class Project
An OntoUML project: the top-level container of an ontology and the entry point of this library. A project holds every element of a model — classes, relations, generalizations, packages, properties, notes — as well as the diagrams and views that depict them, and provides typed access to these elements by id or by kind. New elements are created through the fluent builders exposed by the project (e.g., classBuilder , binaryRelationBuilder ), which register the created elements in the project. A project is also described by the metadata fields of the OntoUML/UFO Catalog Metadata Vocabulary, such as publisher, license, keywords, themes, and designed-for tasks.
@example```typescript const project = new Project(); const person = project.classBuilder().kind().name('Person').build(); const student = project.classBuilder().role().name('Student').build(); project .generalizationBuilder() .general(person) .specific(student) .build(); ```
Project
} from 'ontouml-js';
const const project: Projectproject = new new Project(): Project
An OntoUML project: the top-level container of an ontology and the entry point of this library. A project holds every element of a model — classes, relations, generalizations, packages, properties, notes — as well as the diagrams and views that depict them, and provides typed access to these elements by id or by kind. New elements are created through the fluent builders exposed by the project (e.g., classBuilder , binaryRelationBuilder ), which register the created elements in the project. A project is also described by the metadata fields of the OntoUML/UFO Catalog Metadata Vocabulary, such as publisher, license, keywords, themes, and designed-for tasks.
@example```typescript const project = new Project(); const person = project.classBuilder().kind().name('Person').build(); const student = project.classBuilder().role().name('Student').build(); project .generalizationBuilder() .general(person) .specific(student) .build(); ```
Project
();
const const model: Packagemodel = const project: Projectproject.Project.packageBuilder(): PackageBuilder
Creates a builder for a new Package in this project.
packageBuilder
().PackageBuilder.root(): PackageBuilder
Sets the package as the root package of its project, i.e., the package that contains the entire model.
@returnsthis builder, for method chaining.
root
().NamedElementBuilder<PackageBuilder>.name(value: string, language?: string): PackageBuilder
Adds a name to the element in the given language.
@paramvalue - the name text.@paramlanguage - language tag of `value`; defaults to LanguageString.defaultLanguage.@returnsthis builder, for method chaining.
name
('University').PackageBuilder.build(): Package
Builds an instance of Package with the parameters passed to the builder. When no methods are evoked, the created package has the following defaults: - `id: "randomly-generated-id",` - `created: new Date(),` - `contents: []`
@throwsan error if the builder has already been used.
build
();
const const person: Classperson = const model: Packagemodel.Package.classBuilder(): ClassBuilder
Creates a builder for a Class contained in this package.
classBuilder
().ClassBuilder.kind(): ClassBuilder
Sets the stereotype of the class to «kind», which decorates rigid classes that provide an identity principle to their instances, which are functional complexes (e.g., `Person`, `Car`). Also applies the following defaults: - `restrictedTo = [ "functional-complex" ]` - `order = 1`
@returnsthis builder, for method chaining.
kind
().NamedElementBuilder<ClassBuilder>.name(value: string, language?: string): ClassBuilder
Adds a name to the element in the given language.
@paramvalue - the name text.@paramlanguage - language tag of `value`; defaults to LanguageString.defaultLanguage.@returnsthis builder, for method chaining.
name
('Person').ClassBuilder.build(): Class
Builds an instance of Class with the parameters passed to the builder. **WARNING:** the ordering in which methods are evoked may affect the resulting object. When no methods are evoked, the created class has the following defaults: - `id: "randomly-generated-id",` - `created: new Date(),` - `isAbstract: false,` - `isDerived: false,` - `order: 1,` - `isPowertype: false,`
@throwsan error if the builder has already been used.
build
();
const const student: Classstudent = const model: Packagemodel.Package.classBuilder(): ClassBuilder
Creates a builder for a Class contained in this package.
classBuilder
().ClassBuilder.role(): ClassBuilder
Sets the stereotype of the class to «role», which decorates anti-rigid classes whose instances are contingently classified by virtue of a relational condition (e.g., `Student`, `Employee`).
@returnsthis builder, for method chaining.
role
().NamedElementBuilder<ClassBuilder>.name(value: string, language?: string): ClassBuilder
Adds a name to the element in the given language.
@paramvalue - the name text.@paramlanguage - language tag of `value`; defaults to LanguageString.defaultLanguage.@returnsthis builder, for method chaining.
name
('Student').ClassBuilder.build(): Class
Builds an instance of Class with the parameters passed to the builder. **WARNING:** the ordering in which methods are evoked may affect the resulting object. When no methods are evoked, the created class has the following defaults: - `id: "randomly-generated-id",` - `created: new Date(),` - `isAbstract: false,` - `isDerived: false,` - `order: 1,` - `isPowertype: false,`
@throwsan error if the builder has already been used.
build
();
const const university: Classuniversity = const model: Packagemodel.Package.classBuilder(): ClassBuilder
Creates a builder for a Class contained in this package.
classBuilder
().ClassBuilder.kind(): ClassBuilder
Sets the stereotype of the class to «kind», which decorates rigid classes that provide an identity principle to their instances, which are functional complexes (e.g., `Person`, `Car`). Also applies the following defaults: - `restrictedTo = [ "functional-complex" ]` - `order = 1`
@returnsthis builder, for method chaining.
kind
().NamedElementBuilder<ClassBuilder>.name(value: string, language?: string): ClassBuilder
Adds a name to the element in the given language.
@paramvalue - the name text.@paramlanguage - language tag of `value`; defaults to LanguageString.defaultLanguage.@returnsthis builder, for method chaining.
name
('University').ClassBuilder.build(): Class
Builds an instance of Class with the parameters passed to the builder. **WARNING:** the ordering in which methods are evoked may affect the resulting object. When no methods are evoked, the created class has the following defaults: - `id: "randomly-generated-id",` - `created: new Date(),` - `isAbstract: false,` - `isDerived: false,` - `order: 1,` - `isPowertype: false,`
@throwsan error if the builder has already been used.
build
();
const const enrollment: Classenrollment = const model: Packagemodel.Package.classBuilder(): ClassBuilder
Creates a builder for a Class contained in this package.
classBuilder
().ClassBuilder.relator(): ClassBuilder
Sets the stereotype of the class to «relator», which decorates rigid classes whose instances are relators, i.e., entities that mediate other entities and are the truthmakers of material relations (e.g., `Marriage`, `Enrollment`). Also applies the following defaults: - `restrictedTo = [ "relator" ]` - `order = 1`
@returnsthis builder, for method chaining.
relator
().NamedElementBuilder<ClassBuilder>.name(value: string, language?: string): ClassBuilder
Adds a name to the element in the given language.
@paramvalue - the name text.@paramlanguage - language tag of `value`; defaults to LanguageString.defaultLanguage.@returnsthis builder, for method chaining.
name
('Enrollment').ClassBuilder.build(): Class
Builds an instance of Class with the parameters passed to the builder. **WARNING:** the ordering in which methods are evoked may affect the resulting object. When no methods are evoked, the created class has the following defaults: - `id: "randomly-generated-id",` - `created: new Date(),` - `isAbstract: false,` - `isDerived: false,` - `order: 1,` - `isPowertype: false,`
@throwsan error if the builder has already been used.
build
();
// Student is a subtype of Person const person: Classperson.Classifier<Class, ClassStereotype>.addChild(child: Class): Generalization
Creates a Generalization in which this classifier is the general and the given classifier is the specific.
@paramchild - the classifier to be set as the specific.@returnsthe newly created generalization.
addChild
(const student: Classstudent);
// Enrollment mediates Student and University const const involvesStudent: BinaryRelationinvolvesStudent = const model: Packagemodel .Package.binaryRelationBuilder(): BinaryRelationBuilder
Creates a builder for a BinaryRelation contained in this package.
binaryRelationBuilder
()
.BinaryRelationBuilder.mediation(): BinaryRelationBuilder
Sets the stereotype of the relation to «mediation», which decorates relations between a relator and an endurant it mediates, such as a marriage and one of its spouses. Also applies the following defaults: - `sourceCardinality = "1..*"` - `targetCardinality = "1"` - `targetEnd.isReadOnly = true`
@returnsthis builder, for method chaining.
mediation
()
.NamedElementBuilder<BinaryRelationBuilder>.name(value: string, language?: string): BinaryRelationBuilder
Adds a name to the element in the given language.
@paramvalue - the name text.@paramlanguage - language tag of `value`; defaults to LanguageString.defaultLanguage.@returnsthis builder, for method chaining.
name
('involves')
.BinaryRelationBuilder.source(classifier: Classifier<any, any>): BinaryRelationBuilder
Sets the Classifier connected to the source end of the relation.
@returnsthis builder, for method chaining.
source
(const enrollment: Classenrollment)
.BinaryRelationBuilder.target(classifier: Classifier<any, any>): BinaryRelationBuilder
Sets the Classifier connected to the target end of the relation.
@returnsthis builder, for method chaining.
target
(const student: Classstudent)
.BinaryRelationBuilder.build(): BinaryRelation
Builds an instance of BinaryRelation with the parameters passed to the builder. Both the source and the target classifiers are required before `build()` is evoked. **WARNING:** the ordering in which methods are evoked may affect the resulting object. When no methods are evoked, the created relation has the following defaults: - `id: "randomly-generated-id",` - `created: new Date(),` - `isAbstract: false,` - `isDerived: false,`
@throwsan error if the builder has already been used.
build
();
const const enrolledAt: BinaryRelationenrolledAt = const model: Packagemodel .Package.binaryRelationBuilder(): BinaryRelationBuilder
Creates a builder for a BinaryRelation contained in this package.
binaryRelationBuilder
()
.BinaryRelationBuilder.mediation(): BinaryRelationBuilder
Sets the stereotype of the relation to «mediation», which decorates relations between a relator and an endurant it mediates, such as a marriage and one of its spouses. Also applies the following defaults: - `sourceCardinality = "1..*"` - `targetCardinality = "1"` - `targetEnd.isReadOnly = true`
@returnsthis builder, for method chaining.
mediation
()
.NamedElementBuilder<BinaryRelationBuilder>.name(value: string, language?: string): BinaryRelationBuilder
Adds a name to the element in the given language.
@paramvalue - the name text.@paramlanguage - language tag of `value`; defaults to LanguageString.defaultLanguage.@returnsthis builder, for method chaining.
name
('at')
.BinaryRelationBuilder.source(classifier: Classifier<any, any>): BinaryRelationBuilder
Sets the Classifier connected to the source end of the relation.
@returnsthis builder, for method chaining.
source
(const enrollment: Classenrollment)
.BinaryRelationBuilder.target(classifier: Classifier<any, any>): BinaryRelationBuilder
Sets the Classifier connected to the target end of the relation.
@returnsthis builder, for method chaining.
target
(const university: Classuniversity)
.BinaryRelationBuilder.build(): BinaryRelation
Builds an instance of BinaryRelation with the parameters passed to the builder. Both the source and the target classifiers are required before `build()` is evoked. **WARNING:** the ordering in which methods are evoked may affect the resulting object. When no methods are evoked, the created relation has the following defaults: - `id: "randomly-generated-id",` - `created: new Date(),` - `isAbstract: false,` - `isDerived: false,`
@throwsan error if the builder has already been used.
build
();

1. Collection getters​

A Project (and each Package) exposes typed getters that return every element of a given kind, anywhere in its containment tree. This is the fastest way to sweep the whole model.

GetterReturns
project.classesClass[]
project.relationsRelation[] (binary + n-ary)
project.binaryRelationsBinaryRelation[]
project.naryRelationsNaryRelation[]
project.generalizationsGeneralization[]
project.generalizationSetsGeneralizationSet[]
project.packagesPackage[]
project.attributesProperty[]
project.relationEndsProperty[]
project.literalsLiteral[]

The same getters exist on a Package, scoped to that package's contents:

const const everyClass: Class[]everyClass = const project: Projectproject.Project.classes: Class[]
The classes contained in this project.
classes
; // every class in the project
const const inModel: Class[]inModel = const model: Packagemodel.Package.classes: Class[]
The classes directly contained in this package.
classes
; // only classes in this package

2. Look up a single element by id​

When you already know an element's id, fetch it directly. There's a typed lookup per element kind, plus element(id) for "any element."

const const byClass: ClassbyClass = const project: Projectproject.Project.class(id: string): Class | undefined
Retrieves the class with the given id, if any.
class
(const person: Classperson.OntoumlElement.id: string
The unique identifier of this element; a random id by default.
id
); // Class | undefined
const const byAny: OntoumlElementbyAny = const project: Projectproject.Project.element(id: string): OntoumlElement | undefined
Retrieves the model element with the given id, if any, searching across classes, relations, generalizations, generalization sets, packages, properties, literals, notes, and anchors.
element
(const person: Classperson.OntoumlElement.id: string
The unique identifier of this element; a random id by default.
id
); // OntoumlElement | undefined

Also available: binaryRelation(id), naryRelation(id), generalization(id), generalizationSet(id), package(id), property(id), and more.

3. Query by stereotype and ontological category​

Projects and packages answer queries that retrieve classes and relations by their stereotype — and, more powerfully, by ontological category (all sortals, all rigid types, …), which would otherwise take a hand-written filter. On a project they range over the whole model; on a package, over that package and its subpackages.

// By exact stereotype
const const kinds: Class[]kinds = const project: Projectproject.Queries.getKinds(): Class[]
Retrieves all classes in scope stereotyped as «kind».
getKinds
();
const const relators: Class[]relators = const project: Projectproject.Queries.getRelators(): Class[]
Retrieves all classes in scope stereotyped as «relator».
getRelators
();
const const mediations: BinaryRelation[]mediations = const project: Projectproject.Queries.getMediations(): BinaryRelation[]
Retrieves all binary relations in scope stereotyped as «mediation».
getMediations
();
// By ontological category — no manual filtering needed const const sortals: Class[]sortals = const project: Projectproject.Queries.getSortals(): Class[]
Retrieves all classes in scope decorated with a sortal stereotype, i.e., a stereotype that carries or supplies an identity principle to the instances of the class.
@seeClass.isSortal
getSortals
();
const const rigid: Class[]rigid = const project: Projectproject.Queries.getRigidTypes(): Class[]
Retrieves all classes in scope decorated with a rigid stereotype, i.e., a stereotype of classes whose instances cannot cease to be instances of them (e.g., «kind», «subkind», «category»).
@seeClass.isRigid
getRigidTypes
();
const const antiRigid: Class[]antiRigid = const project: Projectproject.Queries.getAntiRigidTypes(): Class[]
Retrieves all classes in scope decorated with an anti-rigid stereotype, i.e., a stereotype of classes whose instances can cease to be instances of them (e.g., «role», «phase»).
@seeClass.isAntiRigid
getAntiRigidTypes
();
// By an explicit list of stereotypes const const roles: Class[]roles = const project: Projectproject.Queries.getClassesByStereotype(stereotypes: ClassStereotype[]): Class[]
Retrieves all classes in scope whose stereotype is included in `stereotypes`.
@paramstereotypes - the class stereotypes to filter by.
getClassesByStereotype
([enum ClassStereotype
The OntoUML stereotypes applicable to a Class . Each stereotype identifies the micro-theory of UFO that governs the class, constraining, among other things, the ontological natures of its instances (see Nature ), its rigidity, and the specializations in which it can participate.
ClassStereotype
.function (enum member) ClassStereotype.ROLE = "role"
An anti-rigid sortal whose instantiation depends on a relational (extrinsic) condition, e.g., `Student` — a role played by persons while enrolled in a school.
ROLE
]);
// The same queries work on a package, scoped to its subtree const const localKinds: Class[]localKinds = const model: Packagemodel.Queries.getKinds(): Class[]
Retrieves all classes in scope stereotyped as «kind».
getKinds
();

A sampling of what's on offer:

CategoryMethods
Ultimate sortalsgetKinds, getCollectives, getQuantities, getRelators, getModes, getQualities
Base sortalsgetSubkinds, getRoles, getPhases
Non-sortalsgetCategories, getMixins, getRoleMixins, getPhaseMixins
Meta-categoriesgetSortals, getNonSortals, getRigidTypes, getAntiRigidTypes, getSemiRigidTypes
RelationsgetMediations, getMaterialRelations, getCharacterizations, getComponentOfRelations, …
ExplicitgetClassesByStereotype, getBinaryRelationsByStereotype, getAttributesByStereotype

4. Predicates: build your own filters​

Each Class answers a family of boolean predicates — the same ones the stereotype queries use internally. Combine them with Array.filter for queries the named methods don't cover directly.

// Anti-rigid sortals: roles and phases
const const antiRigidSortals: Class[]antiRigidSortals = const project: Projectproject.Project.classes: Class[]
The classes contained in this project.
classes
.Array<Class>.filter(predicate: (value: Class, index: number, array: Class[]) => unknown, thisArg?: any): Class[] (+1 overload)
Returns the elements of an array that meet the condition specified in a callback function.
@parampredicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.@paramthisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
filter
(
c: Classc => c: Classc.Class.isSortal(): boolean
Checks whether this class is a sortal, i.e., whether all of its instances follow the same identity principle.
@seeSORTAL_STEREOTYPES
isSortal
() && c: Classc.Class.isAntiRigid(): boolean
Checks whether this class is anti-rigid, i.e., whether every instance can cease to be classified by it without ceasing to exist.
@seeANTI_RIGID_STEREOTYPES
isAntiRigid
()
);

Predicates include isKind, isSubkind, isRole, isPhase, isRelator, isSortal, isNonSortal, isRigid, isAntiRigid, isSemiRigid, isType, and more.

5. Navigation: taxonomy and relations​

The families above start from the whole project. Just as often you start from one element and walk its neighbourhood — its supertypes, subtypes, or the relations attached to it. These methods live on any Classifier (so, on every Class and Relation).

MethodReturns
getParents() / getChildren()direct super/subtypes
getAncestors() / getDescendants()transitive super/subtypes
getRelations()relations attached to this classifier
getIncomingRelations() / getOutgoingRelations()binary relations by direction
getOwnOppositeRelationEnds()the far ends of those relations

And a BinaryRelation exposes its endpoints directly: source, target, sourceEnd, and targetEnd.

// Walk up the taxonomy: Student -> Person
const const supertypes: string[]supertypes = const student: Classstudent.Classifier<Class, ClassStereotype>.getAncestors(knownAncestors?: Class[]): Class[]
Retrieves the direct and indirect supertypes of this classifier.
@throwsan error if the classifier is part of a circular generalization chain (e.g., `A` specializes `B`, `B` specializes `C`, and `C` specializes `A`), in which case the classifier would be an ancestor of itself.
getAncestors
().Array<Class>.map<string>(callbackfn: (value: Class, index: number, array: Class[]) => string, thisArg?: any): string[]
Calls a defined callback function on each element of an array, and returns an array that contains the results.
@paramcallbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.@paramthisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
map
(c: Classc => c: Classc.NamedElement.getNameOrId(language?: string): string
Returns the name of this element in the given language, falling back to its id when no suitable name is available.
@paramlanguage - language tag of the desired name (e.g., `"en"`); when omitted, the name is selected according to LanguageString.languagePreference.
getNameOrId
());
// What does the Enrollment relator connect to? const const mediated: string[]mediated = const enrollment: Classenrollment .Classifier<Class, ClassStereotype>.getOutgoingRelations(): BinaryRelation[]
Retrieves the binary relations whose source is this classifier.
getOutgoingRelations
()
.Array<BinaryRelation>.map<string>(callbackfn: (value: BinaryRelation, index: number, array: BinaryRelation[]) => string, thisArg?: any): string[]
Calls a defined callback function on each element of an array, and returns an array that contains the results.
@paramcallbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.@paramthisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
map
(rel: BinaryRelationrel => rel: BinaryRelationrel.BinaryRelation.target: Classifier<any, any>
The classifier connected at the target end, if typed.
target
?.NamedElement.getNameOrId(language?: string): string
Returns the name of this element in the given language, falling back to its id when no suitable name is available.
@paramlanguage - language tag of the desired name (e.g., `"en"`); when omitted, the name is selected according to LanguageString.languagePreference.
getNameOrId
());

Putting it together: a lint rule​

Query families compose. Here's a real check — every «role» should specialize at least one «kind» — written by combining stereotype queries, navigation, and predicates:

const const orphanRoles: string[]orphanRoles = const project: Projectproject
  .Queries.getRoles(): Class[]
Retrieves all classes in scope stereotyped as «role».
getRoles
()
.Array<Class>.filter(predicate: (value: Class, index: number, array: Class[]) => unknown, thisArg?: any): Class[] (+1 overload)
Returns the elements of an array that meet the condition specified in a callback function.
@parampredicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.@paramthisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
filter
(role: Classrole => !role: Classrole.Classifier<Class, ClassStereotype>.getAncestors(knownAncestors?: Class[]): Class[]
Retrieves the direct and indirect supertypes of this classifier.
@throwsan error if the classifier is part of a circular generalization chain (e.g., `A` specializes `B`, `B` specializes `C`, and `C` specializes `A`), in which case the classifier would be an ancestor of itself.
getAncestors
().Array<Class>.some(predicate: (value: Class, index: number, array: Class[]) => unknown, thisArg?: any): boolean
Determines whether the specified callback function returns true for any element of an array.
@parampredicate A function that accepts up to three arguments. The some method calls the predicate function for each element in the array until the predicate returns a value which is coercible to the Boolean value true, or until the end of the array.@paramthisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
some
(a: Classa => a: Classa.Class.isKind(): boolean
Checks whether this class is stereotyped as «kind».
isKind
()))
.Array<Class>.map<string>(callbackfn: (value: Class, index: number, array: Class[]) => string, thisArg?: any): string[]
Calls a defined callback function on each element of an array, and returns an array that contains the results.
@paramcallbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.@paramthisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
map
(role: Classrole => role: Classrole.NamedElement.getNameOrId(language?: string): string
Returns the name of this element in the given language, falling back to its id when no suitable name is available.
@paramlanguage - language tag of the desired name (e.g., `"en"`); when omitted, the name is selected according to LanguageString.languagePreference.
getNameOrId
());

This is the shape of most transformations and validators you'll write: pick a starting set with a stereotype query or a getter, filter with predicates, and map/navigate to produce your result.

Now you try it​

Write a query that lists, for each relator, the names of the classes it mediates. Open the console to see your result.

Loading playground…
Show the solution
Loading playground…

Recap​

  • Collection getters (project.classes, …) sweep the whole model by kind.
  • element(id) and its typed siblings fetch one known element.
  • Stereotype queries (getKinds, getRigidTypes, …) retrieve by stereotype and by ontological category, on a project or scoped to a package.
  • Predicates (isKind, isSortal, …) power your own filters.
  • Navigation (getAncestors, getOutgoingRelations, relation.target, …) walks from one element to its neighbours.

Next: generalizations & generalization sets go deeper on the taxonomy these navigation methods traverse.