如何使用.NET NEST Client在功能分数查询中创建过滤器

时间:2018-12-04 09:08:53

标签: c# .net elasticsearch nest elasticsearch.net

In Elasticsearch Document关于功能得分查询显示代码的说明如下

GET /_search
{
    "query": {
        "function_score": {
          "query": { "match_all": {} },
          "boost": "5", 
          "functions": [
              {
                  "filter": { "match": { "test": "bar" } },
                  "random_score": {}, 
                  "weight": 23
              },
              {
                  "filter": { "match": { "test": "cat" } },
                  "weight": 42
              }
          ],
          "max_boost": 42,
          "score_mode": "max",
          "boost_mode": "multiply",
          "min_score" : 42
        }
    }
}

我将此查询写到object initializer syntax

var searchRequest = new SearchRequest<ProductType>
{
   Query = new FunctionScoreQuery()
   {
      Query = new MatchAllQuery {},
      Boost = 5,
      Functions = new List<IScoreFunction>
      {
         Filters...?
      },
      MaxBoost = 42,
      ScoreMode = FunctionScoreMode.Max,
      BoostMode = FunctionBoostMode.Max,
      MinScore = 42
   }
};

如何在函数中构建过滤器?

IScoreFunction界面仅允许ExponentialDecayFunctionGaussDateDecayFunctionLinearGeoDecayFunctionFieldValueFactorFunctionRandomScoreFunctionWeightFunction,{{ 1}}

1 个答案:

答案 0 :(得分:1)

Functions是IScoreFunction的集合。在示例JSON中,第一个函数是随机得分函数,第二个函数是权重函数。链接的Query DSL示例包含不同功能的示例,这是与上面的JSON匹配的示例

var client = new ElasticClient();

var searchRequest = new SearchRequest<ProductType>
{
    Query = new FunctionScoreQuery()
    {
        Query = new MatchAllQuery { },
        Boost = 5,
        Functions = new List<IScoreFunction>
        {
            new RandomScoreFunction
            {
                Filter = new MatchQuery
                {
                    Field = "test",
                    Query = "bar"
                },
                Weight = 23
            },
            new WeightFunction
            {
                Filter = new MatchQuery
                {
                    Field = "test",
                    Query = "cat"
                },
                Weight = 42
            }
        },
        MaxBoost = 42,
        ScoreMode = FunctionScoreMode.Max,
        BoostMode = FunctionBoostMode.Multiply,
        MinScore = 42
    }
};

var searchResponse = client.Search<ProductType>(searchRequest);