El lenguaje de consulta de dominio (RQL) es un lenguaje de consulta basado en cadenas que restringe las búsquedas al recuperar objetos de un dominio. Los métodos específicos del SDK pasan las consultas al motor de consultas de dominio, que recupera los objetos coincidentes del dominio. La sintaxis del lenguaje de consulta de dominio se basa en NSPredicate.
Las consultas evalúan un predicado para cada objeto de la colección consultada. Si el predicado se resuelve como true, la colección de resultados incluye el objeto.
You can use Realm Query Language in most Realm SDKs with your SDK's filter or query methods. The Swift SDK is the exception, as it uses the NSPredicate query API. Some SDKs also support idiomatic APIs for querying realms in their language.
Query with Realm SDKs
For further reading on SDK-specific methods for querying realms, see the documentation for your SDK:
The C++ SDK currently implements only a subset of RQL. For examples querying Realm in the C++ SDK, refer to:
Nota
El SDK de Swift no admite Realm Query Language
El SDK de Swift no admite consultas con el lenguaje de consulta Realm. En su lugar, puede usar NSPredicate para consultar Realm. Para ver ejemplos de consultas de Realm en el SDK de Swift, consulte Filtrar datos - SDK de Swift.
You can also use Realm Query Language to browse for data in Realm Studio. Realm Studio is a visual tool to view, edit, and design Realm files.
Examples on This Page
Many of the examples in this page use a simple data set for a to-do list app. The two Realm object types are Project and Item.
An
Itemhas a name, assignee's name, and completed flag. There is also an arbitrary number for priority (higher is more important) and a count of minutes spent working on it.A
Projecthas zero or moreItemsand an optional quota for minimum number of to-do items expected to be completed.
See the schema for these two classes, Project and Item, below:
public class Item extends RealmObject { ObjectId id = new ObjectId(); String name; Boolean isComplete = false; String assignee; Integer priority = 0; Integer progressMinutes = 0; final RealmResults<Project> projects = null; } public class Project extends RealmObject { ObjectId id = new ObjectId(); String name; RealmList<Item> items; Integer quota = null; }
open class Item(): RealmObject() { var id: ObjectId = new ObjectId() lateinit var name: String var isComplete: Boolean = false var assignee: String? = null var priority: Int = 0 var progressMinutes: Int = 0 } open class Project(): RealmObject() { var id: ObjectId = new ObjectId() lateinit var name: String lateinit var items: RealmList<Item> var quota: Int? = null }
public class Item : RealmObject { [] [] public ObjectId Id { get; set; } = ObjectId.GenerateNewId(); [] [] public string Name { get; set; } [] public bool IsComplete { get; set; } = false; [] public string Assignee { get; set; } [] public int Priority { get; set; } = 0; [] public int ProgressMinutes { get; set; } = 0; [] [] public IQueryable<Project> Projects { get; } } public class Project : RealmObject { [] [] public ObjectId Id { get; set; } = ObjectId.GenerateNewId(); [] public string Name { get; set; } [] public IList<Item> Items { get; } [] public int Quota { get; set; } }
const ItemModel = { name: "Item", properties: { id: "objectId", name: {type: "string", indexed: "full-text"}, isComplete: { type: "bool", default: false }, assignee: "string?", priority: { type: "int", default: 0, }, progressMinutes: { type: "int", default: 0, }, projects: { type: "linkingObjects", objectType: "Project", property: "items", }, }, primaryKey: "id", }; const ProjectModel = { name: "Project", properties: { id: "objectId", name: "string", items: "Item[]", quota: "int?", }, primaryKey: "id", };
const ItemModel = { name: "Item", properties: { id: "objectId", name: {type: "string", indexed: "full-text"}, isComplete: { type: "bool", default: false }, assignee: "string?", priority: { type: "int", default: 0, }, progressMinutes: { type: "int", default: 0, }, projects: { type: "linkingObjects", objectType: "Project", property: "items", }, }, primaryKey: "id", }; const ProjectModel = { name: "Project", properties: { id: "objectId", name: "string", items: "Item[]", quota: "int?", }, primaryKey: "id", };
class Item(): RealmObject { var _id: ObjectId = ObjectId() var name: String = "" var isComplete: Boolean = false var assignee: String? = null var priority: Int = 0 var progressMinutes: Int = 0 } class Project(): RealmObject { var _id: ObjectId = ObjectId() var name: String = "" var items: RealmList<Item> = realmListOf<Item>() var quota: Int? = null }
part 'models.realm.dart'; () class _Project { ("_id") () late ObjectId id; late String name; late List<_Item> items; int? quota; } () class _Item { ("_id") () late ObjectId id; (RealmIndexType.fullText) late String name; bool isComplete = false; String? assignee; int priority = 0; int progressMinutes = 0; }
Expresiones
Los filtros consisten en expresiones dentro de un predicado. Una expresión consta de uno de los siguientes:
The name of a property of the object currently being evaluated.
Un operador y hasta dos expresiones de argumento. Por ejemplo, en la expresión
A + B,A + Bes una expresión, peroAyBtambién son expresiones de argumento para el operador+.A value, such as a string (
'hello') or a number (5).
"progressMinutes > 1 AND assignee == $0", "Ali"
Parameterized Queries
Create parameterized queries to interpolate variables into prepared Realm Query Language statements. The syntax for interpolated variables is $<int>, starting at 0. Pass the positional arguments as additional arguments to Realm SDK methods that use Realm Query Language.
Include just one parameter with $0.
"progressMinutes > 1 AND assignee == $0", "Ali"
Incluye múltiples parámetros con números enteros ascendentes a partir de $0.
"progressMinutes > $0 AND assignee == $1", 1, "Alex"
Query Formats
The following table shows how a query should be formatted when serialized and parameterized for the following data types:
Tipo | Parameterized Example | Serialized Example | Nota |
|---|---|---|---|
Booleano | "setting == $0", false | "configuración == falso" |
|
"name == $0", "George" | "name == 'George'" | Applies to | |
"edad > $0", 5.50 | "edad > 5,50" | Applies to | |
"date < $0", dateObject | "date < 2021-02-20@17:30:15:0" | For parameterized date queries, you must pass in a date object. For serialized date queries, you can represented the date in the following formats:
| |
"_id == $0", oidValue | "_id == oid(507f1f77bcf86cd799439011)" | For parameterized ObjectId queries, you must pass in an ObjectId. For serialized ObjectId queries, the string representation is | |
"id == $0", uuidValue | "id == uuid(d1b186e1-e9e0-4768-a1a7-c492519d47ee)" | Para queries UUID parametrizadas, debes enviar un UUID. Para consultas UUID serializadas, la representación en cadena es | |
Binario | "value == $0", "binary" | "value == 'binary'" | Para caracteres ASCII, RQL serializa el valor binario como una cadena, entre comillas. Para caracteres no imprimibles, RQL serializa el valor binario a un valor de base 64. |
"ANY items.name == {$0, $1}", "milk", "bread" | "ANY items.name == {'milk', 'bread'}" | Applies for list, collections, and sets. A parameterized value should be used for each member of the list. | |
RealmObject | "ANY items == $0", obj("Item", oid(6489f036f7bd0546377303ab)) | "ANY items == obj('Item', oid(6489f036f7bd0546377303ab))" | Para pasar un RealmObject, necesita la clase y la clave principal del objeto. |
Notación de puntos
Al referirse a la propiedad de un objeto, se puede utilizar la notación de puntos para referirse a las propiedades secundarias de ese objeto. Incluso se puede hacer referencia a las propiedades de objetos incrustados y relaciones con la notación de puntos.
For example, consider a query on an object with a workplace property that refers to a Workplace object. The Workplace object has an embedded object property, address. You can chain dot notations to refer to the zipcode property of that address:
"workplace.address.zipcode == 10019"
Nil Type
Realm Query Language include the nil type to represent a null pointer. You can either reference nil directly in your queries or with a parameterized query. If you're using a parameterized query, each SDK maps its respective null pointer to nil.
"assignee == nil"
// comparison to language null pointer "assignee == $0", null
Operadores de comparación
The most straightforward operation in a search is to compare values.
Importante
Types Must Match
El tipo en ambos lados del operador debe ser equivalente. Por ejemplo, comparar un ObjectId con una cadena generará un error de precondición con un mensaje como este:
"Expected object of type object id for property 'id' on object of type 'User', but received: 11223344556677889900aabb (Invalid value)"
Puede comparar cualquier tipo numérico con cualquier otro tipo numérico, incluidos decimal, float y Decimal128.
Operador | Descripción |
|---|---|
| Evaluates to |
==, = | Evaluates to |
> | Evaluates to |
>= | Evaluates to |
IN | Evaluates to |
< | Devuelve |
<= | Se evalúa como |
!=, <> | Evaluates to |
Ejemplo
El siguiente ejemplo usa los operadores de comparación del Realm Query Language para:
Find high priority to-do items by comparing the value of the
priorityproperty value with a threshold number, above which priority can be considered high.Find long-running to-do items by seeing if the
progressMinutesproperty is at or above a certain value.Find unassigned to-do items by finding items where the
assigneeproperty is equal tonull.Busca elementos de tareas pendientes dentro de un cierto rango de tiempo encontrando elementos donde la propiedad
progressMinutesestá entre dos números.Busca elementos pendientes con una cantidad determinada de
progressMinutesde la lista dada.
// Find high priority to-do items by comparing the value of the ``priority`` // property value with a threshold number, above which priority can be considered high. "priority > $0", 5 // Find long-running to-do items by seeing if the progressMinutes property is at or above a certain value. "progressMinutes > $0", 120 // Find unassigned to-do items by finding items where the assignee property is equal to null. "assignee == $0", null // Find to-do items within a certain time range by finding items // where the progressMinutes property is between two numbers. "progressMinutes BETWEEN { $0 , $1 }", 30, 60 // Find to-do items with a certain amount of progressMinutes from the given list. "progressMinutes IN { $0, $1, $2, $3, $4, $5 }", 10, 20, 30, 40, 50, 60
Operadores lógicos
Make compound predicates using logical operators.
Operador | Descripción |
|---|---|
AND&& | Se evalúa como |
NOT! | Negates the result of the given expression. |
OR|| | Evaluates to |
Ejemplo
We can use the query language's logical operators to find all of Ali's completed to-do items. That is, we find all items where the assignee property value is equal to 'Ali' AND the isComplete property value is true:
"assignee == $0 AND isComplete == $1", "Ali", true
Operadores de String
Compara valores de strings utilizando estos operadores de strings. Los comodines tipo Regex permiten una mayor flexibilidad en la búsqueda.
Nota
Puede utilizar los siguientes modificadores con los operadores de cadena:
[c]for case insensitivity."name CONTAINS[c] $0", 'a'
Operador | Descripción |
|---|---|
BEGINSWITH | Evaluates to |
CONTAINS | Da como resultado |
ENDSWITH | Evaluates to |
LIKE | Evaluates to
For example, the wildcard string "d?g" matches "dog", "dig", and "dug", but not "ding", "dg", or "a dog". |
==, = | Evaluates to |
!=, <> | Se evalúa como |
Ejemplo
Se utilizan los operadores de string del motor de query para encontrar lo siguiente:
Projects with a name starting with the letter 'e'
Projects with names that contain 'ie'
"name BEGINSWITH[c] $0", 'e' "name CONTAINS $0", 'ie'
ObjectId and UUID Operators
Consulta los ObjectIds y UUID de BSON. Estos tipos de datos se utilizan a menudo como claves principales.
To query with ObjectIds, use a parameterized query. Pass the ObjectId or UUID you're querying against as the argument.
"_id == $0", oidValue
You can also put a string representation of the ObjectId you're evaluating in oid(<ObjectId String>).
"_id == oid(6001c033600510df3bbfd864)"
Para realizar consultas con UUID, coloque una representación de cadena del UUID que está evaluando en uuid(<UUID String>).
"id == uuid(d1b186e1-e9e0-4768-a1a7-c492519d47ee)"
Operador | Descripción |
|---|---|
==, = | Devuelve |
!=, <> | Evaluates to |
Operadores aritméticos
Realizar operaciones aritméticas básicas en un lado de una expresión RQL al evaluar tipos de datos numéricos.
"2 * priority > 6" // Is equivalent to "priority >= 2 * (2 - 1) + 2"
You can also use multiple object properties together in a mathematic operation.
"progressMinutes * priority == 90"
Operador | Descripción |
|---|---|
* | Multiplication. |
/ | Division. |
+ | Addition. |
- | Subtraction. |
() | Group expressions together. |
Type Operator
Check the type of a property using the @type operator. You can only use the type operator with mixed types and dictionaries.
Evaluate the property against a string representation of the data type name. Refer to SDK documentation on the mapping from the SDK language's data types to Realm data types.
Operador | Descripción |
|---|---|
| Check if type of a property is the property name as a string. Use |
"mixedType.@type == 'string'" "mixedType.@type == 'bool'"
Dictionary Operators
Compare dictionary values using these dictionary operators.
Operador | Descripción |
|---|---|
| Devuelve objetos que tienen el valor especificado en la expresión de la derecha. |
| Returns objects that have the key specified in the right-hand expression. |
| The number of elements in a dictionary. |
| Access the value at a key of a dictionary. |
| Verifica si el diccionario contiene propiedades de cierto tipo. |
También puede usar operadores de diccionario junto con operadores de comparación para filtrar objetos según sus claves y valores. Los siguientes ejemplos muestran cómo usar operadores de diccionario con operadores de comparación. Todos los ejemplos consultan una colección de objetos Realm con una propiedad de diccionario dict llamada.
Ejemplo
The following examples use various dictionary operators.
// Evaluates if there is a dictionary key with the name 'foo' "ANY dict.@keys == $0", 'foo' // Evaluates if there is a dictionary key with key 'foo' and value 'bar "dict['foo'] == $0", 'bar' // Evaluates if there is greater than one key-value pair in the dictionary "dict.@count > $0", 1 // Evaluates if dictionary has property of type 'string' "ANY dict.@type == 'string'" // Evaluates if all the dictionary's values are integers "ALL dict.@type == 'bool'" // Evaluates if dictionary does not have any values of type int "NONE dict.@type == 'double'" // ANY is implied. "dict.@type == 'string'"
Operadores de fecha
query tipos de fecha en un realm.
Generally, you should use a parameterized query to pass a date data type from the SDK language you are using to a query.
"timeCompleted < $0", someDate
You can also specify dates in the following two ways:
As a specific date (in UTC)-
YYYY-MM-DD@HH:mm:ss:nnnnnnnnnn(year-month-day@hours:minutes:seconds:nanoseconds), UTC. You can also useTinstead of@to separate the date from the time.Como un tiempo en segundos desde la Unix epoch-
Ts:n, dondeTdesigna el inicio del tiempo,ses el número de segundos ynes el número de nanosegundos.
Date supports comparison operators.
Ejemplo
The following example shows how to use a parameterized query with a date object:
var date = new Date("2021-02-20@17:30:15:0"); "timeCompleted > $0", date
Aggregate Operators
Apply an aggregate operator to a collection property of a Realm object. Aggregate operators traverse a collection and reduce it to a single value.
Operador | Descripción |
|---|---|
@avg | Evaluates to the average value of a given numerical property across a collection. If any values are |
@count | Evalúa al número de objetos en la colección dada. |
@max | Se evalúa como el valor más alto de una propiedad numérica dada en una colección. Los valores |
@min | Evaluates to the lowest value of a given numerical property across a collection. |
@sum | Evaluates to the sum of a given numerical property across a collection, excluding |
Ejemplo
These examples all query for projects containing to-do items that meet this criteria:
Proyectos con una prioridad promedio de elementos superior a 5.
Proyectos con un elemento cuya prioridad es menor que 5.
Projects with an item whose priority is greater than 5.
Projects with more than 5 items.
Projects with long-running items.
var priorityNum = 5; "items.@avg.priority > $0", priorityNum "items.@max.priority < $0", priorityNum "items.@min.priority > $0", priorityNum "items.@count > $0", 5 "items.@sum.progressMinutes > $0", 100
Collection Operators
A collection operator lets you query list properties within a collection of objects. Collection operators filter a collection by applying a predicate to every element of a given list property of the object. If the predicate returns true, the object is included in the output collection.
Operador | Descripción |
|---|---|
| Devuelve objetos donde el predicado evalúa como |
| Devuelve objetos donde el predicado evalúa a |
| Returns objects where the predicate evaluates to false for all objects in the collection. |
Ejemplo
Este ejemplo utiliza operadores de colecciones para encontrar proyectos que contengan tareas pendientes que cumplan ciertos criterios:
// Projects with no complete items. "NONE items.isComplete == $0", true // Projects that contain a item with priority 10 "ANY items.priority == $0", 10 // Projects that only contain completed items "ALL items.isComplete == $0", true // Projects with at least one item assigned to either Alex or Ali "ANY items.assignee IN { $0 , $1 }", "Alex", "Ali" // Projects with no items assigned to either Alex or Ali "NONE items.assignee IN { $0 , $1 }", "Alex", "Ali"
Comparaciones de listas
Puede utilizar operadores de comparación y operadores de colección para filtrar según listas de datos.
You can compare any type of valid list. This includes:
colecciones de objetos Realm, que le permiten filtrar con respecto a otros datos en el reino.
"oid(631a072f75120729dc9223d9) IN items.id" lists defined directly in the query, which let you filter against static data. You define static lists as a comma-separated list of literal values enclosed in opening (
{) and closing (}) braces."priority IN {0, 1, 2}" objetos de lista nativos pasados en una expresión parametrizada, que le permiten pasar datos de la aplicación directamente a sus consultas.
const ids = [ new BSON.ObjectId("631a072f75120729dc9223d9"), new BSON.ObjectId("631a0737c98f89f5b81cd24d"), new BSON.ObjectId("631a073c833a34ade21db2b2"), ]; const parameterizedQuery = realm.objects("Item").filtered("id IN $0", ids);
If you do not define a collection operator, a list expression defaults to the ANY operator.
Ejemplo
Estas dos consultas de lista son equivalentes:
age == ANY {18, 21}age == {18, 21}
Ambas consultas devuelven objetos con una propiedad de edad igual a 18 o 21. También puede hacer lo contrario y devolver objetos solo si la edad no es igual a 18 o 21:
age == NONE {18, 21}
The following table includes examples that illustrate how collection operators interact with lists and comparison operators:
expresión | Match? | Razón |
| true | A value on the left (3) is greater than some value on the right (both 1 and 2) |
| true | 3 no coincide con ninguno de los dos: 1 o 2 |
| false | Ni 4 ni 8 coinciden con ningún valor en la lista de la derecha (5, 9 o 11) |
| true | Un valor a la izquierda (7) no es menor o igual a 1 y 2 |
| true | Every value on the left (1 and 2) is equal to 1, 2 or 3 |
| false | 1 matches a value in the NONE list (1 or 2) |
| true | Una lista vacía coincide con todas las listas |
| false | 12 es mayor que todos los valores de la derecha (5, 9 y 11) |
| true | 4 y 8 son ambos menores que cierto valor a la derecha (5, 9 o 11) |
| true | 0 and 1 are both less than none of 1 and 2 |
Full Text Search
Puede utilizar RQL para consultar propiedades que tengan una anotación de búsqueda de texto completo (FTS). FTS admite búsquedas de coincidencia booleana de palabras, en lugar de búsquedas por relevancia. Para obtener información sobre cómo habilitar el FTS en una propiedad, consulte la documentación de FTS correspondiente a su SDK:
El SDK de Swift aún no admite la Búsqueda de Texto Completo.
Para consultar estas propiedades, utiliza el predicado TEXT en tu query.
You can search for entire words or phrases, or limit your results with the following characters:
Exclude results for a word by placing the
-character in front of the word.Specify prefixes by placing the
*character at the end of a prefix. Suffix searching is not currently supported.
En el siguiente ejemplo, consultamos la propiedad Item.name:
// Filter for items with 'write' in the name "name TEXT $0", "write" // Find items with 'write' but not 'tests' using '-' "name TEXT $0", "write -tests" // Find items starting with 'wri-' using '*' "name TEXT $0", "wri*"
Detalles del tokenizador de búsqueda de texto completo
Full-Text Search (FTS) indexes support:
Tokens are diacritics- and case-insensitive.
Tokens can only consist of characters from ASCII and the Latin-1 supplement (western languages). All other characters are considered whitespace.
Las palabras separadas por un guion (-) se dividen en dos tokens. Por ejemplo,
full-textse divide enfullytext.
Query geoespacial
Puedes realizar query sobre datos geoespaciales utilizando el operador geoWithin. El operador geoWithin toma el par de latitud/longitud en la propiedad coordinates de un objeto personalizado incrustado y una forma geoespacial. El operador verifica si el punto cordinates está contenido dentro de la forma geoespacial.
The following geospatial shapes are supported for querying:
GeoCircleGeoBoxGeoPolygon
Para query datos geoespaciales:
Crea un objeto con una propiedad que contenga los datos geoespaciales incorporados.
Define la forma geoespacial para establecer el límite de la query.
Query using the
geoWithinRQL operator.
In the following query, we are checking that the coordinates of the embeddeded location property are contained within the GeoCircle shape, smallCircle:
"location geoWithin $0", smallCircle
Para obtener más información sobre cómo definir formas y objetos geoespaciales con datos geoespaciales integrados, consulte la documentación geoespacial de su SDK:
Queries de vínculos inversos
A backlink is an inverse relationship link that lets you look up objects that reference another object. Backlinks use the to-one and to-many relationships defined in your object schemas but reverse the direction. Every relationship that you define in your schema implicitly has a corresponding backlink.
You can access backlinks in queries using the @links.<ObjectType>.<PropertyName> syntax, where <ObjectType> and <PropertyName> refer to a specific property on an object type that references the queried object type.
// Find items that belong to a project with a quota greater than 10 (@links) "@links.Project.items.quota > 10"
You can also define a linkingObjects property to explicitly include the backlink in your data model. This lets you reference the backlink through an assigned property name using standard dot notation.
// Find items that belong to a project with a quota greater than 10 (LinkingObjects) "projects.quota > 10"
El resultado de un vínculo inverso se trata como una colección y soporta operadores de colección.
// Find items where any project that references the item has a quota greater than 0 "ANY @links.Project.items.quota > 0" // Find items where all projects that reference the item have a quota greater than 0 "ALL @links.Project.items.quota > 0"
Puede utilizar operadores agregados en la colección de vínculos de retroceso.
// Find items that are referenced by multiple projects "projects.@count > 1" // Find items that are not referenced by any project "@links.Project.items.@count == 0" // Find items that belong to a project where the average item has // been worked on for at least 5 minutes "@links.Project.items.items.@avg.progressMinutes > 10"
Puede consultar la cantidad de todas las relaciones que apuntan a un objeto utilizando el operador @count directamente en @links.
// Find items that are not referenced by another object of any type "@links.@count == 0"
Subqueries
Iterate through list properties with another query using the SUBQUERY() predicate function.
Subqueries are useful for the following scenarios:
Matching each object in a list property on multiple conditions
Contando el número de objetos que coinciden con una subconsulta
SUBQUERY() has the following structure:
SUBQUERY(<collection>, <variableName>, <predicate>)
collection: The name of the property to iterate throughvariableName:Un nombre de variable del elemento a utilizar en la subconsultapredicate: El predicado de subconsulta. Utiliza la variable especificada porvariableNamepara referirse al elemento que se está iterando actualmente.
A subquery iterates through the given collection and checks the given predicate against each object in the collection. The predicate can refer to the current iterated object with the variable name passed to SUBQUERY().
A subquery expression resolves to a list of objects. Realm only supports the @count aggregate operator on the result of a subquery. This allows you to count how many objects in the subquery input collection matched the predicate.
Puedes usar el conteo del resultado de la subconsulta como cualquier otro número en una expresión válida. En particular, puedes comparar el conteo con el número 0 para devolver todos los objetos coincidentes.
Ejemplo
The following example shows two subquery filters on a collection of projects.
// Returns projects with items that have not been completed // by a user named Alex. "SUBQUERY(items, $item, $item.isComplete == false AND $item.assignee == 'Alex').@count > 0" // Returns the projects where the number of completed items is // greater than or equal to the value of a project's `quota` property. "SUBQUERY(items, $item, $item.isComplete == true).@count >= quota"
Sort, Distinct & Limit
Sort and limit the results collection of your query using additional operators.
Operador | Descripción |
|---|---|
| Specify the name of the property to compare, and whether to sort by ascending ( For example, if you |
| Specify a name of the property to compare. Remove duplicates for that property in the results collection. If you specify multiple DISTINCT fields, the query removes duplicates by the first field, and then the second. For example, if you |
| Limita la colección de resultados al número especificado. |
Ejemplo
Use the query engine's sort, distinct, and limit operators to find to-do items where the assignee is Ali:
Sorted by priority in descending order
Enforcing uniqueness by name
Limitar los resultados a 5 elementos
"assignee == 'Ali' SORT(priority DESC) DISTINCT(name) LIMIT(5)"
Flexible Sync RQL Limitations
Requisitos de suscripción a campos consultables indexados
Adding an indexed queryable field to your App can improve performance for simple queries on data that is strongly partitioned. For example, an app where queries strongly map data to a device, store, or user, such as user_id == $0, “641374b03725038381d2e1fb”, is a good candidate for an indexed queryable field. However, an indexed queryable field has specific requirements for use in a query subscription:
The indexed queryable field must be used in every subscription query. It cannot be missing from the query.
The indexed queryable field must use an
==orINcomparison against a constant at least once in the subscription query. (El campo consultable debe utilizar una comparación o contra una constante al menos una vez en la consulta de suscripción.) For example,user_id == $0, "641374b03725038381d2e1fb"orstore_id IN $0, {1,2,3}. (Por ejemplo, o .)
Opcionalmente, puedes incluir una comparación de AND siempre que el campo indexado consultable se compare directamente con una constante usando == o IN al menos una vez. Por ejemplo, store_id IN {1,2,3} AND region=="Northeast" o store_id == 1 AND (active_promotions < 5 OR num_employees < 10).
Invalid Flexible Sync queries on an indexed queryable field include queries where:
The indexed queryable field does not use
ANDwith the rest of the query. For examplestore_id IN {1,2,3} OR region=="Northeast"is invalid because it usesORinstead ofAND. Similarly,store_id == 1 AND active_promotions < 5 OR num_employees < 10is invalid because theANDonly applies to the term next to it, not the entire query.El campo consultable indexado no se utiliza en un operador de igualdad. Por ejemplo,
store_id > 2 AND region=="Northeast"no es válido porque solo utiliza el operador>con el campo consultable indexado y no tiene una comparación de igualdad.The query is missing the indexed queryable field entirely. For example,
region=="Northeastortruepredicateare invalid because they do not contain the indexed queryable field.
Unsupported Query Operators in Flexible Sync
Flexible Sync has some limitations when using RQL operators. When you write the query subscription that determines which data to sync, the server does not support these query operators. However, you can still use the full range of RQL features to query the synced data set in the client application.
Tipo de operador | Operadores no compatibles |
|---|---|
Aggregate Operators |
|
Query Suffixes |
|
Las queries que no distinguen entre mayúsculas y minúsculas ([c]) no pueden usar índices de manera eficaz. Como resultado, no se recomiendan las queries que no distinguen entre mayúsculas y minúsculas, ya que podrían provocar problemas de rendimiento.
Flexible Sync only supports @count for array fields.
List Queries
Flexible Sync admite la consulta de listas usando el operador IN.
Puede consultar una lista de constantes para ver si contiene el valor de un campo consultable:
// Query a constant list for a queryable field value "priority IN { 1, 2, 3 }"
If a queryable field has an array value, you can query to see if it contains a constant value:
// Query an array-valued queryable field for a constant value "'comedy' IN genres"
Advertencia
You cannot compare two lists with each other in a Flexible Sync query. Note that this is valid Realm Query Language syntax outside of Flexible Sync queries.
// Invalid Flexible Sync query. Do not do this! "{'comedy', 'horror', 'suspense'} IN genres" // Another invalid Flexible Sync query. Do not do this! "ANY {'comedy', 'horror', 'suspense'} != ANY genres"
Objetos incrustados o vinculados
Flexible Sync does not support querying on properties in Embedded Objects or links. For example, obj1.field == "foo".
Query Size Limit
The size limit for any given query subscription in your subscription set is 256 kB. Exceeding this limit results in a LimitsExceeded Error.