ES.scala 10.6 KB
Newer Older
赵威's avatar
赵威 committed
1
package com.gmei.up.utils
赵威's avatar
赵威 committed
2

赵威's avatar
赵威 committed
3
import scala.collection.mutable.ListBuffer
赵威's avatar
赵威 committed
4
import scala.util.Try
赵威's avatar
赵威 committed
5 6 7 8 9

import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._
import org.json4s.JObject

赵威's avatar
赵威 committed
10 11 12 13
import org.apache.http.HttpHost
import org.apache.http.auth.{ AuthScope, UsernamePasswordCredentials }
import org.apache.http.impl.client.BasicCredentialsProvider
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder
赵威's avatar
赵威 committed
14

赵威's avatar
赵威 committed
15 16
import org.elasticsearch.client.RestClient
import org.elasticsearch.client.RestClientBuilder.HttpClientConfigCallback
赵威's avatar
赵威 committed
17
import com.sksamuel.elastic4s.requests.searches.{ SearchRequest, SearchResponse }
赵威's avatar
赵威 committed
18
import com.sksamuel.elastic4s.requests.searches.sort.{ FieldSort, SortOrder, ScriptSortType }
赵威's avatar
赵威 committed
19
import com.sksamuel.elastic4s.ElasticDsl._
赵威's avatar
赵威 committed
20 21 22 23 24 25 26 27 28
import com.sksamuel.elastic4s.{ HitReader, Hit, ElasticClient }
import com.sksamuel.elastic4s.http.JavaClient
import com.sksamuel.elastic4s.requests.searches.queries.Query
import com.sksamuel.elastic4s.requests.searches.queries.term.TermsQuery
import com.sksamuel.elastic4s.requests.script.{ Script, ScriptType }
import com.sksamuel.elastic4s.requests.searches.queries.funcscorer.{
  CombineFunction,
  FunctionScoreQueryScoreMode,
  WeightScore,
赵威's avatar
赵威 committed
29 30
  ScoreFunction,
  ScriptScore
赵威's avatar
赵威 committed
31
}
赵威's avatar
赵威 committed
32 33 34 35 36 37

object ESClient {
  private class ElasticCredentials(username: String, password: String) extends HttpClientConfigCallback {
    val credentials = new UsernamePasswordCredentials(username, password)
    val credentialsProvider = new BasicCredentialsProvider()
    credentialsProvider.setCredentials(AuthScope.ANY, credentials)
赵威's avatar
赵威 committed
38

赵威's avatar
赵威 committed
39
    override def customizeHttpClient(httpClientBuilder: HttpAsyncClientBuilder): HttpAsyncClientBuilder =
赵威's avatar
赵威 committed
40 41 42
      httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
  }

赵威's avatar
赵威 committed
43
  def create(hostname: String, port: Int, username: String, password: String): ElasticClient = {
赵威's avatar
赵威 committed
44 45 46 47 48
    val restClient = RestClient
      .builder(new HttpHost(hostname, port, "http"))
      .setHttpClientConfigCallback(new ElasticCredentials(username, password))
      .build()

赵威's avatar
赵威 committed
49
    ElasticClient(JavaClient.fromRestClient(restClient))
赵威's avatar
赵威 committed
50 51 52 53
  }
}

object ES {
赵威's avatar
赵威 committed
54
  case class Character(id: String, index: String, projects: String)
赵威's avatar
赵威 committed
55 56 57 58

  implicit object CharacterHitReader extends HitReader[Character] {
    override def read(hit: Hit): Try[Character] = {
      val source = hit.sourceAsMap
赵威's avatar
赵威 committed
59
      Try(Character(source("id").toString, hit.index, source("tags_v3").toString))
赵威's avatar
赵威 committed
60 61 62
    }
  }

赵威's avatar
赵威 committed
63 64 65 66 67 68
  def test(
      diaryRequest: SearchRequest,
      tractateRequest: SearchRequest,
      answerRequest: SearchRequest,
      serviceDiaryReq: SearchRequest
  ) = {
赵威's avatar
赵威 committed
69
    // TODO read from config
赵威's avatar
赵威 committed
70
    val client: ElasticClient = ESClient.create("172.16.52.33", 9200, "elastic", "gengmei!@#")
赵威's avatar
赵威 committed
71

赵威's avatar
赵威 committed
72 73 74
    val multiReq = multi(
      diaryRequest,
      tractateRequest,
赵威's avatar
赵威 committed
75 76
      answerRequest,
      serviceDiaryReq
赵威's avatar
赵威 committed
77
    )
赵威's avatar
赵威 committed
78

赵威's avatar
赵威 committed
79
    println(multiReq.show)
赵威's avatar
赵威 committed
80

赵威's avatar
赵威 committed
81
    // TODO remove await
赵威's avatar
赵威 committed
82
    val resp = client.execute(multiReq).await
赵威's avatar
赵威 committed
83

赵威's avatar
赵威 committed
84
    // println(resp)
赵威's avatar
赵威 committed
85

赵威's avatar
赵威 committed
86
    val a = resp.result.to[Character]
赵威's avatar
赵威 committed
87

赵威's avatar
赵威 committed
88 89 90 91
    println("%%%%%%%%%%%")
    println(a.size)
    a.foreach { x =>
      println(x.id, x.index, x.projects)
赵威's avatar
赵威 committed
92
    }
赵威's avatar
赵威 committed
93
    println("%%%%%%%%%%%")
赵威's avatar
赵威 committed
94

赵威's avatar
赵威 committed
95 96
    resp
  }
赵威's avatar
赵威 committed
97

赵威's avatar
赵威 committed
98
  def generateDiaryRequest(
赵威's avatar
赵威 committed
99 100 101 102 103
      projects: List[String],
      secondDemands: List[String],
      cityId: Int = -1
  ): SearchRequest = {
    val size = 15
赵威's avatar
赵威 committed
104
    val includes = List("id", "tags_v3")
赵威's avatar
赵威 committed
105 106
    var scoreListBuffer: ListBuffer[ScoreFunction] = ListBuffer.empty[ScoreFunction]
    var shouldListBuffer: ListBuffer[Query] = ListBuffer.empty[Query]
赵威's avatar
赵威 committed
107 108

    if (projects.size > 0) {
赵威's avatar
赵威 committed
109 110 111 112 113
      scoreListBuffer += WeightScore(60).filter(
        must(termsQuery("tags_v3", projects), termQuery("is_promote", true))
      )
      scoreListBuffer += WeightScore(50).filter(termsQuery("tags_v3", projects))
      shouldListBuffer += TermsQuery("tags_v3", projects)
赵威's avatar
赵威 committed
114 115
    }
    if (secondDemands.size > 0) {
赵威's avatar
赵威 committed
116 117
      scoreListBuffer += WeightScore(40).filter(termsQuery("second_demands", secondDemands))
      shouldListBuffer += TermsQuery("second_demands", secondDemands)
赵威's avatar
赵威 committed
118 119
    }

赵威's avatar
赵威 committed
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
    val res = search("gm-dbmw-diary-read")
      .query {
        functionScoreQuery()
          .functions(scoreListBuffer.toList)
          .scoreMode(FunctionScoreQueryScoreMode.Max)
          .boostMode(CombineFunction.Replace)
          .query {
            boolQuery()
              .must(
                termQuery("is_online", true),
                termQuery("has_cover", true),
                termQuery("is_sink", false),
                termQuery("has_after_cover", true),
                termQuery("has_before_cover", true),
                rangeQuery("content_level").gte(3),
                termQuery("content_simi_bol_show", 0)
              )
              .not(termQuery("show_by_index", 2))
              .should(shouldListBuffer.toList)
              .minimumShouldMatch(1)
          }
赵威's avatar
赵威 committed
141
      }
赵威's avatar
赵威 committed
142 143 144 145 146 147 148 149 150 151 152 153 154 155
      .size(size)
      .sourceInclude(includes)
      .sortBy(
        scriptSort(
          script(
            "if (doc['doctor.hospital.city_tag_id'].size()!=0){if (doc['doctor.hospital.city_tag_id'].value ==params.user_city_tag_id){return 2;} else if (doc['nearby_city_tags_v1.tag_id'].contains(params.user_city_tag_id) ) {return 1;} else {return 0;} }else{return 0}"
          ).params(Map("user_city_tag_id" -> cityId)).lang("painless")
        ).typed("number").order(SortOrder.Desc),
        FieldSort("_score").desc(),
        FieldSort("has_video_cover").asc(),
        FieldSort("offline_score").desc(),
        FieldSort("good_click").desc(),
        FieldSort("last_update_time").desc()
      )
赵威's avatar
赵威 committed
156 157
    // println("diary query")
    // println(res.show)
赵威's avatar
赵威 committed
158
    res
赵威's avatar
赵威 committed
159 160
  }

赵威's avatar
赵威 committed
161 162
  def generateTractateRequest(projects: List[String], secondDemands: List[String]): SearchRequest = {
    val size = 15
赵威's avatar
赵威 committed
163
    val includes = List("id", "tags_v3")
赵威's avatar
赵威 committed
164 165
    var scoreListBuffer: ListBuffer[ScoreFunction] = ListBuffer.empty[ScoreFunction]
    var shouldListBuffer: ListBuffer[Query] = ListBuffer.empty[Query]
赵威's avatar
赵威 committed
166 167

    if (projects.size > 0) {
赵威's avatar
赵威 committed
168 169 170 171 172 173 174 175 176 177
      scoreListBuffer += WeightScore(60).filter(
        must(termsQuery("tags_v3", projects), termQuery("is_promote", true))
      )
      scoreListBuffer += WeightScore(50).filter(termsQuery("tags_v3", projects))
      shouldListBuffer += TermsQuery("tags_v3", projects)
    }
    if (secondDemands.size > 0) {
      scoreListBuffer += WeightScore(40).filter(termsQuery("second_demands", secondDemands))
      shouldListBuffer += TermsQuery("second_demands", secondDemands)
    }
赵威's avatar
赵威 committed
178

赵威's avatar
赵威 committed
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    val res = search("gm-dbmw-tractate-read")
      .query {
        functionScoreQuery()
          .functions(scoreListBuffer.toList)
          .scoreMode(FunctionScoreQueryScoreMode.Max)
          .boostMode(CombineFunction.Replace)
          .query {
            boolQuery()
              .must(
                termQuery("is_online", true),
                rangeQuery("content_level").gte(3)
              )
              .not(termQuery("show_by_index", 2), termQuery("status", 4))
              .should(shouldListBuffer.toList)
              .minimumShouldMatch(1)
          }
      }
      .size(size)
      .sourceInclude(includes)
      .sortBy(
        FieldSort("_score").desc()
      )
    // println("tractate query")
    // println(res.show)
    res
  }
赵威's avatar
赵威 committed
205

赵威's avatar
赵威 committed
206 207 208 209 210
  def generateAnswerRequest(projects: List[String], secondDemands: List[String]): SearchRequest = {
    val size = 15
    val includes = List("id", "tags_v3")
    var scoreListBuffer: ListBuffer[ScoreFunction] = ListBuffer.empty[ScoreFunction]
    var shouldListBuffer: ListBuffer[Query] = ListBuffer.empty[Query]
赵威's avatar
赵威 committed
211

赵威's avatar
赵威 committed
212 213 214 215 216 217 218 219 220 221
    if (projects.size > 0) {
      scoreListBuffer += WeightScore(60).filter(
        must(termsQuery("tags_v3", projects), termQuery("is_promote", true))
      )
      scoreListBuffer += WeightScore(50).filter(termsQuery("tags_v3", projects))
      shouldListBuffer += TermsQuery("tags_v3", projects)
    }
    if (secondDemands.size > 0) {
      scoreListBuffer += WeightScore(40).filter(termsQuery("second_demands", secondDemands))
      shouldListBuffer += TermsQuery("second_demands", secondDemands)
赵威's avatar
赵威 committed
222 223
    }

赵威's avatar
赵威 committed
224
    val res = search("gm-dbmw-answer-read")
赵威's avatar
赵威 committed
225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
      .query {
        functionScoreQuery()
          .functions(scoreListBuffer.toList)
          .scoreMode(FunctionScoreQueryScoreMode.Max)
          .boostMode(CombineFunction.Replace)
          .query {
            boolQuery()
              .must(
                termQuery("is_online", true),
                rangeQuery("content_level").gte(3),
                rangeQuery("content_length").gte(30)
              )
              .not(termQuery("show_by_index", 2))
              .should(shouldListBuffer.toList)
              .minimumShouldMatch(1)
          }
赵威's avatar
赵威 committed
241
      }
赵威's avatar
赵威 committed
242 243 244 245 246 247 248 249 250 251
      .size(size)
      .sourceInclude(includes)
      .sortBy(
        FieldSort("_score").desc(),
        FieldSort("has_picture").desc(),
        FieldSort("smart_rank_v2").desc(),
        FieldSort("good_click").desc()
      )
    // println("answer query")
    // println(res.show)
赵威's avatar
赵威 committed
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
    res
  }

  def generateServiceDiaryRequest(
      projects: List[String],
      secondDemands: List[String],
      cityId: Int = -1
  ): SearchRequest = {
    val size = 15
    val includes = List("id", "tags_v3")
    var shouldListBuffer: ListBuffer[Query] = ListBuffer.empty[Query]

    if (projects.size > 0) {
      shouldListBuffer += TermsQuery("tags_v3", projects)
    }
    if (secondDemands.size > 0) {
      shouldListBuffer += TermsQuery("second_demands", secondDemands)
    }
赵威's avatar
赵威 committed
270

赵威's avatar
赵威 committed
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
    val res = search("gm-dbmw-diary-read")
      .query {
        functionScoreQuery(
          )
          .functions(
            ScriptScore(
              "return (doc.containsKey('new_smr')&&doc['new_smr'].value>0?doc['new_smr'].value:0.0) * ((doc.containsKey('is_promote')&&doc['is_promote'].value?5.0:0.0)+(doc.containsKey('has_before_cover')&&doc['has_before_cover'].value?2.0:0.0) + (doc.containsKey('has_after_cover')&&doc['has_after_cover'].value?2.0:0.0)+(doc.containsKey('has_after_cover')&&doc['has_after_cover'].value?8.0:0.0))"
            ),
            WeightScore(1000000).filter(termQuery("doctor.hospital.city_tag_id", cityId)),
            WeightScore(1000000).filter(termQuery("service_nearby_city_tag_ids", cityId))
          )
          .scoreMode(FunctionScoreQueryScoreMode.Sum)
          .boostMode(CombineFunction.Sum)
          .query {
            boolQuery()
              .must(
                termQuery("is_online", true),
                termQuery("has_service", true),
                termQuery("service.is_promote", true),
                rangeQuery("content_level").gte(3)
              )
              .not(termQuery("show_by_index", 2), termQuery("doctor.hospital.id", "shyxylmryy2203"))
              .should(shouldListBuffer.toList)
              .minimumShouldMatch(1)
          }
      }
      .size(size)
      .sourceInclude(includes)
    // println("service diary query")
    // println(res.show)
赵威's avatar
赵威 committed
301
    res
赵威's avatar
赵威 committed
302
  }
赵威's avatar
赵威 committed
303
}