Search code examples
scalaelasticsearchsprayelastic4s

Exception when using elastic4s with elastic-search and spray-routing


I'm trying to write a little REST api using Scala, Spray.io, Elastic4s and ElasticSearch. My ES instance is running with default parameters, I just changed the parameter network.host to 127.0.0.1.

Here is my spray routing definition

package com.example

import akka.actor.Actor
import spray.routing._
import com.example.core.control.CrudController

class ServiceActor extends Actor with Service {

  def actorRefFactory = context

  def receive = runRoute(routes)
}

trait Service extends HttpService {

  val crudController = new CrudController()

  val routes = {

      path("ads" / IntNumber) {
      id =>
          get {
              ctx =>
                  ctx.complete(
                    crudController.getFromElasticSearch
                  )
          }
      }
  }
}

My crudController :

package com.example.core.control
import com.example._
import org.elasticsearch.action.search.SearchResponse
import scala.concurrent._
import scala.util.{Success, Failure}
import ExecutionContext.Implicits.global

class CrudController extends elastic4s
{

    def getFromElasticSearch : String = {
    val something: Future[SearchResponse] = get
    something onComplete {
        case Success(p) => println(p)
        case Failure(t) => println("An error has occured: " + t)
    }
    "GET received \n"
    }
}

And a trait elastic4s who is encapsulating the call to elastic4s

package com.example

import com.sksamuel.elastic4s.ElasticClient
import com.sksamuel.elastic4s.ElasticDsl._
import scala.concurrent._
import org.elasticsearch.action.search.SearchResponse

trait elastic4s {

    def get: Future[SearchResponse] = {
    val client = ElasticClient.remote("127.0.0.1", 9300)
    client execute { search in "ads"->"categories" }
    }
}

This code runs well, and gives me this output :

[INFO] [03/26/2014 11:41:50.957] [on-spray-can-akka.actor.default-dispatcher-4] [akka://on-spray-can/user/IO-HTTP/listener-0] Bound to localhost/127.0.0.1:8080

But when a try to access to the route "localhost/ads/8" with my browser, the case Failure is always triggered and I got this error output on my intellij console :

An error has occured: org.elasticsearch.transport.RemoteTransportException: [Skinhead][inet[/127.0.0.1:9300]][search]

(No console output with elasticSearch running on my terminal)

Is this exception related to ElasticSearch, or am I doing wrong with my Future declaration ?


Solution

  • I suppose you should use ElasticClient.local in this case, as specified in elastic4s docs:

    https://github.com/sksamuel/elastic4s

    To specify settings for the local node you can pass in a settings object like this:
    
    val settings = ImmutableSettings.settingsBuilder()
          .put("http.enabled", false)
          .put("path.home", "/var/elastic/") 
    val client = ElasticClient.local(settings.build)