elasticsearch 自定义 script score JavaAPI查询

来源:互联网 发布:黄金交易行情软件 编辑:程序博客网 时间:2024/06/05 05:19

一:自定义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());         }            }
   




1 0
原创粉丝点击