K P
K P

Reputation: 851

How to get json string for a searchHit?

Everytime I try to do searchHit.sourceAsString() or searchHit.getSourceAsString(), I get null back. But if I try searchHit.getFields() -> it will give me a Map[String, SearchHitField] and then I can get necessary fields back from it - which I don't want to do. That is because I want to use Lift-json library to parse "if obtained" json string from searchHit in my case class. Any ideas?

Upvotes: 1

Views: 1856

Answers (2)

knutwalker
knutwalker

Reputation: 5974

searchHit.sourceAsString() will return null if you do not ask for the field _source.

This happens, if you have it disabled in your mapping (in which case you have to enable it), or if you specify other fields to return.

In particular, you have to pass _source to the list of fields in your SearchRequestBuilder. The default fields list is [_source], so if you do not specify any other fields, you will get your _source back, but if you specify other fields, you have to add _source as well.

Upvotes: 4

Sudheer Aedama
Sudheer Aedama

Reputation: 2144

Wrap the elastic search call searchHit.sourceAsString() in scala.Option something like: Option(searchHit.sourceAsString()). You can compose on this or do pattern matching as you wish.

Essentially, when you wrap a null in an Option it gives you scala.None type back. You can try it your REPL session.

If you want to compose, you can do this:

val jvalOpt: Option[net.liftweb.json.JValue] = Option(searchHit.sourceAsString()).map(net.liftweb.json.parse(_))

or if you want to pattern match then you can do this:

val jval = Option(searchHit.sourceAsString()) match {
  case None => // todo
  case Some(s) => net.liftweb.json.parse(s)
}

Upvotes: 0

Related Questions