利用NEST为ES FunctionScore提供可变数量的函数

时间:2014-03-04 21:37:45

标签: c# elasticsearch nest

利用NEST的0.12版本,我需要通过功能评分API构建支持,以便在我的c#应用程序中拥有可变数量的函数参数,如下所述。根据API的当前形状,我找不到有条件地添加函数或将原始数组函数项传递给查询描述符对象的方法。是否有不同的方法可以在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);

1 个答案:

答案 0 :(得分:1)

.Functions()方法看起来.FunctionScore()方法接受FunctionScoreFunctionsDescriptor<>个对象。所以你应该能够使用类似下面的东西...

 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);