上篇谈到: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. gin源码剖析

    介绍 Gin 是一个 Golang 写的 web 框架,具有高性能的优点,基于 httprouter,它提供了类似martini但更好性能(路由性能约快40倍)的API服务.官方地址:https:// ...

  2. Java程序、JSP以及JavaScript中如何判断某个字符串是否包含某个子串

    1.JSP str:原始字符串, subStr:要查找的子字符串 <c:if test="${fn:contains(str,subStr)==true}"> < ...

  3. Java WebSocket实现简易聊天室

    一.Socket简介 Socket又称"套接字",应用程序通常通过"套接字"向网络发出请求或者应答网络请求.Socket的英文原义是“孔”或“插座”,作为UNI ...

  4. PHP RabbitMQ 教程(三)

    发布/订阅 我们在上一节创建了一个工作队列,并假定队列对应的任务传送给了某个客户端.在这一章节我们会做一些完全不一样的东西–我们会发送一条消息到多个消费者,也称之为"发布/订阅"模 ...

  5. fabric 初步实践

    在集群部署时,我们经常用到堡垒机作为跳板,堡垒机和集群的其他的用户名.密码.端口号都是不同的,fabric如何进行配置不同的用户.端口号和密码. fabric作为一种强大的运维工具,可以让部署运维轻松 ...

  6. github hexo配置踩过的坑

    大体步骤:配置npm,在github中增加自己的sshkey. 多sshkey的话在用户主目录的.ssh中要配置好. 删除仓库里面 source/_posts/我的文章.md 执行下面命令更新博客 h ...

  7. Android长按及拖动事件探究

    Android中长按拖动还是比较常见的.比如Launcher中的图标拖动及屏幕切换,ListView中item顺序的改变,新闻类App中新闻类别的顺序改变等.下面就这个事件做一下分析. 就目前而言,A ...

  8. Ta说:2016微软亚洲研究院第二届博士生论坛

    ​ "聚合多元人才创造无尽可能,让每一位优秀博士生得到发声成长机会"可以说是这次微软亚洲研究院博士生论坛最好的归纳了.自去年首次举办以来,这项旨在助力青年研究者成长的项目迅速得到了 ...

  9. JS实现总价随数量变化而变化(顾客购买商品表单)

    */ * Copyright (c) 2016,烟台大学计算机与控制工程学院 * All rights reserved. * 文件名:test.html * 作者:常轩 * 微信公众号:Worldh ...

  10. Day 1 模拟

    1. P1088 火星人 利用STL中的next_permutation();函数求一种排列的下一种排列,循环m次即为答案.(STL大法好~~C++是世界上最好的语言~~逃 #include < ...