search(4)- elastic4s-ElasticDsl

来源:https://www.cnblogs.com/tiger-xc/archive/2020/04/16/12716181.html
-Advertisement-
Play Games

上次分析了一下elastic4s的運算框架。本來計劃接著開始實質的函數調用示範,不過看過了Elastic4s的所有使用說明文檔後感覺還是走的快了一點。主要原因是elasticsearch在7.0後有了很多重點調整改變,elastic4s雖然一直在源代碼方面緊跟ES的變化,但使用文件卻一直未能更新,所 ...


   上次分析了一下elastic4s的運算框架。本來計劃接著開始實質的函數調用示範,不過看過了Elastic4s的所有使用說明文檔後感覺還是走的快了一點。主要原因是elasticsearch在7.0後有了很多重點調整改變,elastic4s雖然一直在源代碼方面緊跟ES的變化,但使用文件卻一直未能更新,所以從說明文檔中學習elastic4s的使用方法是不可能的,必須從源碼中摸索。花了些時間過了一次elastic4s的源碼,感覺這個工具庫以後還是挺有用的:一是通過編程方式產生json請求比較靈活,而且可以通過compiler來保證json語句的正確性。二是對搜索結果的處理方面:由於返回的搜索結果是一堆又長又亂的複雜json,不敢想象自己要如何正確的解析這些json, 然後才能調用到正確的結果,但elastic4s提供了一套很完善的response類,使用起來可能會很方便。實際上elastic4s的編程模式和scala語言運用還是值得學習的。既然這樣,我想可能用elastic4s做一套完整的示範,包括:索引創建、索引維護、搜索、聚合統計等,對瞭解和掌握elastic4s可能大有幫助。在這之前,我們還是再回顧一下elastic4s的運算原理:elastic4s的功能其實很簡單:通過dsl語句組合產生json請求,然後發送給ES-rest終端, 對返回的json結果進行處理,篩選出目標答案。

上篇我們討論過elastic4s的基本運算框架:

  client.execute(
      createIndex("company")
      .shards(2).replicas(3)
  )

...

  val bookschema = putMapping("books")
      .as(
        KeywordField("isbn"),
        textField("title"),
        doubleField("price")
      )

  client.execute(
    bookschema
  )

...

  val futAccts = client.execute(
    search("bank").termQuery("city" -> "dante")
  )
  futAccts.onComplete{
    case Success(esresp) =>
      esresp.result.hits.hits.foreach(h =>println(h.sourceAsMap))
    case Failure(err) => println(s"search error: ${err.getMessage}")
  }

實際上execute(T)的T代表elastic4s支持的所有ES操作類型。這種方法實現有賴於scala的typeclass模式。我們先看看execute函數定義:

  // Executes the given request type T, and returns an effect of Response[U]
  // where U is particular to the request type.
  // For example a search request will return a Response[SearchResponse].
  def execute[T, U, F[_]](t: T)(implicit
                                executor: Executor[F],
                                functor: Functor[F],
                                handler: Handler[T, U],
                                manifest: Manifest[U]): F[Response[U]] = {
    val request = handler.build(t)
    val f = executor.exec(client, request)
    functor.map(f) { resp =>
      handler.responseHandler.handle(resp) match {
        case Right(u) => RequestSuccess(resp.statusCode, resp.entity.map(_.content), resp.headers, u)
        case Left(error) => RequestFailure(resp.statusCode, resp.entity.map(_.content), resp.headers, error)
      }
    }
  }

上篇提過Handler[T,U]是個typeclass, 代表對不同類型T的json構建方法。elastic4s提供了這個T類型的操作方法,如下:

trait ElasticDsl
    extends ElasticApi
    with Logging
    with ElasticImplicits
    with BulkHandlers
    with CatHandlers
    with CountHandlers
    with ClusterHandlers
    with DeleteHandlers
    with ExistsHandlers
    with ExplainHandlers
    with GetHandlers
    with IndexHandlers
    with IndexAdminHandlers
    with IndexAliasHandlers
    with IndexStatsHandlers
    with IndexTemplateHandlers
    with LocksHandlers
    with MappingHandlers
    with NodesHandlers
    with ReindexHandlers
    with RoleAdminHandlers
    with RoleHandlers
    with RolloverHandlers
    with SearchHandlers
    with SearchTemplateHandlers
    with SearchScrollHandlers
    with SettingsHandlers
    with SnapshotHandlers
    with UpdateHandlers
    with TaskHandlers
    with TermVectorHandlers
    with UserAdminHandlers
    with UserHandlers
    with ValidateHandlers {

  implicit class RichRequest[T](t: T) {
    def request(implicit handler: Handler[T, _]): ElasticRequest = handler.build(t)
    def show(implicit handler: Handler[T, _]): String            = Show[ElasticRequest].show(handler.build(t))
  }
}

object ElasticDsl extends ElasticDsl

所有的操作api在這裡:

trait ElasticApi
  extends AliasesApi
    with ElasticImplicits
    with AggregationApi
    with AnalyzerApi
    with BulkApi
    with CatsApi
    with CreateIndexApi
    with ClearRolesCacheApi
    with ClusterApi
    with CollapseApi
    with CountApi
    with CreateRoleApi
    with CreateUserApi
    with DeleteApi
    with DeleteIndexApi
    with DeleteRoleApi
    with DeleteUserApi
    with DynamicTemplateApi
    with ExistsApi
    with ExplainApi
    with ForceMergeApi
    with GetApi
    with HighlightApi
    with IndexApi
    with IndexAdminApi
    with IndexRecoveryApi
    with IndexTemplateApi
    with LocksApi
    with MappingApi
    with NodesApi
    with NormalizerApi
    with QueryApi
    with PipelineAggregationApi
    with ReindexApi
    with RoleApi
    with ScriptApi
    with ScoreApi
    with ScrollApi
    with SearchApi
    with SearchTemplateApi
    with SettingsApi
    with SnapshotApi
    with SortApi
    with SuggestionApi
    with TaskApi
    with TermVectorApi
    with TokenizerApi
    with TokenFilterApi
    with TypesApi
    with UpdateApi
    with UserAdminApi
    with UserApi
    with ValidateApi {

  implicit class RichFuture[T](future: Future[T]) {
    def await(implicit duration: Duration = 60.seconds): T = Await.result(future, duration)
  }
}

object ElasticApi extends ElasticApi

通過 import ElasticDsl._  ,所有類型的api,handler操作方法都有了。下麵是例子里的api方法:

trait CreateIndexApi {

  def createIndex(name: String): CreateIndexRequest = CreateIndexRequest(name)
...
}

trait MappingApi {
...
  def putMapping(indexes: Indexes): PutMappingRequest =  PutMappingRequest(IndexesAndType(indexes))
}

trait SearchApi {
  def search(index: String): SearchRequest = search(Indexes(index))
...
}

CreateIndexRequest, PutMappingRequest,SearchRequest這幾個類型都提供了handler隱式實例:

trait IndexAdminHandlers {
...
  implicit object CreateIndexHandler extends Handler[CreateIndexRequest, CreateIndexResponse] {

    override def responseHandler: ResponseHandler[CreateIndexResponse] = new ResponseHandler[CreateIndexResponse] {
      override def handle(response: HttpResponse): Either[ElasticError, CreateIndexResponse] =
        response.statusCode match {
          case 200 | 201 => Right(ResponseHandler.fromResponse[CreateIndexResponse](response))
          case 400 | 500 => Left(ElasticError.parse(response))
          case _         => sys.error(response.toString)
        }
    }

    override def build(request: CreateIndexRequest): ElasticRequest = {

      val endpoint = "/" + URLEncoder.encode(request.name, "UTF-8")

      val params = scala.collection.mutable.Map.empty[String, Any]
      request.waitForActiveShards.foreach(params.put("wait_for_active_shards", _))
      request.includeTypeName.foreach(params.put("include_type_name", _))

      val body   = CreateIndexContentBuilder(request).string()
      val entity = HttpEntity(body, "application/json")

      ElasticRequest("PUT", endpoint, params.toMap, entity)
    }
  }

}

...

trait MappingHandlers {
...
 implicit object PutMappingHandler extends Handler[PutMappingRequest, PutMappingResponse] {

    override def build(request: PutMappingRequest): ElasticRequest = {

      val endpoint = s"/${request.indexesAndType.indexes.mkString(",")}/_mapping${request.indexesAndType.`type`.map("/" + _).getOrElse("")}"

      val params = scala.collection.mutable.Map.empty[String, Any]
      request.updateAllTypes.foreach(params.put("update_all_types", _))
      request.ignoreUnavailable.foreach(params.put("ignore_unavailable", _))
      request.allowNoIndices.foreach(params.put("allow_no_indices", _))
      request.expandWildcards.foreach(params.put("expand_wildcards", _))
      request.includeTypeName.foreach(params.put("include_type_name", _))

      val body   = PutMappingBuilderFn(request).string()
      val entity = HttpEntity(body, "application/json")

      ElasticRequest("PUT", endpoint, params.toMap, entity)
    }
  }

}
...
trait SearchHandlers {
...
  implicit object SearchHandler extends Handler[SearchRequest, SearchResponse] {

    override def build(request: SearchRequest): ElasticRequest = {

      val endpoint =
        if (request.indexes.values.isEmpty)
          "/_all/_search"
        else
          "/" + request.indexes.values
            .map(URLEncoder.encode(_, "UTF-8"))
            .mkString(",") + "/_search"

      val params = scala.collection.mutable.Map.empty[String, String]
      request.requestCache.map(_.toString).foreach(params.put("request_cache", _))
      request.searchType
        .filter(_ != SearchType.DEFAULT)
        .map(SearchTypeHttpParameters.convert)
        .foreach(params.put("search_type", _))
      request.routing.map(_.toString).foreach(params.put("routing", _))
      request.pref.foreach(params.put("preference", _))
      request.keepAlive.foreach(params.put("scroll", _))
      request.allowPartialSearchResults.map(_.toString).foreach(params.put("allow_partial_search_results", _))
      request.batchedReduceSize.map(_.toString).foreach(params.put("batched_reduce_size", _))

      request.indicesOptions.foreach { opts =>
        IndicesOptionsParams(opts).foreach { case (key, value) => params.put(key, value) }
      }

      request.typedKeys.map(_.toString).foreach(params.put("typed_keys", _))

      val body = request.source.getOrElse(SearchBodyBuilderFn(request).string())
      ElasticRequest("POST", endpoint, params.toMap, HttpEntity(body, "application/json"))
    }
  }

}

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 代碼 @Slf4j public class StringCompareDemo { public static void compare() { String a = "1"; String b = "1"; log.info("\nString a = \"1\";\n" + "String b ...
  • 最近與同事討論時,提到Go語言的可變參數,之前沒有總結過相關知識點,今天我們介紹一下Go語言的可變參數。 可變參數(Variable Parameters):參數數量可變的函數稱之為可變參數函數,主要是在使用語法糖(syntactic sugar)。最經典的例子就是fmt.Printf()和類似的函 ...
  • 前言: 準備了體體面面的自我介紹,敗在了技術深度上;又或者技術知識背得完完全全,卻輸在了面試技巧,看看這個,一定要看到最後 115個Java面試題: 1. 什麼是Java虛擬機?為什麼Java被稱作是無關的編程語言? 2. JDK和JRE的區別是什麼? 3. static關鍵字是什麼意思?Java中 ...
  • 命令行啟動服務的方式,在後端使用非常廣泛,如果有寫過C語言的同學相信不難理解這一點!在C語言中,我們可以根據argc和argv來獲取和解析命令行的參數,從而通過不同的參數調取不同的方法,同時也可以用Usage來列印幫助信息了。 那麼開始今天的話題之前,我們回顧一下在C語言中是如何解析傳遞的參數的。 ...
  • 在Asp.net的WEBform中,上傳文件與下載文件處理是很簡單的事情,如果轉為ASP.NET MVC呢?那就沒有那麼容易了,難少少,也不是很難,一起來看下本文吧。本文主要講如何在Asp.net MVC中上傳文件,然後如何再從伺服器中把上傳過的文件下載下來.在Web Forms中,當你把一個Fil ...
  • SolrCloud SolrCloud(solr 雲)是Solr提供的分散式搜索方案,當你需要大規模,容錯,分散式索引和檢索能力時使用 SolrCloud。當一個系統的索引數據量少的時候是不需要使用SolrCloud的,當索引量很大,搜索請求併發很高,這時需要使用SolrCloud來滿足這些需求。 ...
  • 如果你參加過一些大廠面試,肯定會遇到一些開放性的問題: 1、寫一段程式,讓其運行時的表現為觸發了5次Young GC、3次Full GC、然後3次Young GC; 2、如果一個Java進程突然消失了,你會怎麼去排查這種問題? 3、給了一段Spring載入Bean的代碼片段,闡述一下具體的執行流程? ...
  • 前言: 常常一些核心技術等我碰到的時候才發現自己忘得差不多了,甘心安於現狀,等自己跟別人有了差距之後才想起來要學習,我太難了,永遠不要停下自己學習的腳步,比你厲害的人真的有很多,今天給大家分享的是一份283頁的Java核心知識點(PDF)特別詳細,有幸得此寶典,這麼詳細的核心知識點怎能獨吞呢,分享給 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...