Skip to content

Instantly share code, notes, and snippets.

@yasuabe
Created May 10, 2019 11:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yasuabe/a09eda8eaba38ba910fc43fac1437859 to your computer and use it in GitHub Desktop.
Save yasuabe/a09eda8eaba38ba910fc43fac1437859 to your computer and use it in GitHub Desktop.
simple elastic4s sample using Cats Effect and Circe
package trial1
import cats.effect._
import cats.instances.list._
import cats.syntax.flatMap._
import cats.syntax.functor._
import cats.syntax.traverse._
import com.sksamuel.elastic4s.circe._
import com.sksamuel.elastic4s.http.search.SearchResponse
import com.sksamuel.elastic4s.http._
import com.sksamuel.elastic4s.indexes.{CreateIndexRequest, IndexRequest}
import com.sksamuel.elastic4s.searches.SearchRequest
import io.circe.generic.auto._
case class ModernArtist(name2: String)
trait Program[F[_]] {
import com.sksamuel.elastic4s.http.ElasticDsl._
implicit val F: Sync[F]
private def puts(s: Any): F[Unit] = F.delay { println(s) }
val createArtists: CreateIndexRequest = createIndex("artists") mappings {
mapping("modern") fields textField("name")
}
val indexModern: IndexRequest =
indexInto("artists" / "modern") source ModernArtist("L.S. Lowry") refreshImmediately
val searchModern: SearchRequest = search("artists") query "lowry"
def client: Resource[F, ElasticClient] = Resource.make {
F.delay { ElasticClient(ElasticProperties("http://127.0.0.1:9200")) }
} (c => F.delay { c.close() })
def report(res: Response[SearchResponse]): F[Unit] = res match {
case RequestFailure(_, _, _, e) => puts(s"We failed: $e")
case RequestSuccess(_, _, _, r) => for {
_ <- r.to[ModernArtist].toList.map(puts(_)).sequence
_ <- puts(s"There were ${r.totalHits} total hits")
} yield ()
}
def program(implicit U: Functor[F], E: Executor[F]): F[Unit] = client use { c =>
for {
_ <- c.execute(createArtists)
_ <- c.execute(indexModern)
_ <- c.execute(searchModern) >>= report
} yield ()
}
}
object ArtistIndex extends IOApp with Program[IO] {
import com.sksamuel.elastic4s.cats.effect.instances._
val F: Sync[IO] = Sync[IO]
def run(args: List[String]): IO[ExitCode] = program as ExitCode.Success
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment