Swift

Indexing

Add Objects - addObjects

Each entry in an index has a unique identifier called objectID. There are two ways to add an entry to the index:

  1. Supplying your own objectID.
  2. Using automatic objectID assignment. You will be able to access it in the answer.

You don’t need to explicitly create an index, it will be automatically created the first time you add an object. Objects are schema less so you don’t need any configuration to start indexing. If you wish to configure things, the settings section provides details about advanced settings.

Example with automatic objectID assignments:

let obj1 = ["firstname": "Jimmie", "lastname": "Barninger"]
let obj2 = ["firstname": "Warren", "lastname": "Speach"]
index.addObjects([obj1, obj2], completionHandler: { (content, error) -> Void in
    if error == nil {
        print("Object IDs: \(content!)")
    }
})

Example with manual objectID assignments:

let obj1 = ["objectID": "1", firstname": "Jimmie", "lastname": "Barninger"]
let obj2 = ["objectID": "2", "firstname": "Warren", "lastname": "Speach"]
index.addObjects([obj1, obj2], completionHandler: { (content, error) -> Void in
  if error == nil {
      print("Object IDs: \(content!)")
  }
})

To add a single object, use the Add Objects method:

let newObject = ["firstname": "Jimmie", "lastname": "Barninger"]
index.addObject(newObject, withID: "myID", completionHandler: { (content, error) -> Void in
  if error == nil {
      if let objectID = content!["objectID"] as? String {
          print("Object ID: \(objectID)")
      }
  }
})

Update objects - saveObjects

You have three options when updating an existing object:

  1. Replace all its attributes.
  2. Replace only some attributes.
  3. Apply an operation to some attributes.

Example on how to replace all attributes existing objects:

let obj1 = ["firstname": "Jimmie", "lastname": "Barninger", "objectID": "myID1"]
let obj2 = ["firstname": "Warren", "lastname": "Speach", "objectID": "myID2"]
index.saveObjects([obj1, obj2], completionHandler: { (content, error) -> Void in
  if error == nil {
      print("Object IDs: \(content!)")
  }
})

To update a single object, you can use the following method:

let newObject = [
  "firstname": "Jimmie",
  "lastname": "Barninger",
  "city": "New York",
  "objectID": "myID"
]
index.saveObject(newObject)

Partial update objects - partialUpdateObjects

You have many ways to update an object’s attributes:

  1. Set the attribute value
  2. Add a string or number element to an array
  3. Remove an element from an array
  4. Add a string or number element to an array if it doesn’t exist
  5. Increment an attribute
  6. Decrement an attribute

Example to update only the city attribute of an existing object:

let partialObject = ["city": "San Francisco"]
index.partialUpdateObject(partialObject, withID: "myID")

Example to add a tag:

let operation = [
  "value": "MyTag",
  "_operation": "Add"
]
let partialObject = ["_tags": operation]
index.partialUpdateObject(partialObject, withID: "myID")

Example to remove a tag:

let operation = [
  "value": "MyTag",
  "_operation": "Remove"
]
let partialObject = ["_tags": operation]
index.partialUpdateObject(partialObject, withID: "myID")

Example to add a tag if it doesn’t exist:

let operation = [
  "value": "MyTag",
  "_operation": "AddUnique"
]
let partialObject = ["_tags": operation]
index.partialUpdateObject(partialObject, withID: "myID")

Example to increment a numeric value:

let operation = [
  "value": 42,
  "_operation": "Increment"
]
let partialObject = ["price": operation]
index.partialUpdateObject(partialObject, withID: "myID")

Note: Here we are incrementing the value by 42. To increment just by one, put value:1.

Example to decrement a numeric value:

let operation = [
  "value": 42,
  "_operation": "Decrement"
]
let partialObject = ["price": operation]
index.partialUpdateObject(partialObject, withID: "myID")

Note: Here we are decrementing the value by 42. To decrement just by one, put value:1.

To partial update multiple objects using one API call, you can use the [Partial update objects](/doc/api-client/swift/indexing/#partial-update-objects) method:

let obj1 = ["firstname": "Jimmie", "objectID": "myID1"]
let obj2 = ["firstname": "Warren", "objectID": "myID2"]
index.partialUpdateObjects([obj1, obj2], completionHandler: { (content, error) -> Void in
  if error == nil {
      print("Object IDs: \(content!)")
  }
})

Delete objects - deleteObjects

You can delete objects using their objectID:

index.deleteObjects(withIDs: ["myID1", "myID2"])

To delete a single object, you can use the [Delete objects](/doc/api-client/swift/indexing/#delete-objects) method:

index.deleteObject(withID: "myID")

Delete by query - deleteByQuery

You can delete all objects matching a single query with the following code. Internally, the API client performs the query, deletes all matching hits, and waits until the deletions have been applied.

Take your precautions when using this method. Calling it with an empty query will result in cleaning the index of all its records.

let query: Query = /* [...] */
index.deleteByQuery(query, completionHandler: { (content, error) -> Void in
    if error != nil {
        print("Error deleting objects")
    }
})

Wait for operations - waitTask

All write operations in Algolia are asynchronous by design.

It means that when you add or update an object to your index, our servers will reply to your request with a taskID as soon as they understood the write operation.

The actual insert and indexing will be done after replying to your code.

You can wait for a task to complete using the waitTask method on the taskID returned by a write operation.

For example, to wait for indexing of a new object:

index.addObject(newObject, completionHandler: { (content, error) -> Void in
    if error != nil {
        return
    }
    guard let taskID = content!["taskID"] as? Int else {
        return // could not retrieve task ID
    }
    self.index.waitTask(withID: taskID, completionHandler: { (content, error) -> Void in
        if error == nil {
            print("New object is indexed!")
        }
    })
})

If you want to ensure multiple objects have been indexed, you only need to check the biggest taskID.