我要试试elastic4s
搜索适用于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仓库中获取一个合适的版本。
$ docker pull dockerfile/elasticsearch
...
$ docker run -d -p 9200:9200 -p 9300:9300 dockerfile/elasticsearch
好的。
回到sbt控制台并连接到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
如您所見,所有的回傳都是未來。
索引
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"}
}
}
}