elasticsearch 自定义 script score JavaAPI查询

一:自定义score的应用场景

        先打个比方,比如新产品上架了,我想让最新上架的产品搜索时候,排在前面,怎么办呢?很简单按时间排序。嗯这种方法很好实现。

但下面又有个需求,比如我要求排序中上架时间的比重为40%,自营产品为20%,促销产品的比重为40%,这怎么排序呢?单单靠排序估计很难实现。(不排除有些大神可以实现哈)。下面就介绍一个简单的实现方法,自定义score

二:自定义score的官方介绍见下面链接,大家有兴趣的可以看看哈

https://www.elastic.co/guide/en/elasticsearch/reference/5.1/query-dsl-function-score-query.html

"script_score": {
    "script": {
        "lang": "painless",
        "params": {
            "param1": value1,
            "param2": value2
        },
        "inline": "_score * doc['my_numeric_field'].value / Math.pow(params.param1, params.param2)"
    }
}
三 : Java API实现自定义score

     3.1:自定义field score

         TransportClient client =TransportClient.builder().settings(Settings.EMPTY).build()
                   .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));
        // QueryBuilder queryBuilder = QueryBuilders.functionScoreQuery().scoreMode(scoreMode)
        SearchResponse scrollResponse = client.prepareSearch("testproduct")
            //.addSort("price", SortOrder.DESC)
            .setSearchType(SearchType.SCAN).setSize(10000).setScroll(TimeValue.timeValueMinutes(1))
            .setQuery(functionScoreQuery(QueryBuilders.matchPhraseQuery("title", "美白洗面奶"), fieldValueFactorFunction("pop").modifier(FieldValueFactorFunction.Modifier.SQRT)))
            .execute().actionGet();  
        long count = scrollResponse.getHits().getTotalHits();//第一次不返回数据
        for(int i=0,sum=0; sum<count; i++){
            scrollResponse = client.prepareSearchScroll(scrollResponse.getScrollId())  
                .setScroll(TimeValue.timeValueMinutes(8))  
            .execute().actionGet();
            sum += scrollResponse.getHits().hits().length;
            System.out.println("总量"+count+" 已经查到"+sum);
            SearchHit[] hits = scrollResponse.getHits().getHits();
           for(int j =0;j<hits.length;j++){
               System.out.println(hits[j].getSourceAsString());
               System.out.println(hits[j].getScore());
           }
           // System.out.println(hits[0].getSourceAsString());
          
        }


    3.2:自定义的script score java API


      在elasticsearch.yml配置中增加如下配置

      script.inline: on  
      script.indexed: on
      script.engine.groovy.inline.aggs: on

   private static void fromSize() throws UnknownHostException, ParseException {
        Map<String, Object> params = new HashMap<>();
        params.put("num1", 1);
        params.put("num2", 2);
        String f = "2016-12-15";
        SimpleDateFormat dateForamt = new SimpleDateFormat("yyyy-mm-dd");
        long timeNow =dateForamt.parse(f).getTime() ;
        System.out.println(timeNow);
        String inlineScript = "diff="+timeNow+"-doc['regit'].value;"
                             + "return (diff/ (24 * 60 * 60 * 1000))";
        Script script = new Script(inlineScript, ScriptType.INLINE, "groovy", params);
        ScriptScoreFunctionBuilder scriptBuilder = ScoreFunctionBuilders.scriptFunction(script);
        TransportClient client =TransportClient.builder().build()
                   .addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("LOCALHOST"), 9300));
        long count = client.prepareCount("dateproduct").setTypes("product").execute().actionGet().getCount();
        SearchRequestBuilder requestBuilder = client.prepareSearch("dateproduct")
                .setTypes("product")
                 .setQuery(functionScoreQuery(QueryBuilders.matchPhraseQuery("title", "美白洗面奶"),scriptBuilder));
        SearchResponse response = requestBuilder.setFrom(0).setSize(5).execute().actionGet();
        long  sum = response.getHits().hits().length;
        System.out.println("总量"+count+" 已经查到"+sum);
        SearchHit[] hits = response.getHits().getHits();
         for(int j =0;j<hits.length;j++){
             System.out.println(hits[j].getSourceAsString());
             System.out.println(hits[j].getScore());
         }
        
    }
   




  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值