Home > other >  Spring & elasticsearch - Upsert a list of documents by specific field other than id
Spring & elasticsearch - Upsert a list of documents by specific field other than id

Time:10-13

currently we are currently upserting a document based on the given id. However, we have recent changes that id will be autogenerated and we created a new field "main_id" that will serve as the primary id. How can we use upsert by "main_id" and not by id? Here's the sample entity:

@Data
@Document(indexName = "person")
public class Person {

  @Id
  @JsonIgnore
  private String id;

   private String mainId;

  private String name;
}

Currently, here's our implementation of the method:

 public void bulkCreateOrUpdate(final List<T> objectList) {

    List<UpdateQuery> updateList = new ArrayList<>();

    for (T st: objectList) {
      UpdateQuery updateQuery = UpdateQuery.builder(st.getId())
          .withDocument(this.operations.getElasticsearchConverter().mapObject(st))
          .withDocAsUpsert(true)
          .build();
      updateList.add(updateQuery);
    }

    this.operations.bulkUpdate(updateList,
        this.operations.getIndexCoordinatesFor(this.entityClass));
  }

CodePudding user response:

Do this:

public void bulkCreateOrUpdate(final List objectList) {

List<UpdateQuery> updateList = new ArrayList<>();

for (T st: objectList) {
  UpdateQuery updateQuery = UpdateQuery.builder(st.getMainId())
      .withDocument(this.operations.getElasticsearchConverter().mapObject(st))
      .withDocAsUpsert(true)
      .build();
  updateList.add(updateQuery);
}

this.operations.bulkUpdate(updateList,
    this.operations.getIndexCoordinatesFor(this.entityClass));

}

CodePudding user response:

The update API of Elasticsearch requires the document's id.

There is also the update by query, this is available in Spring Data Elasticsearch as well, but there you cannot pass in a new or updated document, but only a script to do the update.

So there is no way to do the update directly without using the id.

  • Related