Jakkwylde
Jakkwylde

Reputation: 1302

Leveraging NEST for ES FunctionScore with variable number of functions

Leveraging the 0.12 release of NEST I need to build in support via the function score API to have a variable number of function parameters in my c# application such as defined below. Based on the current shape of the API I cannot find a way to conditionally add functions or pass a raw array of function items to the query descriptor objects. Is there a different approach to accomplish this evident in 0.12?

bool useFunctionScoreForCreatedDate = true;
bool useFunctionScoreForAge = true;

var s = new SearchDescriptor<ExampleDataObject>().From(0).Size(10)
  .Query(aa => aa
   .FunctionScore(fs => fs
       .Query(qq => qq.MatchAll())
       .Functions(
        // need to conditionally add this function score to the FunctionScoreFunction[] if useFunctionScoreForCreatedDate
        f => f.Linear(x => x.createddate, d => d.Scale("0d")),
       // need to conditionally add this function score to the FunctionScoreFunction[] if useFunctionScoreForAge
        f => f.Exp(x => x.age, d => d.Scale("0.5")),
        f => f.BoostFactor(2)
       )
      .ScoreMode(FunctionScoreMode.sum)
     )
).Fields(x => x.title);

Upvotes: 1

Views: 1047

Answers (1)

Paige Cook
Paige Cook

Reputation: 22555

Looks like the .Functions() method with .FunctionScore() accepts a FunctionScoreFunctionsDescriptor<> object. So you should be able to use something similar to the following...

 bool useFunctionScoreForCreatedDate = true;
 bool useFunctionScoreForAge = true;

 var fsFunctionsDescriptor = new FunctionScoreFunctionsDescriptor<ExampleDataObject();
 if (useFunctionsScoreForCreatedDate)
 {
      fsFunctionsDescriptor.Linear(x => x.createdate, d => d.Scale("0d"));
 }

 if (useFunctionScoreForAge) 
 {
      fsFunctionsDescriptor.Exp( x => x.age, d => d.Scale("0.5"));
 }
 fsFunctionsDescriptor.BoostFactor(2);

 var s = new SearchDescriptor<ExampleDataObject>().From(0).Size(10)
   .Query(aa => aa
   .FunctionScore(fs => fs
       .Query(qq => qq.MatchAll())
       .Functions(fsFunctionsDescriptor)
       .ScoreMode(FunctionScoreMode.sum)
     )
 ).Fields(x => x.title);

Upvotes: 1

Related Questions