1

I'm trying simply to save entity into solr using spring data and get its autogenerated id. I see that id is generated but it was not returned back to me. Code is trivial

entity:

@SolrDocument(solrCoreName = "bank")
@Canonical
class Shop {
    @Id
    @Field
    String id
    @Field
    String name
}

repository:

@Repository
interface ShopRepository extends SolrCrudRepository<Shop, String>{
}

handler:

  @Autowired
    ShopRepository repository

    void save() {
        Shop shop = new Shop()
        shop.name = 'shop1'
        log.info("before {}", shop)
        Shop savedShop = repository.save(shop)
        log.info("after {}", savedShop)
    }

dependencies:

dependencies {
    compile lib.groovy_all
    compile 'org.springframework.boot:spring-boot-starter-data-solr:1.5.10.RELEASE'
}

and result is:

before com.entity.Shop(null, shop1)
after com.entity.Shop(null, shop1)

however via solr's admin console I see generated id:

{   "responseHeader":{
    "status":0,
    "QTime":0,
    "params":{
      "q":"*:*",
      "_":"1527472154657"}},   "response":{"numFound":3,"start":0,"docs":[
      {
        "name":["shop1"],
        "id":"4db1eb1d-718b-4a38-b960-6d52f9b6240c",
        "_version_":1601670593291223040,
        "name_str":["shop1"]},
      {
        "name":["shop1"],
        "id":"6ad52214-0f23-498d-82b8-82f360ef22f1",
        "_version_":1601670855078707200,
        "name_str":["shop1"]},
      {
        "name":["shop1"],
        "id":"b45b5773-f2b9-4474-b177-92c98810978b",
        "_version_":1601670887722975232,
        "name_str":["shop1"]}]   }}

and repository.findAll() also returns correct result with mapped id. Is it a feature or bug?

yassine yousfi
  • 79
  • 2
  • 11
Dmitrii Borovoi
  • 2,814
  • 9
  • 32
  • 50

1 Answers1

0

The flow is working as expected (no ID available in the returned object):

During the Save operation

  • Original object is converted in something can be digested by Solr (id is null)
  • The update request (with the object with null id) is sent to Solr
  • Solr process the "create" and generate (internally) the ID
  • Solr response is OK/KO (with few other data...but no ID here)

So...the final object is exactly the same of the original object (id null).

A quick "workaround" can be implemented as:

@Repository
public interface PlaceRepo extends SolrCrudRepository<PlaceModel, String> {

    default PlaceModel create(PlaceModel model, Duration commit) {
        model.setId(IDGenerator.generateID());
        return this.save(model, commit);
    }

    default PlaceModel create(PlaceModel model) {
        return this.create(model, Duration.ZERO);
    }

}

You are moving the ID generation logic to the Java layer. The Id can be generated as

public static String generateID() {
        return UUID.randomUUID().toString();
    }
ninja
  • 337
  • 3
  • 2