Query
Query
Query builds a request for published entries and sends it. Use this class to
- match entries by field value, reference, tag, search text or taxonomy term
- choose the locale, fields and references that the response carries
- sort the entries and read them one page at a time
- send the request with find(_:)
Query adopts BaseQuery and EntryQueryable, so it carries their methods as well as its own. QueryOn is a subclass that queries with the field keys of your own model type.
Instance State
Query has no public initializer. Two factories create one, and the factory sets which model type find(_:) accepts:
- Call stack.contentType(uid: "CONTENT_TYPE_UID").entry().query() to read the entries of one content type. Annotate find(_:) with EntryModel or your own EntryDecodable type. entry(uid:).query() also adds a condition that matches that entry UID.
- Call stack.taxonomy().query() to read entries of any content type by taxonomy term. Annotate find(_:) with TaxonomyModel.
The SDK stops the app in two cases on the wrong branch:
- stack.contentType().entry() stops the app with a fatal error, because the content type has no UID to build the entries path. Pass a UID to contentType(uid:).
- find(_:) with EntryModel on a query from stack.taxonomy().query() stops the app, because that query has no content type UID. Use TaxonomyModel for a taxonomy query.
Warning query() builds a new query from the content type only. A setting that you chain on the Entry before query(), such as locale(_:) or addValue(_:forHTTPHeaderField:), never reaches the query. Call query() first, then chain the setters.
Class-Level Notes
Where each method writes.
- The condition methods write the queryParameter dictionary: the where methods, operator(_:), and addQuery(with:value:). find(_:) sends it as JSON in the query URL parameter.
- Every other setter writes the parameters dictionary, and find(_:) sends each entry as its own URL parameter. The SDK always adds the environment of the stack.
- No method makes a request except find(_:).
One condition per field.
- A second condition on the same field replaces the first, because the conditions live in a dictionary keyed by field. For a range or any other pair of conditions on one field, pass one subquery per condition to operator(_:) with .and.
Settings stay on the query.
- find(_:) does not clear the query, so a second find(_:) sends the same request again.
Return values.
- Every setter returns the query, so calls chain. The where methods and operator(_:) lack the @discardableResult attribute. A call whose result goes unused compiles with a warning, so chain it or assign the result.
Cache policy.
- A query starts with the cachePolicy of its content type or taxonomy, which is .networkOnly unless you change it. It does not read Stack.cachePolicy. Set cachePolicy on the query to read from the cache.
Capability Matrix
| Capability | Supported | Notes / Alternative |
|---|---|---|
| Two where conditions on the same field | No | Pass one subquery per condition to operator(_:) with .and. |
| Reference search with where(referenceAtKeyPath:_:) | No | Pass $in_query or $nin_query to addQuery(with:value:). |
| Set the levels of a taxonomy operator such as .below | No | Pass the operator and levels to addQuery(with:value:). |
| Return every matching entry in one call | No | Read one page at a time with skip(theFirst:) and limit(to:). |
| Inherit Stack.cachePolicy | No | Set cachePolicy on the query. |
Class-Level Properties
| Property | Type | Access | Default | Description |
|---|---|---|---|---|
| stack | Stack | Read and write | The stack of the content type or taxonomy | Stack that sends the request. |
| parameters | [String: Any] | Read and write | ["content_type": "<content type UID>"] on a content type query, [:] on a taxonomy query | URL parameters the request carries. |
| queryParameter | [String: Any] | Read and write | [:] | Conditions that find(_:) sends as JSON in query. |
| headers | [String: String] | Read and write | [:] | HTTP headers the request carries. |
| cachePolicy | CachePolicy | Read and write | The cachePolicy of the content type or taxonomy (.networkOnly) | Whether find(_:) reads the network or the cache. See Stack. |
Query.Operation
Query.Operation is the operator and value that a where method applies to one field. Pass it to where(valueAtKey:_:), where(queryableCodingKey:_:) or where(valueAtKeyPath:_:). AssetQuery and ContentTypeQuery accept the same values. The following table lists its cases.
| Case | Raw value | Meaning |
|---|---|---|
| equals(QueryableRange) | None | Matches entries whose field equals the value. The SDK writes {"<field>": <value>}. See Equals Operator. |
| notEquals(QueryableRange) | $ne | Matches entries whose field does not equal the value. See Not-equals Operator. |
| includes([QueryableRange]) | $in | Matches entries whose field equals any listed value. See Array Equals Operator. |
| excludes([QueryableRange]) | $nin | Matches entries whose field equals none of the listed values. See Array Not-equals Operator. |
| isLessThan(QueryableRange) | $lt | Matches entries whose field is less than the value. See Less Than. |
| isLessThanOrEqual(QueryableRange) | $lte | Matches entries whose field is at most the value. See Less Than or Equal To. |
| isGreaterThan(QueryableRange) | $gt | Matches entries whose field is greater than the value. See Greater Than. |
| isGreaterThanOrEqual(QueryableRange) | $gte | Matches entries whose field is at least the value. See Greater Than or Equal To. |
| exists(Bool) | $exists | Matches entries that have (true) or lack (false) a value in the field. See Exists. |
| matches(String) | $regex | Matches entries whose field matches a regular expression. See Search by Regex. |
| eqBelow(String) | $eq_below | Matches a taxonomy term and its descendant terms. See Equal and Below Operator. |
| below(String) | $below | Matches the descendant terms of a taxonomy term, without the term itself. See Below Operator. |
| eqAbove(String) | $eq_above | Matches a taxonomy term and its ancestor terms. See Equal and Above Operator. |
| above(String) | $above | Matches the ancestor terms of a taxonomy term, without the term itself. See Above Operator. |
The following list gives the value format that the SDK writes for each case:
- equals, notEquals and the four comparison cases send an Int, Double or Bool as a JSON number or boolean. Any other value goes out as its stringValue, so a Date becomes an ISO 8601 string such as "2024-01-01T00:00:00Z".
- includes and excludes send the array elements unchanged.
- The four taxonomy cases send no levels key, so the API applies its default depth of 10 levels. To set levels, pass the whole condition to addQuery(with:value:).
Known issue includes or excludes with a Date element stops the app with NSInvalidArgumentException when find(_:) converts the conditions to JSON. Pass the date as an ISO 8601 string instead.
Query.Operator
Query.Operator joins the conditions of several subqueries. Pass it to operator(_:). The following table lists its cases.
| Case | Raw value | Meaning |
|---|---|---|
| and([Query]) | $and | Matches entries that satisfy every subquery. See AND Operator. |
| or([Query]) | $or | Matches entries that satisfy at least one subquery. See OR Operator. |
- The SDK copies only the conditions (queryParameter) of each subquery. Settings such as limit(to:) or locale(_:) on a subquery have no effect.
Query.Reference
Query.Reference wraps a subquery that a reference field must match. The where(referenceAtKeyPath:_:) method accepts it, but sends the condition in a form that does not run a reference search, as that page describes. For a reference search, pass $in_query or $nin_query to addQuery(with:value:) instead. The following table lists the cases of Query.Reference.
| Case | Raw value | Meaning |
|---|---|---|
| include(Query) | $in | Intended to match entries whose referenced entries satisfy the subquery. See Reference Search Equals. |
| notInclude(Query) | $nin | Intended to match entries whose referenced entries do not satisfy the subquery. See Reference Search Not-equals. |
Query.Include
Query.Include is an option set that specifies extra data for the response. Pass one value or an array of values to include(params:), for example [.count, .fallback]. The following table lists its options.
| Case | Raw value | Meaning |
|---|---|---|
| count | 1 | Sends include_count=true. The response carries the total number of matching entries. See Count. |
| unpublished | 2 | Sends nothing. include(params:) has no branch for this option. |
| contentType | 4 | Sends include_content_type=true and include_global_field_schema=false. |
| globalField | 8 | Sends include_content_type=true and include_global_field_schema=true. |
| refContentTypeUID | 16 | Sends include_reference_content_type_uid=true. |
| fallback | 32 | Sends include_fallback=true. The response carries fallback locale content for entries not published in the requested locale. |
| embeddedItems | 64 | Sends include_embedded_items[]=BASE. |
| metadata | 128 | Sends include_metadata=true. |
| all | 255 | Every option above. include_global_field_schema is true, because globalField overrides contentType. |
QueryableRange
QueryableRange is the protocol for a value that a Query.Operation case accepts. Its one requirement is stringValue: String. The SDK makes the following types conform:
| Type | stringValue |
|---|---|
| Int | The number as text, for example "600". |
| Double | The number as text, for example "5.5". |
| Bool | "true" or "false". |
| String | The string unchanged. |
| Date | The ISO 8601 string, for example "2024-01-01T00:00:00Z". |
- A type of your own can conform by implementing stringValue. equals, notEquals and the comparison cases send its stringValue. Inside includes or excludes, a value that is not a JSON type stops the app, as the Known issue under Query.Operation above describes.
Method Index
The tables below group the methods by task. A row that links into BaseQuery or EntryQueryable is an inherited method, documented once on that page.
Filter by field value. Available on any Query, before find(_:).
| Method Name | Returns | Description |
|---|---|---|
| where(valueAtKey:_:) | The same query, for chaining. | Matches entries by a field UID and an operation. |
| where(queryableCodingKey:_:) | The same query, for chaining. | Matches entries by a system field key and an operation. |
| where(valueAtKeyPath:_:) | The same query, for chaining. | Matches by a field path. Inherited from BaseQuery. |
| operator(_:) | The same query, for chaining. | Joins the conditions of subqueries with $and or $or. |
| addQuery(with:value:) | The same query, for chaining. | Adds one raw condition. Inherited from BaseQuery. |
| addQuery(dictionary:) | The same query, for chaining. | Adds several raw conditions. Inherited from BaseQuery. |
Filter by reference, tag or search text. Available on a query from entry().query(), before find(_:).
| Method Name | Returns | Description |
|---|---|---|
| where(referenceAtKeyPath:_:) | The same query, for chaining. | Builds a condition on the entries a reference field points to. |
| tags(for:) | The same query, for chaining. | Sends a tag string in the tags parameter. |
| search(for:) | The same query, for chaining. | Sends a search string in the typeahead parameter. |
Choose the locale, fields and references. Available on any Query, before find(_:).
| Method Name | Returns | Description |
|---|---|---|
| locale(_:) | The same entry or query, for chaining. | Sets the locale to read. Inherited from EntryQueryable. |
| only(fields:) | The same entry or query, for chaining. | Keeps only the listed fields. Inherited from EntryQueryable. |
| except(fields:) | The same entry or query, for chaining. | Leaves out the listed fields. Inherited from EntryQueryable. |
| include(params:) | The same entry or query, for chaining. | Adds the Query.Include data. Inherited from EntryQueryable. |
| includeReference(with:) | The same entry or query, for chaining. | Returns referenced entries in full. Inherited from EntryQueryable. |
| includeReferenceField(with:only:) | The same entry or query, for chaining. | Returns listed fields of referenced entries. Inherited from EntryQueryable. |
| includeReferenceField(with:except:) | The same entry or query, for chaining. | Leaves fields out of referenced entries. Inherited from EntryQueryable. |
Read entry variants. Available on a query from entry().query(), before find(_:).
| Method Name | Returns | Description |
|---|---|---|
| variants(uid:) | The same entry or query, for chaining. | Reads one variant. Inherited from EntryQueryable. |
| variants(uids:) | The same entry or query, for chaining. | Reads several variants. Inherited from EntryQueryable. |
| variants(uid:branch:) | The same entry or query, for chaining. | Reads one variant on a branch. Inherited from EntryQueryable. |
| variants(uids:branch:) | The same entry or query, for chaining. | Reads several variants on a branch. Inherited from EntryQueryable. |
Sort and paginate. Available on any Query, before find(_:).
| Method Name | Returns | Description |
|---|---|---|
| orderByAscending(propertyName:) | The same query, for chaining. | Sorts by a system field in ascending order. |
| orderByDecending(propertyName:) | The same query, for chaining. | Sorts by a system field in descending order. |
| orderByAscending(keyPath:) | The same query, for chaining. | Sorts by any field path, ascending. Inherited from BaseQuery. |
| orderByDecending(keyPath:) | The same query, for chaining. | Sorts by any field path, descending. Inherited from BaseQuery. |
| limit(to:) | The same query, for chaining. | Sets the page size. Inherited from BaseQuery. |
| skip(theFirst:) | The same query, for chaining. | Skips entries before the page starts. Inherited from BaseQuery. |
Send a parameter or header the SDK has no method for. Available on any Query, before find(_:).
| Method Name | Returns | Description |
|---|---|---|
| addURIParam(with:value:) | The same query, for chaining. | Adds one URL parameter. Inherited from BaseQuery. |
| addURIParam(dictionary:) | The same query, for chaining. | Adds several URL parameters. Inherited from BaseQuery. |
| addValue(_:forHTTPHeaderField:) | The same query, for chaining. | Adds one HTTP header. Inherited from BaseQuery. |
Send the request. Available on any Query, as the last call in the chain.
| Method Name | Returns | Description |
|---|---|---|
| find(_:) | Nothing. The completion handler receives the result. | Sends the query and returns one page of entries. Inherited from BaseQuery. |
Class-Level Snippet
The snippet below lists the ten cheapest French entries under a price, with fallback content, the total count and a sort.
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
.where(valueAtKey: "price_in_usd", .isLessThan(600))
.locale("fr-fr")
.include(params: [.count, .fallback])
.orderByAscending(keyPath: "price_in_usd")
.limit(to: 10)
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
switch result {
case .success(let contentstackResponse):
print("Total matches: \(contentstackResponse.count ?? 0)")
for entry in contentstackResponse.items {
print(entry.title)
}
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}Methods
Each method of the Query class has its own section below, with its parameters, validation rules, behavior, and examples.
operator(_:)
operator(_:) joins the conditions of several subqueries with $and or $or and adds the result to the query.
| Name | Type | Description |
|---|---|---|
| operator (required) | Query.Operator | .and or .or with the subqueries to join. |
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. An empty subquery array sends an empty $and or $or list.
- Errors that do occur come from the find(_:) call that follows, not from operator(_:).
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. operator(_:) writes {"$and": [...]} or {"$or": [...]} into the conditions of the query, with one object per subquery. It makes no request. See AND Operator and OR Operator.
- The SDK copies only the conditions of each subquery. The content type of a subquery and settings such as limit(to:) or locale(_:) have no effect, so build each subquery with entry().query() and the where methods.
- A second .and call replaces the first $and list, and a second .or call replaces the first $or list. One query can hold one $and list and one $or list.
- The JSON object holds $and and $or next to any conditions from the where methods.
- Use .and for two conditions on the same field, such as a price range, because a second where call on one field replaces the first.
- On a query from stack.taxonomy().query(), the subqueries hold taxonomies.<taxonomy_uid> conditions. See OR Operator for taxonomy.
Example
Basic usage: match entries in a price range
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
let contentType = stack.contentType(uid: "CONTENT_TYPE_UID")
let atLeast = contentType.entry().query().where(valueAtKey: "price_in_usd", .isGreaterThanOrEqual(100))
let below = contentType.entry().query().where(valueAtKey: "price_in_usd", .isLessThan(600))
contentType.entry().query()
.operator(.and([atLeast, below]))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
switch result {
case .success(let contentstackResponse):
for entry in contentstackResponse.items {
print(entry.title)
}
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}Match entries that satisfy either condition
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
let contentType = stack.contentType(uid: "CONTENT_TYPE_UID")
let gold = contentType.entry().query().where(valueAtKey: "color", .equals("Gold"))
let black = contentType.entry().query().where(valueAtKey: "color", .equals("Black"))
contentType.entry().query()
.operator(.or([gold, black]))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
guard case .success(let contentstackResponse) = result else { return }
for entry in contentstackResponse.items {
print(entry.title)
}
}Match entries tagged with either of two taxonomy terms
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
let black = stack.taxonomy().query().where(valueAtKey: "taxonomies.color", .equals("black"))
let small = stack.taxonomy().query().where(valueAtKey: "taxonomies.size", .equals("small"))
stack.taxonomy().query()
.operator(.or([black, small]))
.find { (result: Result<ContentstackResponse<TaxonomyModel>, Error>, response: ResponseType) in
guard case .success(let contentstackResponse) = result else { return }
for entry in contentstackResponse.items {
print(entry.title)
}
}orderByAscending(propertyName:)
orderByAscending(propertyName:) sorts the entries in ascending order of the system field that an EntryModel.FieldKeys case names.
| Name | Type | Description |
|---|---|---|
| propertyName (required) | EntryModel.FieldKeys | System field to sort by, for example .createdAt. |
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. The compiler accepts only EntryModel.FieldKeys cases.
- Errors that do occur come from the find(_:) call that follows, not from orderByAscending(propertyName:).
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. orderByAscending(propertyName:) converts the key to its field UID, for example .createdAt to created_at, and writes it to the asc parameter through the orderByAscending(keyPath:) method. It makes no request. See Order by asc.
- EntryModel.FieldKeys holds the system fields only: title, uid, locale, createdAt, updatedAt, createdBy and updatedBy. To sort by a field of your own content type, use the orderByAscending(keyPath:) method.
- A second call replaces the field from the first.
- The orderByDecending(propertyName:) method writes a separate parameter, so calling both sends both.
- The method carries the @discardableResult attribute, so a call on a separate line compiles without a warning.
Example
Basic usage: sort entries by creation date
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
.orderByAscending(propertyName: .createdAt)
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
switch result {
case .success(let contentstackResponse):
for entry in contentstackResponse.items {
print(entry.title)
}
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}Sort a page of twenty entries by title
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
let query = stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
query.orderByAscending(propertyName: .title)
query.limit(to: 20)
query.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
guard case .success(let contentstackResponse) = result else { return }
for entry in contentstackResponse.items {
print(entry.title)
}
}orderByDecending(propertyName:)
orderByDecending(propertyName:) sorts the entries in descending order of the system field that an EntryModel.FieldKeys case names.
| Name | Type | Description |
|---|---|---|
| propertyName (required) | EntryModel.FieldKeys | System field to sort by, for example .createdAt. |
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. The compiler accepts only EntryModel.FieldKeys cases.
- Errors that do occur come from the find(_:) call that follows, not from orderByDecending(propertyName:).
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. orderByDecending(propertyName:) converts the key to its field UID, for example .createdAt to created_at, and writes it to the desc parameter through the orderByDecending(keyPath:) method. It makes no request. See Order by desc.
- EntryModel.FieldKeys holds the system fields only: title, uid, locale, createdAt, updatedAt, createdBy and updatedBy. To sort by a field of your own content type, use the orderByDecending(keyPath:) method.
- A second call replaces the field from the first.
- The orderByAscending(propertyName:) method writes a separate parameter, so calling both sends both.
- The method carries the @discardableResult attribute, so a call on a separate line compiles without a warning.
Example
Basic usage: sort entries by creation date
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
.orderByDecending(propertyName: .createdAt)
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
switch result {
case .success(let contentstackResponse):
for entry in contentstackResponse.items {
print(entry.title)
}
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}Sort a page of twenty entries by title
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
let query = stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
query.orderByDecending(propertyName: .title)
query.limit(to: 20)
query.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
guard case .success(let contentstackResponse) = result else { return }
for entry in contentstackResponse.items {
print(entry.title)
}
}search(for:)
search(for:) sends a search string in the typeahead parameter of the request.
| Name | Type | Description |
|---|---|---|
| for (required) | String | Text to send in the typeahead parameter. |
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. An empty string sends an empty typeahead parameter.
- Errors that do occur come from the find(_:) call that follows, not from search(for:).
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. search(for:) writes the string to the typeahead URL parameter and makes no request. The find(_:) method sends it.
- A second call replaces the first value.
- The SDK percent-encodes the value but leaves & as is. A & in the string ends the parameter early, so the API receives only the text before it.
- The method carries the @discardableResult attribute, so a call on a separate line compiles without a warning.
Example
Basic usage: send a search string
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
.search(for: "phone")
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
switch result {
case .success(let contentstackResponse):
for entry in contentstackResponse.items {
print(entry.title)
}
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}tags(for:)
tags(for:) sends a tag string in the tags parameter of the request, to match entries by tag.
| Name | Type | Description |
|---|---|---|
| for (required) | String | Tag text to send in the tags parameter. |
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. An empty string sends an empty tags parameter.
- Errors that do occur come from the find(_:) call that follows, not from tags(for:).
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. tags(for:) writes the string to the tags URL parameter and makes no request. The find(_:) method sends it.
- A second call replaces the first value.
- The SDK percent-encodes the value but leaves & as is. A & in the string ends the parameter early, so the API receives only the text before it.
- The method carries the @discardableResult attribute, so a call on a separate line compiles without a warning.
Example
Basic usage: match entries by a tag
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
.tags(for: "electronics")
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
switch result {
case .success(let contentstackResponse):
for entry in contentstackResponse.items {
print(entry.title)
}
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}where(queryableCodingKey:_:)
where(queryableCodingKey:_:) adds a condition that matches entries by the value of the system field that an EntryModel.FieldKeys case names.
| Name | Type | Description |
|---|---|---|
| queryableCodingKey (required) | EntryModel.FieldKeys | System field to match, for example .title. |
| operation (required) | Query.Operation | Operator and value the field must match. |
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. The compiler accepts only EntryModel.FieldKeys cases.
- Errors that do occur come from the find(_:) call that follows, not from where(queryableCodingKey:_:).
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. where(queryableCodingKey:_:) converts the key to its field UID, for example .createdAt to created_at, and passes it to the where(valueAtKeyPath:_:) method. It makes no request.
- EntryModel.FieldKeys holds the system fields only: title, uid, locale, createdAt, updatedAt, createdBy and updatedBy. The Entry page describes EntryModel.
- To filter on a field of your own content type, use the where(valueAtKey:_:) method, or a QueryOn query with the field keys of your model.
- A second condition on the same field replaces the first.
Example
Basic usage: match entries updated after a date
import ContentstackSwift
import Foundation
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
let cutoff = Date(timeIntervalSince1970: 1_704_067_200)
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
.where(queryableCodingKey: .updatedAt, .isGreaterThan(cutoff))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
switch result {
case .success(let contentstackResponse):
for entry in contentstackResponse.items {
print(entry.title, entry.updatedAt ?? cutoff)
}
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}Match entries whose title starts with a prefix
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
.where(queryableCodingKey: .title, .matches("^Redmi"))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
guard case .success(let contentstackResponse) = result else { return }
for entry in contentstackResponse.items {
print(entry.title)
}
}where(referenceAtKeyPath:_:)
where(referenceAtKeyPath:_:) adds a condition on the entries that a reference field points to, built from the conditions of a subquery.
| Name | Type | Description |
|---|---|---|
| referenceAtKeyPath (required) | String | UID or dot path of the reference field. |
| operation (required) | Query.Reference | Subquery wrapped in .include or .notInclude. |
Returns: Query. The same query, for chaining.
Known issue where(referenceAtKeyPath:_:) sends the condition as a JSON string with $in or $nin, not as the $in_query or $nin_query object that the reference search request expects, so the query does not run a reference search. Pass the $in_query or $nin_query object to the addQuery(with:value:) method instead.
Validation
- There is no client-side validation.
- Errors that do occur come from the find(_:) call that follows, not from where(referenceAtKeyPath:_:).
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. where(referenceAtKeyPath:_:) makes no request.
- where(referenceAtKeyPath:_:) converts the conditions of the subquery to JSON text and wraps it as {"$in": "<text>"} (.include) or {"$nin": "<text>"} (.notInclude). It then converts that wrapper to JSON text too, and stores the string under referenceAtKeyPath.
- The Reference Search Equals and Reference Search Not-equals requests take an object, for example {"brand": {"$in_query": {"title": "Apple Inc."}}}. The second example below builds that object.
- The SDK reads only the conditions of the subquery. Its content type and settings such as limit(to:) have no effect.
Example
Basic usage: build a reference condition from a subquery
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
let brandQuery = stack.contentType(uid: "brand").entry().query()
.where(valueAtKey: "title", .equals("Apple Inc."))
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
.where(referenceAtKeyPath: "brand", .include(brandQuery))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
switch result {
case .success(let contentstackResponse):
for entry in contentstackResponse.items {
print(entry.title)
}
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}Search by a referenced field with $in_query
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
.addQuery(with: "brand", value: ["$in_query": ["title": "Apple Inc."]])
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
guard case .success(let contentstackResponse) = result else { return }
for entry in contentstackResponse.items {
print(entry.title)
}
}Exclude entries by a referenced field with $nin_query
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
.addQuery(with: "brand", value: ["$nin_query": ["title": "Apple Inc."]])
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
guard case .success(let contentstackResponse) = result else { return }
for entry in contentstackResponse.items {
print(entry.title)
}
}where(valueAtKey:_:)
where(valueAtKey:_:) adds a condition that matches entries by the value of one field.
| Name | Type | Description |
|---|---|---|
| valueAtKey (required) | String | UID or dot path of the field to match. |
| operation (required) | Query.Operation | Operator and value the field must match. |
Returns: Query. The same query, for chaining.
Validation
- There is no client-side validation. The SDK does not check that the field exists.
- Errors that do occur come from the find(_:) call that follows, not from where(valueAtKey:_:).
Additional Resource Refer to Delivery API Errors for the full error code list.
Behavior
- Client-side only. where(valueAtKey:_:) writes {"<valueAtKey>": <condition>} into the conditions of the query and makes no request. The find(_:) method sends them as JSON in the query parameter. See Equals Operator.
- where(valueAtKey:_:) passes its arguments to the where(valueAtKeyPath:_:) method and returns the result as a Query.
- The Query.Operation table on the Query page lists each operator and the value format the SDK writes.
- A second condition on the same field replaces the first. For a range, use the operator(_:) method with one subquery per condition.
- To filter on a field inside a Group or Modular Blocks field, pass its dot path, for example bank_offers.card_type. See Equals Operator Within Group.
- On a query from stack.taxonomy().query(), pass taxonomies.<taxonomy_uid> as the key and a term UID as the value.
Example
Basic usage: match entries by title
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
.where(valueAtKey: "title", .equals("Redmi Note 3"))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
switch result {
case .success(let contentstackResponse):
for entry in contentstackResponse.items {
print(entry.title)
}
case .failure(let error):
if let apiError = error as? APIError {
print("Error \(apiError.errorCode): \(apiError.errorMessage)")
} else {
print(error)
}
}
}Match entries whose field equals any listed value
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
.where(valueAtKey: "price_in_usd", .includes([101, 749]))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
guard case .success(let contentstackResponse) = result else { return }
for entry in contentstackResponse.items {
print(entry.title)
}
}Match a field inside a Group field
import ContentstackSwift
let stack = Contentstack.stack(apiKey: "API_KEY", deliveryToken: "DELIVERY_TOKEN", environment: "ENVIRONMENT")
stack.contentType(uid: "CONTENT_TYPE_UID").entry().query()
.where(valueAtKey: "bank_offers.card_type", .notEquals("Debit Card"))
.find { (result: Result<ContentstackResponse<EntryModel>, Error>, response: ResponseType) in
guard case .success(let contentstackResponse) = result else { return }
for entry in contentstackResponse.items {
print(entry.title)
}
}