Skip to content

Instantly share code, notes, and snippets.

@sc6l6d3v
Created September 13, 2017 15:33
Show Gist options
  • Save sc6l6d3v/c1aa5240d3b20f9687ff918596400506 to your computer and use it in GitHub Desktop.
Save sc6l6d3v/c1aa5240d3b20f9687ff918596400506 to your computer and use it in GitHub Desktop.
ES 5.4 Completion example using elastic4s DSL
package com.sksamuel.elastic4s.samples
import com.sksamuel.elastic4s.http.HttpClient
import com.sksamuel.elastic4s.{ArrayFieldValue, ElasticsearchClientUri, Indexable, SimpleFieldValue}
import org.elasticsearch.action.support.WriteRequest.RefreshPolicy
import scala.concurrent.duration.{Duration, _}
import scala.language.implicitConversions
object CompletionExampleApp extends App {
// you must import the DSL to use the syntax helpers
import com.sksamuel.elastic4s.http.ElasticDsl._
val host = "localhost"
val port = 9200
val client = HttpClient(ElasticsearchClientUri(host, port))
val myIndex = "complsuggest"
val myType = "music"
val indexType = myIndex / myType
case class Song(name: String, artist: String, name_suggest: List[String])
implicit object SongIndexable extends Indexable[Song] {
def stringifyList(l: List[String]) = l.mkString("""["""", """","""", """"]""")
override def json(t: Song): String =
s"""{"name":"${t.name}", "artist":"${t.artist}", "name_suggest": {"input": ${stringifyList(t.name_suggest)}}}"""
}
implicit val timeout: Duration = 8000 millis
client.execute {
createIndex(myIndex).mappings(
mapping("music").fields(
textField("name").index(true),
textField("artist").index(true),
completionField("name_suggest")
)
)
}.await
private def enumperms(t: String): List[String] = t.scanLeft("")(_+_).filter(_ != "").toSet.toList.sorted
client.execute {
val bulkData = bulk(
indexInto(indexType) doc Song("Rocket Man", "Kate Bush", enumperms("rocket man")),
indexInto(indexType) doc Song("Rubberband Girl", "Kate Bush", enumperms("rubberband girl")),
indexInto(indexType) doc Song("Running Up that Hill", "Kate Bush", enumperms("running up that hill")),
indexInto(indexType) doc Song("The Fog", "Kate Bush", enumperms("the fog")),
indexInto(indexType) doc Song("The Red Shoes", "Kate Bush", enumperms("the red shoes")),
indexInto(indexType) doc Song("The Dreaming", "Kate Bush", enumperms("the dreaming")),
indexInto(indexType) doc Song("The Big Sky", "Kate Bush", enumperms("the big sky"))
).refresh(RefreshPolicy.IMMEDIATE)
bulkData
}.await
client.close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment