Java API中脚本分数和功能分数过滤器的组合

时间:2019-02-26 16:24:02

标签: java elasticsearch search filter scoring

我找不到如何在弹性Java API中结合脚本分数和函数分数过滤器的选项。

我有以下查询:

GET index/type/_search
{
  "query": {
    "nested": {
      "path": "field",
      "query": {
        "function_score": {
          "query": {
            "bool": {
              "must": [
                {
                  "match": {
                    "field.name": "NAME"
                  }
                }
              ]
            }
          },
          "functions": [
            {
              "filter": {
                "match": {
                  "field.type":"TYPE"
                }
              },
              "weight": 3
            },
            {
              "script_score": {
                 "script":"doc['field.count'].value"
              }
            }
          ]
        }
      }
    }
  }
}

并尝试编写ElasticSearchQuery

ElasticSearchQuery query = new ElasticSearchQuery(Indexes.NAME, Types.TYPE)
            .setQueryBuilder(QueryBuilders.nestedQuery(FIELD, QueryBuilders.functionScoreQuery(
                    QueryBuilders.boolQuery().must(QueryBuilders.matchQuery(FIELD_NAME, fieldName)),
                    new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                            new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                    QueryBuilders.matchQuery(FIELD_TYPE, fieldType),
                                    ScoreFunctionBuilders.weightFactorFunction(3.0F)
                            )
                    }), ScoreMode.None));

但是如何添加脚本分数?

1 个答案:

答案 0 :(得分:0)

解决方案非常简单:

FunctionScoreQueryBuilder.FilterFunctionBuilder[] filterFunctionBuilders = new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                        QueryBuilders.matchQuery(FIELD_TYPE, fieldType),
                        ScoreFunctionBuilders.weightFactorFunction(3)
                ),
                new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                        ScoreFunctionBuilders.scriptFunction(format("doc['%s'].value", FIELD_COUNT))
                )
        };