Skip to content

Instantly share code, notes, and snippets.

@RHDZMOTA
Created June 1, 2019 03:33
Show Gist options
  • Save RHDZMOTA/95933e9db999da82012396a82336574c to your computer and use it in GitHub Desktop.
Save RHDZMOTA/95933e9db999da82012396a82336574c to your computer and use it in GitHub Desktop.
Using elastic4s

Elasticsearch Scala Config

This is a simple elasticsearch scala config.

SBT Config

Add the following dependency:

"com.sksamuel.elastic4s" %% "elastic4s-http" % "6.5.1"

Code Config

Create the ES client:

import com.sksamuel.elastic4s.http.{ElasticClient, ElasticProperties}
import com.sksamuel.elastic4s.http.ElasticDsl._
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.auth.UsernamePasswordCredentials
import org.apache.http.client.config.RequestConfig
import org.apache.http.auth.AuthScope

val connectionRequestTimeoutMs = 30000
val socketTimeoutMs = 30000
val url = "http://localhost:920"

// Credential provider
val provider: Option[BasicCredentialsProvider] = for {
  userName <- sys.env.get("ES_USER")
  password <- sys.env.get("ES_PW")
} yield {
  val basicCredentialsProvider = new BasicCredentialsProvider
  val credentials = new UsernamePasswordCredentials(userName, password)
  basicCredentialsProvider.setCredentials(AuthScope.ANY, credentials)
  basicCredentialsProvider
}

// Elasticsearch client
val client: ElasticClient = ElasticClient(
  ElasticProperties(url),
  (requestConfigBuilder: RequestConfig.Builder) => {
    requestConfigBuilder
      .setConnectionRequestTimeout(connectionRequestTimeoutMs)
      .setSocketTimeout(socketTimeoutMs)
  },
  (httpClientBuilder: HttpAsyncClientBuilder) => { provider
    .map { credsProvider => httpClientBuilder.setDefaultCredentialsProvider(credsProvider) }
    .getOrElse(httpClientBuilder)
  }
)

// Create an index...
client.execute(createIndex("idx")).await
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment