elasticsearch nest support of filters in functionscore function

我的未来我决定 提交于 2019-12-04 10:42:41

It's already implemented:

_client.Search<ElasticsearchProject>(s => 
            s.Query(q=>q
                .FunctionScore(fs=>fs.Functions(
                    f=>f
                        .ScriptScore(ss=>ss.Script("25"))
                        .Filter(ff=>ff.Term(t=>t.Country, "A")),
                    f=> f
                        .ScriptScore(ss=>ss.Script("15"))
                        .Filter(ff=>ff.Term("a","b")))
                .ScoreMode(FunctionScoreMode.first)
                .BoostMode(FunctionBoostMode.sum))));

The Udi's answer didn't work for me. It seems that in new version (v 2.3, C#) there's no Filter() method on ScoreFunctionsDescriptor class.

But I found a solution. You can provide an array of IScoreFunction. To do that you can use new FunctionScoreFunction() or use my helper class:

class CustomFunctionScore<T> : FunctionScoreFunction
    where T: class
{
    public CustomFunctionScore(Func<QueryContainerDescriptor<T>, QueryContainer> selector, double? weight = null)
    {
        this.Filter = selector.Invoke(new QueryContainerDescriptor<T>());
        this.Weight = weight;
    }
}

With this class, filter can be applied this way (this is just an example):

        SearchDescriptor<BlobPost> searchDescriptor = new SearchDescriptor<BlobPost>()
            .Query(qr => qr
                .FunctionScore(fs => fs
                    .Query(q => q.Bool(b => b.Should(s => s.Match(a => a.Field(f => f.FirstName).Query("john")))))
                    .ScoreMode(FunctionScoreMode.Max)
                    .BoostMode(FunctionBoostMode.Sum)
                    .Functions(
                        new[] 
                        {
                            new CustomFunctionScore<BlobPost>(q => q.Match(a => a.Field(f => f.Id).Query("my_id")), 10),
                            new CustomFunctionScore<BlobPost>(q => q.Match(a => a.Field(f => f.FirstName).Query("john")), 10),
                        }
                    )
                )
            );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!