上篇谈到:elasticsearch本身是一个完整的后台系统,对其的操作使用是通过终端api进行的。elasticsearch本身提供了多种编程语言的api,包括java的esjava。而elastic4s是一套基于esjava之上的scala api。

先看看scala 终端 ElasticClient的构建过程:

  import com.sksamuel.elastic4s.ElasticDsl._
val esjava = JavaClient(ElasticProperties("http://localhost:9200"))
val client = ElasticClient(esjava)

先构建JavaClient,JavaClient包嵌了个esjava的RestClient进行具体的操作:

class JavaClient(client: RestClient) extends HttpClient {
...
//send request to elasticsearch
override def send(req: ElasticRequest, callback: Either[Throwable, HttpResponse] => Unit): Unit = {
if (logger.isDebugEnabled) {
logger.debug("Executing elastic request {}", Show[ElasticRequest].show(req))
} val l = new ResponseListener {
override def onSuccess(r: org.elasticsearch.client.Response): Unit = callback(Right(fromResponse(r)))
override def onFailure(e: Exception): Unit = e match {
case re: ResponseException => callback(Right(fromResponse(re.getResponse)))
case t => callback(Left(JavaClientExceptionWrapper(t)))
}
} val request = new Request(req.method, req.endpoint)
req.params.foreach { case (key, value) => request.addParameter(key, value) }
req.entity.map(apacheEntity).foreach(request.setEntity)
//perform actual request sending
client.performRequestAsync(request, l)
}
...
}

上面这个RestClient即是elasticsearch提供的javaClient。而elastic4s的具体操作是通过RestClient.performRequestAsync进行的,如下:

public class RestClient implements Closeable {
...
/**
* Sends a request to the Elasticsearch cluster that the client points to.
* The request is executed asynchronously and the provided
* {@link ResponseListener} gets notified upon request completion or
* failure. Selects a host out of the provided ones in a round-robin
* fashion. Failing hosts are marked dead and retried after a certain
* amount of time (minimum 1 minute, maximum 30 minutes), depending on how
* many times they previously failed (the more failures, the later they
* will be retried). In case of failures all of the alive nodes (or dead
* nodes that deserve a retry) are retried until one responds or none of
* them does, in which case an {@link IOException} will be thrown.
*
* @param request the request to perform
* @param responseListener the {@link ResponseListener} to notify when the
* request is completed or fails
*/
public void performRequestAsync(Request request, ResponseListener responseListener) {
try {
FailureTrackingResponseListener failureTrackingResponseListener = new FailureTrackingResponseListener(responseListener);
InternalRequest internalRequest = new InternalRequest(request);
performRequestAsync(nextNodes(), internalRequest, failureTrackingResponseListener);
} catch (Exception e) {
responseListener.onFailure(e);
}
}
... }

另外,ElasticProperties是一个javaClient与ES连接的参数结构,包括IP地址:

/**
* Contains the endpoints of the nodes to connect to, as well as connection properties.
*/
case class ElasticProperties(endpoints: Seq[ElasticNodeEndpoint], options: Map[String, String] = Map.empty)

ElasticProperties包含了ES地址ElasticNodeEndPoint及其它连接参数(如果需要的话),如下:

 it should "support prefix path with trailing slash" in {
ElasticProperties("https://host1:1234,host2:2345/prefix/path/") shouldBe
ElasticProperties(Seq(ElasticNodeEndpoint("https", "host1", , Some("/prefix/path")), ElasticNodeEndpoint("https", "host2", , Some("/prefix/path"))))
}

当elastic4s完成了与elasticsearch的连接之后,就可以把按ES要求组合的Json指令发送到后台ES去执行了。elastic4s提供了一套DSL, 一种嵌入式语言,可以帮助用户更方便的用编程模式来组合ES的指令Json。当然,用户也可以直接把字符类的Json直接通过ElasticClient发送到后台ES。下面是一个简单可以运行的elastic4s示范:

import com.sksamuel.elastic4s.http.JavaClient
import com.sksamuel.elastic4s.requests.common.RefreshPolicy
import com.sksamuel.elastic4s.{ElasticClient, ElasticProperties} object HttpClientExampleApp extends App { // you must import the DSL to use the syntax helpers
import com.sksamuel.elastic4s.ElasticDsl._
val esjava = JavaClient(ElasticProperties("http://localhost:9200"))
val client = ElasticClient(esjava) client.execute {
bulk(
indexInto("books" ).fields("title" -> "重庆火锅的十种吃法", "content" -> "在这部书里描述了火锅的各种烹饪方式"),
indexInto("books" ).fields("title" -> "中国火锅大全", "content" -> "本书是全国中式烹饪中有关火锅的各种介绍")
).refresh(RefreshPolicy.WaitFor)
}.await val json =
"""
|{
| "query" : {
| "match" : {"title" : "火锅"}
| }
|}
|""".stripMargin
val response = client.execute {
search("books").source(json) // .matchQuery("title", "火锅")
}.await // prints out the original json
println(response.result.hits.hits.head.sourceAsString) client.close() }

search(2)- elasticsearch scala终端:elastic4s的更多相关文章

  1. elastic search book [ ElasticSearch book es book]

    谁在使用ELK 维基百科, github都使用 ELK (ElasticSearch es book) ElasticSearch入门 Elasticsearch入门,这一篇就够了==>http ...

  2. ElasticSearch、Logstash、Kibana 搭建高效率日志管理系统

    ELK (ElasticSearch.LogStash以及Kibana)三者组合是一个非常强大的工具,这里我们来实现监控日志文件并且收到日志到ElasticSearch搜索引擎,利用Kibana可视化 ...

  3. ElasticSearch大数据分布式弹性搜索引擎使用

    阅读目录: 背景 安装 查找.下载rpm包 .执行rpm包安装 配置elasticsearch专属账户和组 设置elasticsearch文件所有者 切换到elasticsearch专属账户测试能否成 ...

  4. Elasticsearch问题总结

    1.ES大量做FULL GC,日志如下: [2016-12-15 14:53:21,496][WARN ][monitor.jvm ] [vsp4] [gc][old][94725][4389] du ...

  5. Elasticsearch(入门篇)——Query DSL与查询行为

    ES提供了丰富多彩的查询接口,可以满足各种各样的查询要求.更多内容请参考:ELK修炼之道 Query DSL结构化查询 Query DSL是一个Java开源框架用于构建类型安全的SQL查询语句.采用A ...

  6. scala 学习心得

    scala 安装步骤 文件下载地址:www.scala-lang.org(Please report bugs at https://issues.scala-lang.org/. We welcom ...

  7. ElasticSearch大数据分布式弹性搜索引擎使用—从0到1

    阅读目录: 背景 安装 查找.下载rpm包 .执行rpm包安装 配置elasticsearch专属账户和组 设置elasticsearch文件所有者 切换到elasticsearch专属账户测试能否成 ...

  8. [Elasticsearch] 控制相关性 (一) - 后面的相关度分值理论计算

    从第一章翻译Elasticsearch官方指南Controlling Relevance一章. 控制相关度(Controlling Relevance) 对于仅处理结构化数据(比方日期.数值和字符枚举 ...

  9. 解剖 Elasticsearch 集群 - 之三

    解剖 Elasticsearch 集群 - 之三 本篇文章是一系列涵盖 Elasticsearch 底层架构和原型示例的其中一篇.在本篇文章中,我们会讨论 Elasticsearch 如何提供准实时搜 ...

随机推荐

  1. FileZilla相关配置说明

    相关下载可以直接到官网,或者阿里云帮助:https://help.aliyun.com/knowledge_detail/36243.html?spm=5176.10695662.1996646101 ...

  2. mysql--sql_mode报错整理

    1.在5.7版本以上mysql中使用group by语句进行分组时, 如果select的字段 , 不是完全对应的group by后面的字段 , 有其他字段 , 那么就会报这个错误 ERROR 1055 ...

  3. CRISPR/Cas9|InParanoid|orthoMCL|PanOCT|pan genome|meta genome|Core gene|CVTree3|

    生命组学: 泛基因组学:用于描述一个物种基因组,据细菌基因组动力学,因为细菌的基因漂移使得各个细菌之间的基因组差异很大,(单个细菌之间的基因组差异是以基因为单位的gain&loss,而人类基因 ...

  4. dTree动态生成树(后台处理,简化前台操作)

    dTree是个很方便在页面生成树的 js 控件,如果你下载了,我猜里在几分钟之内便能在页面上显示出一颗树来. 它本身给的例子是通过一些静态数据构造树,下面我说一种通过查询的数据动态构造树的方法. 例子 ...

  5. 吴裕雄--天生自然python编程:正则表达式

    re.match函数 re.match 尝试从字符串的起始位置匹配一个模式,如果不是起始位置匹配成功的话,match()就返回none. 函数语法: re.match(pattern, string, ...

  6. CSS--沃顿商学院网页布局

    源代码: <head> 右键CSS样式--附加样式表 </head> <body> <div id="dd"> <div id ...

  7. 维生素D补充过多会中毒

    虽然我们的物质生活越来越丰富,各种食材几乎一年四季都能够吃到,然而却越来越多的人选择进行补充各种维生素,但是你知道吗?维生素不是我们想象中多吃无害的,补充过多也会要人命,特别是最近非常流行补充的一种维 ...

  8. TICA 2019 自动的自动化测试——智能化一站式的API测试服务

    阿里QA导读:新奥集团中台的陈磊为我们打开了AI测试驱动的视野,同时也深入浅出地介绍了如何打造智能化API测试框架.通过陈磊老师的分享,我们看到了AI-DT的无限可能性.以后,AI能不能代替大部分手动 ...

  9. 通过zxing生成二维码

    二维码现在随处可见,在日常的开发中,也会经常涉及到二维码的生成,特别是开发一些活动或者推广方面的功能时,二维码甚至成为必备功能点.本文介绍通过 google 的 zxing 包生成带 logo 的二维 ...

  10. Nginx+PHP配置错误,日志:[error] 24324#0: *31 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream

    一.问题现象 1.安装nginx.php.php-fpm后,浏览器访问php报错,“File not found”: 二.问题排查 1.检查nginx.php-fpm服务是否正常启动,均正常启动: 2 ...