Api reference icon

Add objects

Add objects

Description Add new objects (records) to an index.
PHP Ruby JS Python iOS Android C# Java Go Scala name addObjects() add_objects() addObjects() add_objects() addObjects() addObjectsAsync() AddObjects() addObjects() AddObjects() index into()
Required ACL

addObject

More details

There are two ways to add a record to an index:

  1. Supplying an objectID:
    • If the objectID does not exist in the index, the record will be created.
    • If the objectID already exists, the record will be replaced. This is the main difference with Update Objects, which would throw an error instead.
  2. Not supplying an objectID:
    • Algolia will automatically assign an objectID, that you will be able to access in the response.

In both cases, once a record is added, it will have a unique identifier called objectID. This ID can be used later by methods like Update Objects or Partial Updates.

Read more on the differences between these methods.

Using your own unique IDs when creating records is a good way to make future updates easier without having to keep track of Algolia’s generated IDs. The value you provide for objectIDs can be an integer or a string.

Examples

Add objects with automatic objectID assignments

<?php
$res = $index->addObjects(
    [
        [
            'firstname' => 'Jimmie',
            'lastname'  => 'Barninger'
        ],
        [
            'firstname' => 'Warren',
            'lastname'  => 'Speach'
        ]
    ]
);
res = index.add_objects([{"firstname" => "Jimmie",
                          "lastname" => "Barninger"},
                         {"firstname" => "Warren",
                          "lastname" => "Speach"}])
var objects = [{
  firstname: 'Jimmie',
  lastname: 'Barninger'
}, {
  firstname: 'Warren',
  lastname: 'Speach'
}];

index.addObjects(objects, function(err, content) {
  console.log(content);
});
res = index.add_objects([{"firstname": "Jimmie",
                         "lastname": "Barninger"},
                        {"firstname": "Warren",
                         "lastname": "Speach"}])
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!)")
    }
})
List<JSONObject> array = new ArrayList<JSONObject>();
array.add(new JSONObject().put("firstname", "Jimmie").put("lastname", "Barninger"));
array.add(new JSONObject().put("firstname", "Warren").put("lastname", "Speach"));
index.addObjectsAsync(new JSONArray(array), null);
List<JObject> objs = new List<JObject>();
objs.Add(JObject.Parse(@"{""firstname"":""Jimmie"",
                          ""lastname"":""Barninger""}"));
objs.Add(JObject.Parse(@"{""firstname"":""Warren"",
                          ""lastname"":""Speach""}"));
var res = index.AddObjects(objs);
// Asynchronous
// var res = await index.AddObjectsAsync(objs);
System.Diagnostics.Debug.WriteLine(res);
//Sync & Async version

index.addObjects(Arrays.asList(
  new Contact().setFirstName("Jimmie").setLastName("Barninger"),
  new Contact().setFirstName("Warren").setLastName("Speach")
));
objects := []algoliasearch.Object{
  {"firstname": "Jimmie", "lastname": "Barninger"},
  {"firstname": "Ray", "lastname": "Charles"},
}

res, err := index.AddObjects(objects)
client.execute {
  batch(
    index into "index1" `object` Contact("Jimmie", "Barninger"),
    index into "index1" `object` Contact("Warren", "Speach")
  )
}

//or

client.execute {
  index into "index1" objects Seq(Contact("Jimmie", "Barninger"), Contact("Warren", "Speach"))
}

//or

client.execute {
  batch(
    index into "test1" objects Seq(Contact("Jimmie", "Barninger"), Contact("Warren", "Speach"))
  )
}

Add objects with manual objectID assignments

<?php
$index->addObjects(
    [
        [
            'objectID' => 'myID1',
            'firstname' => 'Jimmie',
            'lastname'  => 'Barninger'
        ],
        [
            'objectID' => 'myID2',
            'firstname' => 'Warren',
            'lastname'  => 'Speach'
        ]
    ]
);
res = index.add_objects([{"objectID" => "myID1",
                          "firstname" => "Jimmie",
                          "lastname" => "Barninger"},
                         {"objectID" => "myID2",
                          "firstname" => "Warren",
                          "lastname" => "Speach"}])
var objects = [{
  objectID: 'myID1',
  firstname: 'Jimmie',
  lastname: 'Barninger'
}, {
  objectID: 'myID2',
  firstname: 'Warren',
  lastname: 'Speach'
}];

index.addObjects(objects, function(err, content) {
  console.log(content);
});
res = index.add_objects([{"objectID": "myID1",
                         "firstname": "Jimmie",
                         "lastname": "Barninger"},
                        {"objectID": "myID2",
                         "firstname": "Warren",
                         "lastname": "Speach"}])
let obj1 = ["objectID": "myID1", "firstname": "Jimmie", "lastname": "Barninger"]
let obj2 = ["objectID": "myID2", "firstname": "Warren", "lastname": "Speach"]
index.addObjects([obj1, obj2], completionHandler: { (content, error) -> Void in
  if error == nil {
      print("Object IDs: \(content!)")
  }
})
List<JSONObject> array = new ArrayList<JSONObject>();
array.add(new JSONObject().put("objectID", "myID1").put("firstname", "Jimmie").put("lastname", "Barninger"));
array.add(new JSONObject().put("objectID", "myID2").put("firstname", "Warren").put("lastname", "Speach"));
index.addObjectsAsync(new JSONArray(array), null);
List<JObject> objs = new List<JObject>();
objs.Add(JObject.Parse(@"{""objectID"":""myID1"",
                          ""firstname"":""Jimmie"",
                          ""lastname"":""Barninger""}"));
objs.Add(JObject.Parse(@"{""objectID"":""myID2"",
                          ""firstname"":""Warren"",
                          ""lastname"":""Speach""}"));
var res = index.AddObjects(objs);
// Asynchronous
// var res = await index.AddObjectsAsync(objs);
System.Diagnostics.Debug.WriteLine(res);
//Sync & Async version

index.addObjects(Arrays.asList(
  new Contact().setObjectID("myID1").setFirstName("Jimmie").setLastName("Barninger"),
  new Contact().setObjectID("myID2").setFirstName("Warren").setLastName("Speach")
));
objects := []algoliasearch.Object{
  {"objectID": "myID1", "firstname": "Jimmie", "lastname": "Barninger"},
  {"objectID": "myID2", "firstname": "Ray", "lastname": "Charles"},
}

res, err := index.AddObjects(objects)
client.execute {
  batch(
    index into "index1" `object` Contact("myID", "Jimmie", "Barninger"),
    index into "index1" `object` Contact("myID2", "Warren", "Speach")
  )
}

//or

client.execute {
  index into "index1" objects Seq(Contact("myID1", "Jimmie", "Barninger"), Contact("myID2", "Warren", "Speach"))
}

//or

client.execute {
  batch(
    index into "test1" objects Seq(Contact("myID1", "Jimmie", "Barninger"), Contact("myID2", "Warren", "Speach"))
  )
}

Add a single object

<?php
$index->addObject(
  [
    'objectID' => 'myID',
    'firstname' => 'Jimmie',
    'lastname'  => 'Barninger'
  ]
);
res = index.add_object({"firstname" => "Jimmie",
                        "lastname" => "Barninger"}, "myID")
puts "ObjectID=" + res["objectID"]
index.addObject({
  objectID: 'myId',
  firstname: 'Jimmie',
  lastname: 'Barninger'
}, function(err, content) {
  console.log('objectID=' + content.objectID);
});
res = index.add_object({"firstname": "Jimmie",
                       "lastname": "Barninger"}, "myID")
print "ObjectID=%s" % res["objectID"]
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)")
      }
  }
})
JSONObject object = new JSONObject()
    .put("firstname", "Jimmie")
    .put("lastname", "Barninger");
index.addObjectAsync(object, "myID", null);
var res = index.AddObject(JObject.Parse(@"{""firstname"":""Jimmie"",
                                           ""lastname"":""Barninger""}"), "myID");
// Asynchronous
// var res = await index.AddObjectAsync(JObject.Parse(@"{""firstname"":""Jimmie"",
//                                                       ""lastname"":""Barninger""}"), "myID");
System.Diagnostics.Debug.WriteLine("objectID=" + res["objectID"]);
//Sync version
TaskSingleIndex task = index.addObject(new Contact()
      .setFirstName("Jimmie"),
      .setLastname("Barninger")
      .setObjectID("objectID"));

String objectID = task.getObjectID("objectID"));
//Async version
CompletableFuture<AsyncTaskSingleIndex> task = index.addObject(new Contact()
      .setFirstName("Jimmie"),
      .setLastname("Barninger")
      .setObjectID("objectID"));

String objectID = task.get().getObjectID("objectID"));
object := algoliasearch.Object{
  "objectID":  "myID",
  "firstname": "Jimmie",
  "lastname":  "Barninger",
}
res, err := index.AddObject(object)
val indexing: Future[Indexing] = client.execute {
    index into "contacts" objectId "myID" `object` Contact("Jimmie", "Barninger", 93, "California Paint")
}

indexing onComplete {
    case Success(indexing) => println(indexing.objectID)
    case Failure(e) =>  println("An error has occured: " + e.getMessage)
}

Add objects and send extra http headers

<?php
$extraHeaders = [
  'X-FORWARDED-FOR' => '94.228.178.246'
];

$objects = [/* objects */];
$res = $index->addObjects($objects, 'objectID', $extraHeaders);
objects = []

extra_headers = {
  'X-FORWARDED-FOR': '94.228.178.246'
}

res = index.add_objects(objects, extra_headers)
client.setExtraHeader('X-FORWARDED-FOR', '94.228.178.246');
index.addObject({
  objectID: 'myId',
  firstname: 'Jimmie',
  lastname: 'Barninger'
}, function(err, content) {
  console.log('objectID=' + content.objectID);
});
request_options = RequestOptions({'algoliaUserID': 'user123'})
res = index.add_object({"firstname": "Jimmie", "lastname": "Barninger"}, "myID", request_options=request_options)
let newObject = ["firstname": "Jimmie", "lastname": "Barninger"]
let requestOptions = RequestOptions()
requestOptions.headers["X-Algolia-User-ID"] = "user123"

index.addObject(newObject, withID: "myID", requestOptions: requestOptions, completionHandler: { (content, error) -> Void in
  if error == nil {
      if let objectID = content!["objectID"] as? String {
          print("Object ID: \(objectID)")
      }
  }
})
List<JSONObject> array = new ArrayList<JSONObject>();
array.add(new JSONObject().put("firstname", "Jimmie").put("lastname", "Barninger"));
array.add(new JSONObject().put("firstname", "Warren").put("lastname", "Speach"));
index.addObjectsAsync(new JSONArray(array), new RequestOptions().setHeader("X-Algolia-User-ID", "94.228.178.246"), null);
RequestOptions requestOptions = new RequestOptions();
requestOptions.AddExtraHeader("X-Algolia-User-ID", "user123");
var res = index.AddObject(JObject.Parse(@"{""firstname"":""Jimmie"",
                                           ""lastname"":""Barninger""}"), "myID", requestOptions);
// Asynchronous
// var res = await index.AddObjectAsync(JObject.Parse(@"{""firstname"":""Jimmie"",
//                                                       ""lastname"":""Barninger""}"), "myID", requestOptions);
System.Diagnostics.Debug.WriteLine("objectID=" + res["objectID"]);
//Sync version
TaskSingleIndex task = index.addObject(new Contact()
      .setFirstName("Jimmie"),
      .setLastname("Barninger")
      .setObjectID("objectID"), new RequestOptions().setExtraHeader("X-Algolia-User-ID", "user123"));

String objectID = task.getObjectID("objectID"));
//Async version
CompletableFuture<AsyncTaskSingleIndex> task = index.addObject(new Contact()
      .setFirstName("Jimmie"),
      .setLastname("Barninger")
      .setObjectID("objectID"), new RequestOptions().setExtraHeader("X-Algolia-User-ID", "user123"));

String objectID = task.get().getObjectID("objectID"));
objects := []algoliasearch.Object{
  {"firstname": "Jimmie", "lastname": "Barninger"},
  {"firstname": "Ray", "lastname": "Charles"},
}

client.SetExtraHeader("X-Forwarded-For", "94.228.178.246")
res, err := index.AddObjects(objects)
val indexing: Future[Indexing] = client.execute {
    index into "contacts" objectId "myID" `object` Contact("Jimmie", "Barninger", 93, "California Paint") options RequestOptions(extraHeaders = Some(Map("X-Algolia-User-ID" => "user123")))
}

indexing onComplete {
    case Success(indexing) => println(indexing.objectID)
    case Failure(e) =>  println("An error has occured: " + e.getMessage)
}