LoginSignup
5
4

More than 5 years have passed since last update.

elastic4s を試す

Posted at

Elasticsearch 用のscala バインディングを探していて、elastic4s 触った記録。

他にもあるが このなかであげられてる中では一番☆が多かった。

試す

build.sbt にこれだけ書いてsbt console起動。

libraryDependencies ++= Seq(
  "com.sksamuel.elastic4s" %% "elastic4s" % "1.2.1.2"
)

まずパッケージをインポート

scala> import com.sksamuel.elastic4s.ElasticClient
import com.sksamuel.elastic4s.ElasticClient

scala> import com.sksamuel.elastic4s.ElasticDsl._
import com.sksamuel.elastic4s.ElasticDsl._

てか、そもそもElasticsearchが動いてないじゃんってことでdocker repoから適当なのを取ってくる、

$ docker pull dockerfile/elasticsearch
...
$ docker run -d -p 9200:9200 -p 9300:9300 dockerfile/elasticsearch

はい。

sbt consoleに戻ってESとつなげる。

scala > val cl = Elaticsearch.local
cl: com.sksamuel.elastic4s.ElasticClient = com.sksamuel.elastic4s.ElasticClient@619fc958
// val cl = Elaticsearch.remote("remote", 9300) // リモートの場合

インデックスの作成

scala> cl.execute{ create index "tweets" }
res0: scala.concurrent.Future[org.elasticsearch.action.admin.indices.create.CreateIndexResponse] = scala.concurrent.impl.Promise$DefaultPromise@16f91928

見て分かる通り全部Futureで返ってくる。

インデックス

scala> val f =cl.execute{ index into "tweets" fields ("text"->"helloworld","user"->"iwag")  }
f: scala.concurrent.Future[org.elasticsearch.action.index.IndexResponse] = scala.concurrent.impl.Promise$DefaultPromise@26ae2063

サーチ

scala> val f =cl.execute{ search in "tweets" }
f: scala.concurrent.Future[org.elasticsearch.action.search.SearchResponse] = scala.concurrent.impl.Promise$DefaultPromise@3ade8076

サーチ返ってくるのがESのJavaなSearchResponseでだるい。

scala> f.value.get.get
res1: org.elasticsearch.action.search.SearchResponse =
{
  "took" : 2,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "failed" : 0
  },
  "hits" : {
    "total" : 7,
    "max_score" : 1.0,
    "hits" : [ {
      "_index" : "tweets",
      "_type" : "test",
      "_id" : "KGWbDEY7Q66PFDnDeFmdpA",
      "_score" : 1.0,
      "_source":{"text":"hello world","user":"iwag"}
    }
  }
}
5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4