0

Are there any generic implementations out-there which can transform a Scala case class to SolrDocument ?

Since I could not find any such mapper utility that I can reuse, I took the below approach:

  1. Create the case class object
  2. Get non-empty fields by transforming case class object to Map
  3. Add fields to the mutable document one-by-one.

This approach works for me, but I would have to create the intermediate Map object. I want to avoid this for verbosity and complexity reasons. Is there a better way of doing it?

Sudheer Aedama
  • 2,116
  • 2
  • 21
  • 39
  • The answer to this question has a nice little case class to map function that you could modify to return a `SolrDocument` http://stackoverflow.com/a/1227643/47496 – Noah Oct 22 '14 at 19:59
  • @Noah Thanks, I am aware of it. As you can see that answer also involves creating the Map, a Map[String, Any] => one of the biggest anti-patterns which I do not want to pollute my code-base with. As I had mentioned I wanted to know if there are any better utilities which do not involve in the construction of this intermediate Map object. – Sudheer Aedama Oct 22 '14 at 20:02

2 Answers2

0

Not a complete answer (I would write this in a comment, but need a few more rep), but just you point you in a direction, macros are the way to do this in a type-safe way without writing boiler plate mapping functions for every case class. JSON libraries deal with the same problem (except replace SolrDocument with JSON object). As an example you can take a look at the JSON serializer/deserializer macro implementation from Play Framework:

https://github.com/playframework/playframework/blob/master/framework/src/play-json/src/main/scala/play/api/libs/json/JsMacroImpl.scala

I suspect this solution is a little more heavy than you were looking for. The way I would approach it is to write the stupid boilerplate mapping functions for each case class, and only go down the macro path if this becomes a significant burden.

lea
  • 408
  • 3
  • 7
0

Seems fairly trivial to modify one of these answers:

  def getSolrDoc(cc: Product): SolrDocument = {
    val solrDoc = new SolrDocument
    cc.getClass.getDeclaredFields.foreach { f =>
      f.setAccessible(true)
      solrDoc.addField(f.getName, f.get(cc))
    }
    solrDoc
  }

And usage:

  case class X(a:Int, b:String)
  val x = X(1, "Test")
  val doc = getSolrDoc(x)
  println(doc) // prints SolrDocument{a=1, b=Test}
Community
  • 1
  • 1
Noah
  • 13,821
  • 4
  • 36
  • 45