iOS
...
Data Objects
Техническое руководство по запросам ParseSwift SDK
20 мин
кулинарная книга запросов для parseswift введение в руководстве по базовым запросам https //www back4app com/docs/ios/parse swift sdk/data objects/basic queries мы представили некоторые из основных методов для построения запросов и извлечения данных из базы данных back4app sdk parseswift sdk parseswift sdk предлагает практические способы построения более сложных запросов для реальных приложений в этом руководстве вы глубоко погрузитесь в query\<u> query\<u> (обобщенный) класс и увидите все методы, которые вы можете использовать для построения своих запросов вы будете использовать простой класс базы данных (названный профиль профиль ) с некоторыми смоделированными данными для выполнения запросов с использованием swift перед тем как начать, мы должны установить несколько понятий о объектах и типах данных в этом руководстве мы относим объекты к любому типу данных (например, структурам), которые могут храниться в базе данных в некоторых ситуациях их также называют элементами или элементами свойства — это члены типа данных (в основном структур) однако здесь мы обычно называем их полями parseswift использует термин «ключ», чтобы указать имя свойств таким образом, любой параметр, помеченный как «ключ» в любом методе из parseswift sdk parseswift sdk указывает на то, что его значение должно соответствовать имени поля предварительные требования чтобы завершить этот учебник, вам потребуется приложение созданное на back4app базовое ios приложение для тестирования запросов цель чтобы изучить различные методы, которые предоставляет класс query\<u> query\<u> для выполнения запросов класс query\<u> в этом руководстве мы будем запрашивать информацию о контакте человека эти данные хранятся в классе profile profile в базе данных back4app для того чтобы получить профили через ios приложение, нам нужно создать структуру profile profile , которая будет содержать такую информацию 1 import parseswift 2 3 4 struct profile parseobject { 5 6 7 // custom properties to organize the person's information 8 var name string? 9 var birthday date? 10 var numberoffriends int? 11 var favoritefoods \[string]? 12 var luckynumbers \[int]? 13 var lastloginlocation parsegeopoint? // a data type to store coordinates for geolocation 14 var isactive bool? 15 var membership pointer\<membership>? // more details about membership below 16 17 18 } кроме того, мы используем объект членство членство для показа того, как запросы между профиль профиль и членство членство взаимодействуют друг с другом структура членство членство реализована следующим образом 1 import parseswift 2 3 4 struct membership parseobject { 5 6 7 // custom properties to organize the membership's information 8 var typedescription string? 9 var expirationdate date? 10 11 12 } любая операция запроса в базе данных back4app выполняется с помощью обобщенного класса query\<profile> query\<profile> где обобщенный тип профиль профиль (соответствующий протоколу parseswift parseswift ) является объектом, который мы пытаемся получить после создания объекта query\<profile> query\<profile> мы должны вызвать один из его find( ) find( ) методов (см руководство по базовым запросам https //www back4app com/docs/ios/parse swift sdk/data objects/basic queries ) для обработки результата, возвращаемого запросом вы можете узнать больше о query\<u> query\<u> классе здесь в официальной документации https //github com/parse community/parse swift сохранение объектов данных с помощью следующего фрагмента кода мы создаем и сохраняем некоторые данные для тестирования различных запросов 1 let adamsandler = profile( 2 name "adam sandler", 3 birthday date(string "09/09/1996"), 4 numberoffriends 2, 5 favoritefoods \["lobster", "bread"], 6 luckynumbers \[2, 7], 7 lastloginlocation try? parsegeopoint(latitude 37 38412167489413, longitude 122 01268034622319), 8 isactive false, 9 membership nil 10 ) 11 12 let britneyspears = profile( 13 name "britney spears", 14 birthday date(string "12/02/1981"), 15 numberoffriends 52, 16 favoritefoods \["cake", "bread"], 17 luckynumbers \[22, 7], 18 lastloginlocation try? parsegeopoint(latitude 37 38412167489413, longitude 122 01268034622319), 19 isactive true, 20 membership nil 21 ) 22 23 let carsonkressley = profile( 24 name "carson kressley", 25 birthday date(string "03/27/1975"), 26 numberoffriends 12, 27 favoritefoods \["fish", "cookies"], 28 luckynumbers \[8, 7], 29 lastloginlocation try? parsegeopoint(latitude 37 38412167489413, longitude 122 01268034622319), 30 isactive true, 31 membership nil 32 ) 33 34 // we create and save a membership object 35 let premiummembership = membership(typedescription "premium", expirationdate date(string "10/10/2030")) 36 let savedpremiummembership = try! premiummembership save() // careful with the forced unwrap 37 38 let danaykroyd = profile( 39 name "dan aykroyd", 40 birthday date(string "07/01/1952"), 41 numberoffriends 66, 42 favoritefoods \["jam", "peanut butter"], 43 luckynumbers \[22, 77], 44 lastloginlocation try? parsegeopoint(latitude 37 38412167489413, longitude 122 01268034622319), 45 isactive true, 46 membership try? init(savedpremiummembership) 47 ) 48 49 let eddymurphy = profile( 50 name "eddie murphy", 51 birthday date(string "04/03/1961"), 52 numberoffriends 49, 53 favoritefoods \["lettuce", "pepper"], 54 luckynumbers \[6, 5], 55 lastloginlocation try? parsegeopoint(latitude 27 104919974838154, longitude 52 61428045237739), 56 isactive false, 57 membership nil 58 ) 59 60 let fergie = profile( 61 name "fergie", 62 birthday date(string "03/27/1975"), 63 numberoffriends 55, 64 favoritefoods \["lobster", "shrimp"], 65 luckynumbers \[12, 7], 66 lastloginlocation try? parsegeopoint(latitude 27 104919974838154, longitude 52 61428045237739), 67 isactive false, 68 membership nil 69 ) 70 71 do { 72 = try? adamsandler save() 73 = try? britneyspears save() 74 = try? carsonkressley save() 75 = try? danaykroyd save() 76 = try? eddymurphy save() 77 } catch { 78 // handle the errors here 79 } после выполнения приведенного выше кода у нас должна быть небольшая база данных для работы узнайте больше о том, как сохранять данные с помощью parseswift на ios data objects запросы эти методы отвечают за выполнение запроса и получение его результатов, всегда присутствуя в вашей реализации запроса find //this is the basic method for retrieving your query results 1 let query = profile query() // instantiate a query\<profile> class with no additional constraints 2 3 let profiles = try? query find() // executes the query synchronously returns and array of profiles it throws an error if something happened 4 5 query find { result in // executes the query asynchronously 6 // handle the result (of type result<\[profile], parseerror>) 7 } first //retrieves the first profile instance that meets the query criteria 1 let query = profile query() 2 3 let profile = try? query first() // executes the query synchronously 4 5 query first { result in // executes the query asynchronously 6 // handle the result (of type result\<profile, parseerror>) 7 } count //retrieves the number of elemets found by the query 1 let query = profile query() // instantiate a query\<profile> class with no additional constraints 2 3 let profiles = try? query count() // executes the query synchronously 4 5 query count { result in // executes the query asynchronously 6 // handle the result (of type result\<int, parseerror>) 7 } distinct //runs the query and returns a list of unique values from the results and the specified field, name in this case 1 let query = profile query() // instantiate a query\<profile> class with no additional constraints 2 3 let profiles = try? query distinct("name") // executes the query synchronously 4 5 query distinct("name") { result in // executes the query asynchronously 6 // handle the result (of type result<\[profile], parseerror>) 7 } find all //retrieves a complete list of profile’s that satisfy this query 1 let query = profile query() 2 3 let profiles = try? query findall() // executes the query synchronously 4 5 query findall { result in // executes the query asynchronously 6 // handle the result (of type result<\[profile], parseerror>) 7 } using the objectid //when you need to retrieve an object with a specific objectid 1 let profile = try? profile(objectid "huyfn4yxfd") fetch() // retrieves synchronously the profile with the given objectid it throws an error if something happened 2 3 profile(objectid "huyfn4yxfd") fetch { // retrieves asynchronously the profile with the given objectid 4 // handle the result (of type result\<profile, parseerror>) 5 } запросы с ограничениями на поля строкового типа теперь мы начинаем применять конкретные ограничения к запросам во первых, мы наложим ограничения, которые выбирают объекты только тогда, когда поле типа string string удовлетворяет заданному условию это и любое другое ограничение, наложенное на объект query\<profile> query\<profile> выполняется через объект queryconstraint queryconstraint ниже и в следующих разделах мы подробно расскажем, как строить такие ограничения equal //used when we need to select all the objects which have a field equal to a given string we use the == operator to construct the corresponding constraint on the left hand side goes the field’s name and on the right hand side goes the string to compare against 1 let constraint queryconstraint = "name" == "fergie" // selects all profiles with name equals to fergie 2 let query = profile query(constraint) 3 4 let profiles = try? query find() // executes the query synchronously 5 6 query find { result in // executes the query asynchronously 7 // handle the result (of type result<\[profile], parseerror>) 8 } regular expression //used when one of the fields contains a given string 1 let constraint queryconstraint = containsstring(key "name", substring "ie") 2 // containsstring(key\ substring ) is a method provided by the parseswift sdk 3 let query = profile query(constraint) 4 5 let profiles = try? query find() // executes the query synchronously 6 7 query find { result in // executes the query asynchronously 8 // handle the result (of type result<\[profile], parseerror>) 9 } contains substring //retrieves the number of elemets found by the query 1 let query = profile query() // instantiate a query\<profile> class with no additional constraints 2 3 let profiles = try? query count() // executes the query synchronously 4 5 query count { result in // executes the query asynchronously 6 // handle the result (of type result\<int, parseerror>) 7 } matches text //similar to == but it has additional options like case sensite, language and diacritic sensitive 1 // careful with the force unwrap! 2 let constraint queryconstraint = try! matchestext(key "name", text "fergie", options \[ casesensitive false]) 3 // matchestext(key\ text ,options ) is a method provided by the parseswift sdk 4 5 let query = profile query(constraint) 6 7 let profiles = try? query find() // executes the query synchronously 8 9 query find { result in // executes the query asynchronously 10 // handle the result (of type result<\[profile], parseerror>) 11 } запросы с ограничениями на сравнимые поля очень часто пытаются выбрать объекты, где поле определенного числового типа должно быть равно, отличаться, быть больше или меньше заданного значения это достигается с помощью следующих операций сравнения equal //use this constraint when you need to select objects where a certain number type field is equal to a given value 1 let constraint queryconstraint = "numberoffriends" == 2 // selects all profiles with number of friends = 2 2 let query = profile query(constraint) 3 4 let profiles = try? query find() // executes the query synchronously 5 6 query find { result in // executes the query asynchronously 7 // handle the result (of type result<\[profile], parseerror>) 8 } not equal //the opposite constraint of equals to and it also works with date type fields 1 let constraint queryconstraint = "numberoffriends" != 2 // selects all profiles where the number of friends is different from 2 2 let query = profile query(constraint) 3 4 let profiles = try? query find() // executes the query synchronously 5 6 query find { result in // executes the query asynchronously 7 // handle the result (of type result<\[profile], parseerror>) 8 } less than //to construct this constraint we use the < operator on the left hand side goes the field’s name and on the right hand side goes the value to compare against 1 let constraint queryconstraint = "numberoffriends" < 49 // selects all profiles with a maximum of 48 friends 2 let query = profile query(constraint) 3 4 let profiles = try? query find() // executes the query synchronously 5 6 query find { result in // executes the query asynchronously 7 // handle the result (of type result<\[profile], parseerror>) 8 } less than or equal //to construct this constraint we use the <= operator on the left hand side goes the field’s name (also referred as key) and on the right hand side goes the value to compare against 1 let constraint queryconstraint = "numberoffriends" <= 49 // selects all profiles with a maximum of 49 friends 2 let query = profile query(constraint) 3 4 let profiles = try? query find() // executes the query synchronously 5 6 query find { result in // executes the query asynchronously 7 // handle the result (of type result<\[profile], parseerror>) 8 } greater than //once again, for this constraint we use another operator to construct it, the > operator 1 let constraint queryconstraint = "birthday" > date(string "08/19/1980") // selects all profiles who born after 08/19/1980 2 let query = profile query(constraint) 3 4 let profiles = try? query find() // executes the query synchronously 5 6 query find { result in // executes the query asynchronously 7 // handle the result (of type result<\[profile], parseerror>) 8 } greater than or equal //last but not least, the greater than or equal constraint are constructed using the >= operator 1 let constraint queryconstraint = "numberoffriends" >= 20 // selects all profiles with at least 20 number of friends 2 let query = profile query(constraint) 3 4 let profiles = try? query find() // executes the query synchronously 5 6 query find { result in // executes the query asynchronously 7 // handle the result (of type result<\[profile], parseerror>) 8 } эти ограничения также работают на дата дата тип полей например, мы можем иметь 1 let constraint queryconstraint = "birthday" > date(string "08/19/1980") // selects all profiles who were born after 08/19/1980 2 let query = profile query(constraint) 3 4 let profiles = try? query find() // executes the query synchronously 5 6 query find { result in // executes the query asynchronously 7 // handle the result (of type result<\[profile], parseerror>) 8 } для bool bool тип полей, у нас есть равно и не равно опции например 1 let constraint queryconstraint = "isactive" == true 2 let query = profile query(constraint) // selects all active profiles 3 4 let profiles = try? query find() // executes the query synchronously 5 6 query find { result in // executes the query asynchronously 7 // handle the result (of type result<\[profile], parseerror>) 8 } запросы с ограничениями, связанными с геолокацией для полей, содержащих данные о местоположении (т е типа parsegeopoint parsegeopoint ) у нас есть следующие варианты запросов near //in order to select objects where one of their parsegeopoint type fields is near to another given geopoint, we use 1 guard let geopoint = try? parsegeopoint(latitude 37 38412167489413, longitude 122 01268034622319) else { 2 return 3 } 4 5 let query = profile query(near(key "lastloginlocation", geopoint geopoint)) 6 // near(key\ geopoint ) is a method provided by the parseswift sdk 7 8 let profiles = try? query find() // executes the query synchronously 9 10 query find { result in // executes the query asynchronously 11 // handle the result (of type result<\[profile], parseerror>) 12 } contains //given an object with a parsepolygon type field, in order to select them in a query depending on what geopoints the field contains, we can use the following constraint 1 struct myobject parseswift { 2 3 4 var apolygon parsepolygon? 5 6 7 } 8 9 guard let geopoint = try? parsegeopoint(latitude 37 38412167489413, longitude 122 01268034622319) else { 10 return 11 } 12 13 let query = myobject query(polygoncontains(key "apolygon", point geopoint)) 14 // polygoncontains(key\ point ) is a method provided by the parseswift sdk 15 16 let myobjects = try? query find() // executes the query synchronously 17 18 query find { result in // executes the query asynchronously 19 // handle the result (of type result<\[myobject], parseerror>) 20 } within geo box //used to select objects where a parsegeopoint type field is inside of a given geopoint box this box is described by its northeastpoint and southwestpoint geopoints 1 guard let southwestpoint = try? parsegeopoint(latitude 37 38412167489413, longitude 122 01268034622319), 2 let northeastpoint = try? parsegeopoint(latitude 37 28412167489413, longitude 121 91268034622319) else { 3 return 4 } 5 6 let query = profile query(withingeobox(key "lastloginlocation", fromsouthwest southwestpoint, tonortheast northeastpoint)) 7 // withingeobox(key\ fromsouthwest\ tonortheast ) is a method provided by the parseswift sdk 8 9 let profiles = try? query find() // executes the query synchronously 10 11 query find { result in // executes the query asynchronously 12 // handle the result (of type result<\[profile], parseerror>) 13 } within km/mph //used to select objects according to whether or not a parsegeopoint type field value is near a given geopoint additionally, we should provide the maximum distance for how far the field value can be from the geopoint 1 guard let geopoint = try? parsegeopoint(latitude 37 38412167489413, longitude 122 01268034622319) else { 2 return 3 } 4 5 let query1 = profile query(withinkilometers(key "lastloginlocation", geopoint geopoint, distance 100)) 6 // withinkilometers(key\ geopoint\ distance ) is a method provided by the parseswift sdk 7 8 let query2 = profile query(withinmiles(key "lastloginlocation", geopoint geopoint, distance 100)) 9 // withinmiles(key\ geopoint\ distance ) is a method provided by the parseswift sdk 10 11 // execute the corresponding query within polygon //used to select objects with a parsegeopoint type field in a given polygon the vertices of the polygon are represented by parsegeopoint objects 1 // create the vertices of the polygon (4 in this case) 2 guard let geopoint1 = try? parsegeopoint(latitude 37 48412167489413, longitude 122 11268034622319), 3 let geopoint2 = try? parsegeopoint(latitude 37 48412167489413, longitude 121 91268034622319), 4 let geopoint3 = try? parsegeopoint(latitude 37 38412167489413, longitude 121 91268034622319), 5 let geopoint4 = try? parsegeopoint(latitude 37 38412167489413, longitude 122 01268034622319) else { 6 return 7 } 8 9 let constraint queryconstraint = withinpolygon( 10 key "lastloginlocation", 11 points \[geopoint1, geopoint2, geopoint3, geopoint4] 12 ) 13 // withinpolygon(key\ points ) is a method provided by the parseswift sdk 14 15 let query = profile query(constraint) 16 17 let profiles = try? query find() // executes the query synchronously 18 19 query find { result in // executes the query asynchronously 20 // handle the result (of type result<\[profile], parseerror>) 21 } within radians //similar to ‘within kilometers’ or ‘within miles’ but the distance is expressed in radians 1 guard let geopoint = try? parsegeopoint(latitude 37 48412167489413, longitude 122 11268034622319) else { 2 return 3 } 4 5 let query = profile query(withinradians(key "lastloginlocation", geopoint geopoint, distance 1 5)) 6 // withinradians(key\ geopoint\ distance ) is a method provided by the parseswift sdk 7 8 let profiles = try? query find() // executes the query synchronously 9 10 query find { result in // executes the query asynchronously 11 // handle the result (of type result<\[profile], parseerror>) 12 } запросы с ограничениями, включающими поля типа массив когда объекты, которые мы хотим извлечь, должны удовлетворять определенному условию по любому из их полей типа массив, parseswift sdk parseswift sdk предоставляет следующие альтернативы для достижения этой цели contained in //add a constraint to the query that requires a particular field to be contained in the provided array 1 let constraint queryconstraint = containedin(key "luckynumbers", array \[2, 7]) 2 // containedby(key\ array ) is a method provided by the parseswift sdk 3 4 let query = profile query(constraint) 5 6 let profiles = try? query find() // executes the query synchronously 7 8 query find { result in // executes the query asynchronously 9 // handle the result (of type result<\[profile], parseerror>) 10 } contained by //add a constraint to the query that requires a particular field to be contained by the provided array it retrieves objects where all the elements of their array type field match 1 let constraint queryconstraint = containedby(key "luckynumbers", array \[2, 7]) 2 // containedby(key\ array ) is a method provided by the parseswift sdk 3 4 let query = profile query(constraint) 5 6 let profiles = try? query find() // executes the query synchronously 7 8 query find { result in // executes the query asynchronously 9 // handle the result (of type result<\[profile], parseerror>) 10 } contains all //add a constraint to the query that requires a particular array type field to contain every element of the provided array 1 let constraint queryconstraint = containsall(key "luckynumbers", array \[2, 7]) 2 // containsall(key\ array ) is a method provided by the parseswift sdk 3 4 let query = profile query(constraint) 5 6 let profiles = try? query find() // executes the query synchronously 7 8 query find { result in // executes the query asynchronously 9 // handle the result (of type result<\[profile], parseerror>) 10 } расширенные запросы до сих пор мы представили основные условия, которые мы можем применить к данному полю для выбора объектов из базы данных back4app с использованием parseswift sdk parseswift sdk в этом разделе мы продолжаем с составлением запросов и расширенными запросами exists //it is used to select objects depending on the value of a given field not being nil 1 let constraint queryconstraint = exists(key "membership") 2 // exists(key ) is a method provided by the parseswift sdk 3 4 let query = profile query(constraint) // will retrieve all profiles which have a membership 5 6 let profiles = try? query find() // executes the query synchronously 7 8 query find { result in // executes the query asynchronously 9 // handle the result (of type result<\[profile], parseerror>) 10 } does not exists //it is used to select objects depending on the value of a given field being nil 1 let constraint queryconstraint = doesnotexist(key "membership") 2 // doesnotexist(key ) is a method provided by the parseswift sdk 3 4 let query = profile query(constraint) // will retrieve all profiles which do not have a membership 5 6 let profiles = try? query find() // executes the query synchronously 7 8 query find { result in // executes the query asynchronously 9 // handle the result (of type result<\[profile], parseerror>) 10 } matches key in query //when we need to retrieve objects using the result from a different query as a condition, we make use of the method doesnotmatchkeyinquery(key\ querykey\ query ) to construct the corresponding condition to illustrate this in more detail, we first introduce a new object friend which has a property numberofcontacts of type int 1 struct friend parseswift { 2 3 var numberofcontacts int? 4 5 } does not match key in query //this case is the opposite of matches key in query it is useful when we want to select all the profile objects where their numberoffriends field does not match with the numberofcontacts field in all friend objects the method we use to compose this query is doesnotmatchkeyinquery(key\ querykey\ query ) 1 let friendquery = friend query() // selects all friends objects 2 3 let constraint queryconstraint = doesnotmatchkeyinquery( 4 key "numberoffriends", 5 querykey "numberofcontacts", 6 query friendquery 7 ) 8 // doesnotmatchkeyinquery(key\ querykey\ query ) is a method provided by the parseswift sdk 9 10 let query = profile query(constraint) 11 12 let profiles = try? query find() // executes the query synchronously 13 14 query find { result in // executes the query asynchronously 15 // handle the result (of type result<\[profile], parseerror>) 16 } порядок запросов сортировка результатов запроса является ключевой перед началом отображения или манипуляции этими результатами parseswift sdk parseswift sdk предоставляет следующие варианты для достижения этого ascending //sort the results in ascending order, overwrites previous orderings multiple fields can be used to solve ordering ties by calling the order( ) method on a query\<profile> object, we obtain a new query which implements the given order option the argument for the order( ) method is an array of query\<profile> order items these enumerations contain the name of the field to be used for the sort algorithm for ascending order we use query\<profile> order ascending("nameofthefield") 1 let query = profile query() order(\[ ascending("numberoffriends")]) 2 3 let profiles = try? query find() // executes the query synchronously 4 5 query find { result in // executes the query asynchronously 6 // handle the result (of type result<\[profile], parseerror>) 7 } descending //similar to the ascending order, the only diference is that instead of using query\<profile> order ascending("nameofthefield") we should use query\<profile> order descending("nameofthefield") 1 let query = profile query() order(\[ descending("numberoffriends")]) 2 3 let profiles = try? query find() // executes the query synchronously 4 5 query find { result in // executes the query asynchronously 6 // handle the result (of type result<\[profile], parseerror>) 7 } text score //this kind of sorting procedure relies on a score metric in order to use this option, the profile object must conform to the parsequeryscorable protocol once the protocol is implemented, we call the sortbytextscore() method on the query\<profile> object to obtain a new one that implements the required sorting method 1 extension profile parsequeryscorable { 2 var score double? { 3 // add the corresponding implementation 4 } 5 } 6 7 let query = profile query() sortbytextscore() 8 9 let profiles = try? query find() // executes the query synchronously 10 11 query find { result in // executes the query asynchronously 12 // handle the result (of type result<\[profile], parseerror>) 13 } выбор поля в зависимости от того, какие данные требуются во время запроса, это может занять больше или меньше времени в некоторых сценариях может быть достаточно извлечь определенные поля из объекта и игнорировать ненужные поля более того, выбирая только те поля, которые нам нужны из запроса, мы избегаем избыточного извлечения и улучшаем производительность процесса извлечения exclude //calling the exclude( ) method on a query returns a new query that will exclude the fields passed (in variadic format) as the argument 1 let query = profile query() exclude("name", "numberoffriends") 2 3 let profiles = try? query find() // executes the query synchronously 4 5 query find { result in // executes the query asynchronously 6 // handle the result (of type result<\[profile], parseerror>) 7 } include //it is used to retrieve the fields whose data type conforms to the parseobject protocol (i e , objects stored in the same database under its corresponding class name) calling the include( ) method on a query returns a new query that will include the fields passed (in variadic format) as the argument for instance, the membership field in profile will not be fetched unless we include it manually 1 let query = profile query() include("membership") 2 3 let profiles = try? query find() // executes the query synchronously 4 5 query find { result in // executes the query asynchronously 6 // handle the result (of type result<\[profile], parseerror>) 7 } include all //when we need to retrieve the fields that conforms to the parseobject we call the includeall() method on the query 1 let query = profile query() includeall() 2 3 let profiles = try? query find() // executes the query synchronously 4 5 query find { result in // executes the query asynchronously 6 // handle the result (of type result<\[profile], parseerror>) 7 } select //it returns only the specified fields in the returned objects calling the select( ) method on a query returns a new query which will select only the fields passed (in variadic format) as argument 1 let query = profile query() select("name", "birthday") 2 3 let profiles = try? query find() // executes the query synchronously 4 5 query find { result in // executes the query asynchronously 6 // handle the result (of type result<\[profile], parseerror>) 7 } пагинация в больших базах данных пагинация является основным элементом для запроса и обработки большого объема результатов parseswift sdk parseswift sdk предоставляет следующие методы для управления этими ситуациями limit //determines the maximum number of results a query is able to return, the default value is 100 we call the limit( ) method on the query in question to change this value 1 let query = profile query() limit(2) 2 3 let profiles = try? query find() // executes the query synchronously 4 5 query find { result in // executes the query asynchronously 6 // handle the result (of type result<\[profile], parseerror>) 7 } skip //together with the previous option, the skip option allows us to paginate the results we call the skip( ) method on the query in question to change this value 1 let query = profile query() skip(2) 2 3 let profiles = try? query find() // executes the query synchronously 4 5 query find { result in // executes the query asynchronously 6 // handle the result (of type result<\[profile], parseerror>) 7 } with count //when we need to know in advance the number of results retrieved from a query, we use the withcount(completion ) method instead of the usual find( ) in this way, the result is composed by the objects found together with an integer indicating the length of the array 1 let query = profile query() 2 3 query withcount { result in // executes the query asynchronously 4 // handle the result (of type result<(\[profile], int), parseerror>) 5 } составные запросы эти методы создадут составные запросы, которые могут объединять более чем один query\<profile> query\<profile> экземпляр для достижения более сложных результатов and //compose a compound query that is the and of the passed queries this is accomplished by first instantiating the queries to be used for the and operation the and(queries ) method provided by the parseswift sdk allows us to perform the and operation and embed the result in a queryconstraint object this constraint is then used to instantiate the final query to be used for retrieveing the results 1 let query1 = profile query("numberoffriends" > 10) 2 let query2 = profile query("numberoffriends" < 50) 3 4 let query = profile query(and(queries query1, query2)) 5 // and(queries ) is a method provided by the parseswift sdk it takes an array of queries and applies the and op on them 6 7 let profiles = try? query find() // executes the query synchronously 8 9 query find { result in // executes the query asynchronously 10 // handle the result (of type result<\[profile], parseerror>) 11 } nor //in this case, we apply a nor operation on a set of queries we use the nor(queries ) method provided by the parseswift sdk to perform such operation we handle the result in a similar way as the and operation 1 let query1 = profile query("numberoffriends" > 10) 2 let query2 = profile query("numberoffriends" < 50) 3 4 let query = profile query(nor(queries query1, query2)) 5 6 let profiles = try? query find() // executes the query synchronously 7 8 query find { result in // executes the query asynchronously 9 // handle the result (of type result<\[profile], parseerror>) 10 } or //similar to previous cases, we apply an or operation on a set of queries we use the or(queries ) method provided by the parseswift sdk to perform such operation we handle the result in a similar way as the and (or nor) operation 1 let query1 = profile query("numberoffriends" > 10) 2 let query2 = profile query("numberoffriends" < 50) 3 4 let query = profile query(or(queries query1, query2)) 5 6 let profiles = try? query find() // executes the query synchronously 7 8 query find { result in // executes the query asynchronously 9 // handle the result (of type result<\[profile], parseerror>) 10 } связанные с базой данных эти методы связаны с предпочтениями и операциями базы данных aggregate //executes an aggregate query, retrieving objects over a set of input values to use this feature, instead of executing the query with find( ), we call the aggregate( completion ) the first argument of this function is a dictionary containing the information about the pipeline for more details, refer to mongodb documentation on aggregate 1 let query = profile query() 2 3 query aggregate(\[\["pipeline" 5]]) { result in 4 // handle the result (of type result<\[profile], parseerror>) 5 } explain //investigates the query execution plan, related to mongodb explain operation this option requires a new object (conforming to the decodable protocol) to handle the results 1 struct anycodable decodable { 2 // implement the corresponding properties 3} 4 5let query = profile query() 6 7let results = try? query findexplain() // executes the option synchronously 8 9// instantiate the completion block explicitely in order for the method findexplain(completion ) to infer the type of the returning results 10 let completion (result<\[anycodable], parseerror>) > void = { result in 11 // handle the result 12 } 13 14 // executes the option asynchronously 15 query findexplain(completion completion) readpreference //when using a mongodb replica set, use this method to choose from which replica the objects will be retrieved the possible values are primary (default), primary preferred, secondary, secondary preferred, or nearest 1 let query = profile query() readpreference("nearest") 2 3 let profiles = try? query find() // executes the query synchronously 4 5 query find { result in // executes the query asynchronously 6 // handle the result (of type result<\[profile], parseerror>) 7 } заключение используя различные методы, объекты и операторы, предоставленные parseswift sdk parseswift sdk , мы смогли понять, как конструировать и извлекать объекты из back4app базы данных с помощью этой кулинарной книги вы сможете выполнять запросы с очень гибкими ограничениями и управлять результатами в соответствии с вашим случаем использования для получения более подробной информации по любым из вышеупомянутых тем вы можете обратиться к репозиторию parseswift https //github com/parse community/parse swift