how to use more Like this query score to function score in Elasticsearch

75 views Asked by At

how to use "more Like this" query score to function score in Elasticsearch

    static FunctionScore mltFunctionScore(String text, Double weight, List<String> fields) {
        return new FunctionScore.Builder()
                .filter(new Query.Builder()
                        .moreLikeThis(new MoreLikeThisQuery.Builder()
                            .fields(fields)
                            .like(new Like.Builder().text(text).build())
                            .build())
                        .build())
                .weight(weight)
                .build();
    }

Using a function score will only use the "more like this" query as a filter.

Can I get the same score as the one from the match query and use it as a function score?

1

There are 1 answers

2
Jeyhun Rashidov On

If you want to utilize the score from the MLT query in your function score, you should not use it as a filter.

If I understand your question correctly this query should handle your problem:

{
  "query": {
    "function_score": {
      "query": {
        "more_like_this": {
          "fields": ["your_field_name"],
          "like": "Your text here",
          "min_term_freq": 1
        }
      },
      "functions": [
        {
          "weight": 2
        }
      ],
      "boost_mode": "multiply"
    }
  }
}

In Java it should be:

FunctionScore functionScore = new FunctionScore.Builder()
    .query(new Query.Builder()
        .moreLikeThis(new MoreLikeThisQuery.Builder()
            .fields(fields)
            .like(new Like.Builder().text(text).build())
            .build())
        .build())
    .addFunction(new WeightFunction.Builder().weight(weight).build())
    .boostMode(CombineFunction.MULTIPLY)
    .build();

if you faced with an error you need to modify codes, because i don't have chance to test codes.