欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

elasticsearch FunctionScore Java API sample

程序员文章站 2022-07-14 12:40:15
...
public Response<List<Book>> fieldValueFactor(String query) {
        // query
        MultiMatchQueryBuilder multiMatchQueryBuilder = new MultiMatchQueryBuilder(query)
                .field(Constants.TITLE).field(Constants.SUMMARY);
        // fieldValueFactor
        FieldValueFactorFunctionBuilder fieldValueFactor = ScoreFunctionBuilders.fieldValueFactorFunction(Constants.NUM_REVIEWS)
                .factor(2).modifier(FieldValueFactorFunction.Modifier.LOG1P);
        // functionscore
        FunctionScoreQueryBuilder queryBuilder = QueryBuilders.functionScoreQuery(multiMatchQueryBuilder, fieldValueFactor);

        SearchRequestBuilder requestBuilder = client.prepareSearch(bookIndex).setTypes(bookType)
                .setQuery(queryBuilder).setFetchSource(Constants.fetchFieldsTSPN, null);
    }

script_score,通过脚本进行自定义打分

        // 参数
        Map<String, Object> params = new HashMap<>();
        params.put("threshold", threshold);
        //painless 脚本,注意不能换行
        String scriptStr = "publish_date = doc['publish_date'].value; num_reviews = doc['num_reviews'].value; if (publish_date > Date.parse('yyyy-MM-dd', threshold).getTime()) { return log(2.5 + num_reviews) }; return log(1 + num_reviews);";
        Script script = new Script(ScriptType.INLINE, "painless", scriptStr, params);

        //构造脚本查询对象
        ScriptScoreFunctionBuilder scriptScoreFunctionBuilder = ScoreFunctionBuilders.scriptFunction(script);

        //组合成完整查询
        FunctionScoreQueryBuilder queryBuilder = QueryBuilders.functionScoreQuery(multiMatchQueryBuilder, scriptScoreFunctionBuilder);