Querying an Elasticsearch Server using Scala

Querying an Elasticsearch Server using Scala

Last updated:

Assuming you are using Typesafe Activator to manage your apps, create a simple project based upon the minimal-scala template.

We'll be using elastic4s, which is but one way to connect to elasticsearch using Scala. There are other libraries around and you can also use raw HTTP requests.

Add

libraryDependencies += "com.sksamuel.elastic4s" %% "elastic4s" % "1.2.1.2"

to build.sbt and compile:

~/path/to/your/project$ sbt compile

Example 1: using Thread.sleep()

package com.example

// the query dsl
import com.sksamuel.elastic4s.ElasticClient
import com.sksamuel.elastic4s.ElasticDsl._

// elasticsearch stuff
import org.elasticsearch.action.search.SearchResponse

// scala concurrency stuff
import scala.concurrent._
import scala.concurrent.duration._
import ExecutionContext.Implicits.global
import scala.util.{Success, Failure}

object Hello {
    def main(args: Array[String]): Unit = {
       // scala uses the java driver which listens on port 9300
       val client = ElasticClient.remote("url.of.your.es.server", 9300)

       val res:Future[SearchResponse] = client execute { search in "index_name/type_name" query "your_query" }

        res onComplete{
            case Success(s) => println(s)
            case Failure(t) => println("An error has occured: " + t)
        }

        println("Request sent")

        //adjust this if needed
        Thread.sleep(1000)
    }
}

HEADS-UP

You may also want to have a look at Elastic4s DSL Examples and Reference.

Example 2: using Await.result()

package com.example

import com.sksamuel.elastic4s.ElasticClient
import com.sksamuel.elastic4s.ElasticDsl._
import org.elasticsearch.action.search.SearchResponse
import scala.concurrent._
import scala.concurrent.duration._
import ExecutionContext.Implicits.global
import scala.util.{ Success, Failure }
object Hello {
    def main(args: Array[String]) {
        val client = ElasticClient.remote("url.of.your.es.server", 9300)
        val res:Future[SearchResponse] = client execute { search in "index_name/type_name" query "your_query" }

        println("REQUEST SENT")

        val await = Await.result(res, 10.seconds)
        println(await)
    }
}

P.S.:

Since JSON is the lingua franca for Elasticsearch, you may want to have a look at some examples on how to use the json plugin for Play.

Dialogue & Discussion